import tensorflow as tf
import numpy as np
import random
x_data = np.random.rand(100).astype(np.float32)
noise = np.random.normal(loc=0, scale=0.005, size=x_data.shape)
y_data = x_data*0.1+0.3 + noise
weights = tf.Variable(tf.random_uniform([1], -1.0, 1.0))
bias = tf.Variable(tf.zeros([1]))
y = weights*x_data + bias
loss = tf.reduce_mean(tf.square(y-y_data))
optimizer = tf.train.GradientDescentOptimizer(0.5)
train = optimizer.minimize(loss)
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)
for step in range(201):
sess.run(train)
if step%20 == 0:
print(step, sess.run(weights), sess.run(bias))
0 [0.5786313] [0.04093613]
20 [0.22345346] [0.23119761]
40 [0.13341352] [0.28108537]
60 [0.11040851] [0.2938316]
80 [0.10453079] [0.2970882]
100 [0.10302906] [0.2979203]
120 [0.10264537] [0.29813287]
140 [0.1025473] [0.2981872]
160 [0.10252227] [0.29820108]
180 [0.10251586] [0.29820463]
200 [0.10251423] [0.29820552]
import matplotlib.pyplot as plt
plt.xlabel("x")
plt.ylabel("y")
plt.title("Linear Regression")
plt.scatter(x_data, y_data)
plt.plot(x_data, sess.run(weights) * x_data + sess.run(bias),'r--' , label='拟合数据')
plt.show()