给定x和y,y=a*x+b,用梯度下降法计算a和b的值
import tensorflow as tf
import numpy as np
x_data = np.random.rand(100).astype(np.float32)
y_data = x_data*0.1+0.3
Weights = tf.Variable(tf.random_uniform([1], -1.0, 1.0))
biases = tf.Variable(tf.zeros([1]))
y = x_data*Weights + biases
loss = tf.reduce_mean(tf.square(y-y_data))
optimizer = tf.train.GradientDescentOptimizer(0.5)
train = optimizer.minimize(loss)
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)
for step in range(200):
sess.run(train)
if step%20 == 0:
print(step, sess.run(Weights), sess.run(biases))
0 [ 0.22152893] [ 0.23289981]
20 [ 0.12997523] [ 0.28617936]
40 [ 0.10714599] [ 0.29670522]
60 [ 0.10170358] [ 0.29921454]
80 [ 0.10040613] [ 0.29981276]
100 [ 0.10009683] [ 0.29995537]
120 [ 0.10002309] [ 0.29998937]
140 [ 0.10000551] [ 0.29999748]
160 [ 0.10000131] [ 0.29999942]
180 [ 0.10000031] [ 0.29999986]