Tensorflow学习2:线性回归

1
2
3
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#使用numpy生成100个随机点
#y_data = 3*x_data

x_data = []
y_data = []

for i in range(100):
x_data.append(np.random.normal(0.0, 0.5))
y_data.append( x_data[i]*0.2 + 0.3 + np.random.normal(0,0.03) )

#构建一个线性模型
b = tf.Variable(0.)
k = tf.Variable(0.)
y = k*x_data + b

#均方误差作为损失函数
loss = tf.reduce_mean(tf.square(y - y_data))
#定义一个梯度下降优化器
optimizer = tf.train.GradientDescentOptimizer(0.2)
#最小化损失函数
train = optimizer.minimize(loss)

init = tf.global_variables_initializer()

with tf.Session() as sess:
sess.run(init)
for step in range(40):
sess.run(train)
if step%4 == 0:
# print(sess.run([k,b]))
y_predict = sess.run(y)
plt.plot(x_data, y_predict, color="red", lw=3)
plt.scatter(x_data, y_data, color="blue")
plt.show()

总结:
1 数值0 用0.表示当作float
2 训练目标变量用tf.Variable,其他的用numpy普通变量

꧁༺The༒End༻꧂