TensorFlow 实现简单线性回归
程序员文章站
2024-03-23 13:16:22
...
import tensorflow as tf
import numpy as np
import random
#create data
x_data = np.random.rand(100).astype(np.float32) # 使用numpy生成100个随机点
noise = np.random.normal(loc=0, scale=0.005, size=x_data.shape) # 生成标准正态分布
y_data = x_data*0.1+0.3 + noise
# 搭建模型
weights = tf.Variable(tf.random_uniform([1], -1.0, 1.0)) #[1]表示张量形状
bias = tf.Variable(tf.zeros([1])) # [1]表示张量形状
y = weights*x_data + bias
# 计算误差
loss = tf.reduce_mean(tf.square(y-y_data)) # 均方误差MSE
# 传播误差
# 反向传播由optimizer完成,可以用梯度下降进行参数更新
optimizer = tf.train.GradientDescentOptimizer(0.5)
train = optimizer.minimize(loss)
# 训练
# 首先初始化所有变量
init = tf.global_variables_initializer()
# 创建会话session
sess = tf.Session()
sess.run(init) # 用session来执行init初始化步骤
for step in range(201): # 201是迭代次数
sess.run(train) # 用session来run每次training的数据
if step%20 == 0: # 每20步打印一下训练信息
print(step, sess.run(weights), sess.run(bias))
0 [0.5786313] [0.04093613]
20 [0.22345346] [0.23119761]
40 [0.13341352] [0.28108537]
60 [0.11040851] [0.2938316]
80 [0.10453079] [0.2970882]
100 [0.10302906] [0.2979203]
120 [0.10264537] [0.29813287]
140 [0.1025473] [0.2981872]
160 [0.10252227] [0.29820108]
180 [0.10251586] [0.29820463]
200 [0.10251423] [0.29820552]
# 把随机在坐标轴中打印出来
plt.xlabel("x")
plt.ylabel("y")
plt.title("Linear Regression")
plt.scatter(x_data, y_data)
# 用最终训练的模型输出结果,在图上显示
plt.plot(x_data, sess.run(weights) * x_data + sess.run(bias),'r--' , label='拟合数据')
plt.show()