一个简单的线性回归的例子,可以可视化回归过程
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
N=500
y_point=[]
x_point=[]
a=0.22
b=0.62
for i in range(N):
x=np.random.normal(0.0,0.5)
y=a*x+b+np.random.normal(0.0,0.1)
x_point.append(x)
y_point.append(y)
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.plot(x_point, y_point,'o')
plt.ion()
plt.legend()
plt.show()
A=tf.Variable(tf.random_uniform([1], -1.0, 1.0, dtype=tf.float32))
B=tf.Variable(tf.zeros([1], dtype=tf.float32))
y_out=A*x_point+B
cost_function=tf.reduce_mean(tf.square(y_out-y_point))
optimizer = tf.train.GradientDescentOptimizer(0.5)
train=optimizer.minimize(cost_function)
model=tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(model)
for step in range(21):
sess.run(train)
if step%5==0:
# plt.plot(x_point,y_point,'o',label="step={}".format(step))
try:
ax.lines.remove(lines[0])
except Exception:
pass
lines=ax.plot(x_point,sess.run(A)*x_point+sess.run(B),'r-', lw=5)
plt.pause(1)
plt.pause(100)
效果