目标:利用tensorflow实现线性关系的训练
import tensorflow as tf
import numpy as np
x_data=np.random.rand(100)#获取100个随机值
y_data=0.1*x_data+0.2#令y=0.1x+0.2
#初始化b,k,y
b=tf.Variable(0.)
k=tf.Variable(0.)
y=k*x_data+b
loss=tf.reduce_mean(tf.square(y_data-y))#定义代价函数
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(201):
sess.run(train)
if step%20 == 0:
print(step,sess.run([k,b]))
结果:
0 [0.04952874, 0.09861456]
20 [0.10020342, 0.19989765]
40 [0.10011184, 0.19994381]
60 [0.10006148, 0.19996911]
80 [0.1000338, 0.19998302]
100 [0.10001856, 0.19999067]
120 [0.1000102, 0.19999488]
140 [0.100005604, 0.19999719]
160 [0.10000309, 0.19999844]
180 [0.10000171, 0.19999915]
200 [0.10000095, 0.19999951]