使用TensorFlow实现简单的线性回归(LinearRegression)

来源:互联网 发布:网络语言翻译文言文 编辑:程序博客网 时间:2024/05/18 09:20

线性模型基本形式 :

  • 线性回归属于回归算法,表达监督学习的过程。通过属性的线性组合来预测函数:
    f(x)=w1x1+w2x2+...+wdxd+b
  • 一般向量形式写成:
    f(x)=wTx+b
  • 其中的 w=(w1;w2;...;wd).wb学的后模型就可以确定
  • 线性回归的目标是找到一个与这些数据最为吻合的线性函数,用来预测或者分类,主要解决线性问题

使用TensorFlow实现简单的线性回归:

  • 在TensorFlow中进行线性回归处理重点是将样本和样本特征矩阵化

    1. 定义用于显示图画的长和宽产出样本点个个数。linspace在X -3 到 3 的位置产出100个样本点.使用np.random增加扰动使用scatter做散点绘制show展示图像

      plt.rcParams["figure.figsize"] = (12, 6)n_observations = 200xs = np.linspace(-3, 3, n_observations)ys = np.sin(xs) + np.random.uniform(-0.5, 0.5, n_observations)plt.scatter(xs, ys)plt.show()
    2. 准备好placeholder容器往模型添加tf.placeholder:用于得到传递进来的真实的训练样本:声明时,必须提供初始值;名称的真实含义,在于变量,也即在真实训练时,其值是会改变的,自然事先需要指定初始值

      X = tf.placeholder(tf.float32, name='X_placeholder')Y = tf.placeholder(tf.float32, name='Y_placeholder')
    3. tf.Variable:主要在于一些可训练变量(trainable variables),比如模型的权重或者偏执值,不必指定初始值,可在运行时,通过 Session.run 的函数的 feed_dict 参数指定; 这也是其命名的原因所在,仅仅作为一种占位符;

      W = tf.Variable(tf.random_normal([1]), name='weight')b = tf.Variable(tf.random_normal([1]), name='bias')
    4. 计算预算结果,先做一次向,再增加高次项

      Y_pred = tf.add(tf.multiply(X, W), b)W_2 = tf.Variable(tf.random_normal([1]), name='weight_1')Y_pred = tf.add(tf.multiply(tf.pow(X, 2), W_2), Y_pred)W_3 = tf.Variable(tf.random_normal([1]), name='weight_2')Y_pred = tf.add(tf.multiply(tf.pow(X, 3), W_3), Y_pred)sample_num = xs.shape[0]
    5. 计算损失函数值,对Y去做差值后求平方设置步进值,凸函数可以用梯度下降收敛到的局部最低点就是全局最低点初始化GradientDescentOptimizer对象去执行op>minimize运算会对loss做一个最小化,但是如果是神经网络就不能使用GradientDescentOptimizer因为会降到最低点

      loss = tf.reduce_sum(tf.pow(Y_pred - Y, 2)) / sample_numlearning_rate = 0.01optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss)n_samples = xs.shape[0]
    6. 指定迭代的次数,并在Session里执行graph,显示参数的更新

      n_samples = xs.shape[0]with tf.Session() as sess:sess.run(tf.global_variables_initializer()) writer = tf.summary.FileWriter('./graphs/polynomial_reg', sess.graph)for i in range(1000):    total_loss = 0    for x, y in zip(xs, ys):        _, l = sess.run([optimizer, loss], feed_dict={X: x, Y:y})         total_loss += l    if i%20 ==0:        print('Epoch {0}: {1}'.format(i, total_loss/n_samples))writer.close()W, W_2, W_3, b = sess.run([W, W_2, W_3, b])
    7. 绘制可视化图形

      plt.plot(xs, ys, 'bo', label='Real data')plt.plot(xs, xs * W + np.power(xs, 2) * W_2 + np.power(xs, 3) * W_3 + b, 'r', label='Predicted data')plt.legend()plt.show()

    运行结果
    这里写图片描述

阅读全文
0 0
原创粉丝点击