TensorFlow 实现线性回归
1、生成高斯分布的随机数
导入numpy模块,通过numpy模块内的方法生成一组在方程
y = 2 * x + 3
周围小幅波动的随机坐标。代码如下:
1 import numpy as np 2 import matplotlib.pyplot as plot 3 4 5 def getRandomPoints(count): 6 xList = [] 7 yList = [] 8 for i in range(count): 9 x = np.random.normal(0, 0.5) 10 y = 2 * x + 3 + np.random.normal(0, 0.3) 11 xList.append(x) 12 yList.append(y) 13 return xList, yList 14 15 16 if __name__ == '__main__': 17 X, Y = getRandomPoints(1000) 18 plot.scatter(X, Y) 19 plot.show()
运行上述代码,输出图形如下:
2、采用TensorFlow来获取上述方程的系数
首先搭建基本的预估模型y = w * x + b,然后再采用梯度下降法进行训练,通过最小化损失函数的方法进行优化,最终训练得出方程的系数。
在下面的例子中,梯度下降法的学习率为0.2,训练迭代次数为100次。
1 def train(x, y): 2 # 生成随机系数 3 w = tf.Variable(tf.random_uniform([1], -1, 1)) 4 # 生成随机截距 5 b = tf.Variable(tf.random_uniform([1], -1, 1)) 6 # 预估值 7 preY = w * x + b 8 9 # 损失值:预估值与实际值之间的均方差10 loss = tf.reduce_mean(tf.square(preY - y)) 11 # 优化器:梯度下降法,学习率为0.212 optimizer = tf.train.GradientDescentOptimizer(0.2)