看了某个教程写的代码:
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
num_puntos = 1000
conjunto_puntos = []
for i in xrange (num_puntos):
x1 = np.random.normal(0.0,0.55)
y1 = x1*0.3 + 0.9 + np.random.normal(0.0,0.03)
conjunto_puntos.append([x1,y1])
#x_data,y_data分别conjunto_puntos的第一列和第二列的值
x_data = [v[0] for v in conjunto_puntos]
y_data = [v[1] for v in conjunto_puntos]
# print (x_data)
# print (y_data)
# plt.plot(x_data, y_data,'ro', label='Original data')
# plt.legend('wr is a pig')
# plt.show()
W = tf.Variable(tf.random_uniform([1],-1.0,1.0))
b = tf.Variable(tf.zeros([1]))
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()
sess = tf.Session()
sess.run(init)
#无返回值
#print("************",sess.run(init))
for step in xrange(8):
sess.run(train)
#无返回值
# print("************",sess.run(train))
print(step, sess.run(W), sess.run(b))
#返回参数值
y = sess.run(W)*x_data+sess.run(b)
# print('y:',y)
plt.plot(x_data, y_data,'ro', x_data,y,'-b')
# plt.plot(y,'-b')
#['a','b']分别是两组数据的标签提示值
plt.legend(['a','b'],loc="upper right")
plt.show()