本文我们通过利用Tensorflow实现线性回归简单demo,来了解tensorflow的简单使用
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
# 使用 NumPy 生成假数据(phony data), 总共 100 个点.
x_data = np.float32(np.random.rand(2, 100)) # 随机输入
y_data = x_data * 0.1 + 0.300
# 构造一个线性模型
#
b = tf.Variable(tf.zeros([1]))
W = tf.Variable(tf.random_uniform([1], -1.0, 1.0))
y = W * x_data + b
# 最小化方差
loss = tf.reduce_mean(tf.square(y - y_data))
optimizer = tf.train.GradientDescentOptimizer(0.5)
train = optimizer.minimize(loss)
# 初始化变量
init = tf.initialize_all_variables()
# 启动图 (graph)
sess = tf.Session()
sess.run(init)
# 拟合平面
for step in range(0, 201):
sess.run(train)
if step % 20 == 0:
print (step, sess.run(W), sess.run(b))
plt.plot(x_data, y_data, 'ro')
plt.plot(x_data, sess.run(W) * x_data + sess.run(b))
plt.legend()
plt.show()
结果为:
0 [ 0.44483739] [ 0.15947637]
20 [ 0.18209828] [ 0.25776637]
40 [ 0.12043458] [ 0.2894879]
60 [ 0.10508627] [ 0.29738349]
80 [ 0.10126598] [ 0.29934874]
100 [ 0.10031512] [ 0.29983792]
120 [ 0.10007843] [ 0.29995966]
140 [ 0.10001951] [ 0.29998997]
160 [ 0.10000486] [ 0.29999751]
180 [ 0.10000122] [ 0.29999939]
200 [ 0.10000031] [ 0.29999986]