利用tensorflow 实现线性回归简单例子。
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
num_points = 1000
vector_set = []
for i in range(num_points):
x = np.random.normal(0.0, 0.5)
y = x * 0.1 + 0.3 + np.random.normal(0.0, 0.03)
vector_set.append([x, y])
x_data = [v[0] for v in vector_set]
y_data = [v[1] for v in vector_set]
plt.scatter(x_data, y_data, c='g')
plt.show()
W = tf.Variable(tf.random_uniform([1], -1.0, 1.0), name='W')
b = tf.Variable(tf.zeros([1]), name='b')
y = W * x_data + b
loss = tf.reduce_mean(tf.square(y - y_data), name='loss')
optimizer = tf.train.GradientDescentOptimizer(0.5)
train = optimizer.minimize(loss, name='train')
sess = tf.Session()
init = tf.global_variables_initializer()
sess.run(init)
print ("W=", sess.run(W), "b=", sess.run(b), "loss=", sess.run(loss))
for i in range(200):
sess.run(train)
print ("W=", sess.run(W), "b=", sess.run(b), "loss=", sess.run(loss))