TensorFlow 实现线性回归

时间:2023-03-10 07:00:24
TensorFlow 实现线性回归

1、生成高斯分布的随机数

导入numpy模块,通过numpy模块内的方法生成一组在方程

y = 2 * x + 3

周围小幅波动的随机坐标。代码如下:

 import numpy as np
import matplotlib.pyplot as plot def getRandomPoints(count):
xList = []
yList = []
for i in range(count):
x = np.random.normal(0, 0.5)
y = 2 * x + 3 + np.random.normal(0, 0.3)
xList.append(x)
yList.append(y)
return xList, yList if __name__ == '__main__':
X, Y = getRandomPoints(1000)
plot.scatter(X, Y)
plot.show()

运行上述代码,输出图形如下:

TensorFlow 实现线性回归

2、采用TensorFlow来获取上述方程的系数

  首先搭建基本的预估模型y = w * x + b,然后再采用梯度下降法进行训练,通过最小化损失函数的方法进行优化,最终训练得出方程的系数。

  在下面的例子中,梯度下降法的学习率为0.2,训练迭代次数为100次。

 def train(x, y):
# 生成随机系数
w = tf.Variable(tf.random_uniform([1], -1, 1))
# 生成随机截距
b = tf.Variable(tf.random_uniform([1], -1, 1))
# 预估值
preY = w * x + b # 损失值:预估值与实际值之间的均方差
loss = tf.reduce_mean(tf.square(preY - y))
# 优化器:梯度下降法,学习率为0.2
optimizer = tf.train.GradientDescentOptimizer(0.2)
# 训练:最小化损失函数
trainer = optimizer.minimize(loss) with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
# 打印初始随机系数
print('init w:', sess.run(w), 'b:', sess.run(b))
# 先训练个100次:
for i in range(100):
sess.run(trainer)
# 每10次打印下系数
if i % 10 == 9:
print('w:', sess.run(w), 'b:', sess.run(b)) if __name__ == '__main__':
X, Y = getRandomPoints(1000)
train(X, Y)

  运行上面的代码,某次的最终结果为:

w = 1.9738449
b = 3.0027733

仅100次的训练迭代,得出的结果已十分接近方程的实际系数。

  某次模拟训练中的输出结果如下:

init w: [-0.6468966] b: [0.52244043]
w: [1.0336646] b: [2.9878206]
w: [1.636582] b: [3.0026987]
w: [1.8528996] b: [3.0027785]
w: [1.930511] b: [3.0027752]
w: [1.9583567] b: [3.0027738]
w: [1.9683474] b: [3.0027735]
w: [1.9719319] b: [3.0027733]
w: [1.9732181] b: [3.0027733]
w: [1.9736794] b: [3.0027733]
w: [1.9738449] b: [3.0027733]

3、完整代码和结果

完整测试代码:

 import numpy as np
import matplotlib.pyplot as plot
import tensorflow as tf def getRandomPoints(count, xscale=0.5, yscale=0.3):
xList = []
yList = []
for i in range(count):
x = np.random.normal(0, xscale)
y = 2 * x + 3 + np.random.normal(0, yscale)
xList.append(x)
yList.append(y)
return xList, yList def train(x, y, learnrate=0.2, cycle=100):
# 生成随机系数
w = tf.Variable(tf.random_uniform([1], -1, 1))
# 生成随机截距
b = tf.Variable(tf.random_uniform([1], -1, 1))
# 预估值
preY = w * x + b # 损失值:预估值与实际值之间的均方差
loss = tf.reduce_mean(tf.square(preY - y))
# 优化器:梯度下降法
optimizer = tf.train.GradientDescentOptimizer(learnrate)
# 训练:最小化损失函数
trainer = optimizer.minimize(loss) with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
# 打印初始随机系数
print('init w:', sess.run(w), 'b:', sess.run(b))
for i in range(cycle):
sess.run(trainer)
# 每10次打印下系数
if i % 10 == 9:
print('w:', sess.run(w), 'b:', sess.run(b))
return sess.run(w), sess.run(b) if __name__ == '__main__':
X, Y = getRandomPoints(1000)
w, b = train(X, Y)
plot.scatter(X, Y)
plot.plot(X, w * X + b, c='r')
plot.show()

  最终效果图如下,蓝色为高斯随机分布数据,红色为最终得出的直线:

TensorFlow 实现线性回归

本文地址:https://www.cnblogs.com/laishenghao/p/9571343.html