本文介绍如何用TensorFlow求简单的线性回归问题。
- 生成训练数据
import tensorflow as tf
import numpy as np
# Create 100 phony x, y data points in NumPy, y = x * 0.1 + 0.3
x_data = np.random.rand(100).astype(np.float32)
y_data = x_data * 0.1 + 0.3
- 创建数据流图
# Try to find values for W and b that compute y_data = W * x_data + b
# (We know that W should be 0.1 and b 0.3, but TensorFlow will
# figure that out for us.)
W = tf.Variable(tf.random_uniform([1], -1.0, 1.0))
b = tf.Variable(tf.zeros([1]))
y = W * x_data + b
- 设计目标函数
# Minimize the mean squared errors.
loss = tf.reduce_mean(tf.square(y - y_data))
- 选择训练算法(梯度下降)
optimizer = tf.train.GradientDescentOptimizer(0.5)
train = optimizer.minimize(loss)
- 创建TensorFlow的Session,初始化
# Before starting, initialize the variables. We will 'run' this first.
init = tf.global_variables_initializer()
# Launch the graph.
sess = tf.Session()
sess.run(init)
- 开始训练过程
# Fit the line.
for step in range(201):
sess.run(train)
if step % 20 == 0:
print(step, sess.run(W), sess.run(b))
# Learns best fit is W: [0.1], b: [0.3]
- 运行结果
(0, array([ 0.40007937], dtype=float32), array([ 0.18186936], dtype=float32))
(20, array([ 0.16719148], dtype=float32), array([ 0.26199135], dtype=float32))
(40, array([ 0.11624231], dtype=float32), array([ 0.2908121], dtype=float32))
(60, array([ 0.10392629], dtype=float32), array([ 0.29777899], dtype=float32))
(80, array([ 0.1009491], dtype=float32), array([ 0.29946312], dtype=float32))
(100, array([ 0.10022942], dtype=float32), array([ 0.29987025], dtype=float32))
(120, array([ 0.10005546], dtype=float32), array([ 0.29996863], dtype=float32))
(140, array([ 0.10001341], dtype=float32), array([ 0.29999244], dtype=float32))
(160, array([ 0.10000324], dtype=float32), array([ 0.29999819], dtype=float32))
(180, array([ 0.10000078], dtype=float32), array([ 0.29999956], dtype=float32))
(200, array([ 0.1000002], dtype=float32), array([ 0.29999989], dtype=float32))