- 代码
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
train_x = np.array([[3.3], [4.4], [5.5], [6.71], [6.93], [4.168], [9.779], [6.128],
[7.59], [2.167], [7.042], [10.791], [5.313], [7.997], [5.654],
[9.27], [3.1]])
train_y = np.array([[1.7], [2.76], [2.09], [3.19], [1.649], [1.573], [3.366],
[2.596], [2.53], [1.221], [2.827], [3.465], [1.65], [2.904],
[2.42], [2.94], [1.3]])
total_samples = train_x.shape[0]
#total_samples = tf.constant(17.)
x = tf.placeholder(dtype = tf.float32, shape = (None, 1))
w = tf.Variable(initial_value = [[1]], dtype = tf.float32)
b = tf.Variable(tf.zeros(1), dtype = tf.float32)
y = tf.matmul(x, w) + b
y_ = tf.placeholder(dtype = tf.float32, shape = (None, 1))
global_step = tf.Variable(0, trainable = False)
loss = tf.reduce_sum(tf.pow(y - y_, 2)) / total_samples
optimizer = tf.train.GradientDescentOptimizer(learning_rate = 0.01)
train_op = optimizer.minimize(loss = loss, global_step = global_step)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
while global_step.eval() < 2000:
sess.run(train_op, feed_dict = {x:train_x, y_:train_y})
print('step:%d, w = %f, b = %f, loss = %f' % (global_step.eval(), w.eval(), b.eval(), loss.eval(feed_dict = {x:train_x, y_:train_y})))
plt.plot(train_x, train_y, 'ro')
plt.plot(train_x, w.eval() * train_x + b.eval())
plt.show()
可以看到拟合直线的变化过程,如下图
- 最终结果如下图
共迭代2000步,最终w = 0.252106, b = 0.793189, loss = 0.158868