本文实例为大家分享了tensorflow实现线性回归的具体代码,供大家参考,具体内容如下
一、随机生成1000个点,分布在y=0.1x+0.3直线周围,并画出来
import tensorflow as tf import numpy as np import matplotlib.pyplot as plt num_points = 1000 vectors_set = [] for i in range(num_points): x1 = np.random.normal(0.0,0.55) //设置一定范围的浮动 y1 = x1*0.1+0.3+np.random.normal(0.0,0.03) vectors_set.append([x1,y1]) x_data = [v[0] for v in vectors_set] y_data = [v[1] for v in vectors_set] plt.scatter(x_data,y_data,c='r') plt.show()
二、构造线性回归函数
#生成一维的w矩阵,取值为[-1,1]之间的随机数 w = tf.Variable(tf.random_uniform([1],-1.0,1.0),name='W') #生成一维的b矩阵,初始值为0 b = tf.Variable(tf.zeros([1]),name='b') y = w*x_data+b #均方误差 loss = tf.reduce_mean(tf.square(y-y_data),name='loss') #梯度下降 optimizer = tf.train.GradientDescentOptimizer(0.5) #最小化loss train = optimizer.minimize(loss,name='train') sess=tf.Session() init = tf.global_variables_initializer() sess.run(init) #print("W",sess.run(w),"b=",sess.run(b),"loss=",sess.run(loss)) for step in range(20): sess.run(train) print("W=",sess.run(w),"b=",sess.run(b),"loss=",sess.run(loss)) //显示拟合后的直线 plt.scatter(x_data,y_data,c='r') plt.plot(x_data,sess.run(w)*x_data+sess.run(b)) plt.show()
三、部分训练结果如下:
W= [ 0.10559751] b= [ 0.29925063] loss= 0.000887708 W= [ 0.10417549] b= [ 0.29926425] loss= 0.000884275 W= [ 0.10318361] b= [ 0.29927373] loss= 0.000882605 W= [ 0.10249177] b= [ 0.29928035] loss= 0.000881792 W= [ 0.10200921] b= [ 0.29928496] loss= 0.000881397 W= [ 0.10167261] b= [ 0.29928818] loss= 0.000881205 W= [ 0.10143784] b= [ 0.29929042] loss= 0.000881111 W= [ 0.10127408] b= [ 0.29929197] loss= 0.000881066
拟合后的直线如图所示:
结论:最终w趋近于0.1,b趋近于0.3,满足提前设定的数据分布
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。