单变量线性回归代码

import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as np

trX = np.linspace(-1, 1, 101) #-1至1 101个元素
trY = 2 * trX + np.random.randn(*trX.shape) * 0.4 + 0.2 # β0+β1*x β0=0.2 β1=2 噪音0.4

plt.scatter(trX,trY)
plt.plot (trX, .2 + 2 * trX) #这里输出标准的 β0+β1*x β0=0.2 β1=2 斜线
plt.show()

X = tf.placeholder("float", name="X") # 声明变量
Y = tf.placeholder("float", name = "Y")

with tf.name_scope("Model"): #定义计算Y的模型 X*w + b0

def model(X, w, b):
return tf.multiply(X, w) + b

w = tf.Variable(-1.0, name="b0")
b = tf.Variable(-2.0, name="b1")
y_model = model(X, w, b)


with tf.name_scope("CostFunction"): #使用定义的模型计算Y
cost = (tf.pow(Y-y_model, 2))

train_op = tf.train.GradientDescentOptimizer(0.05).minimize(cost) #步长0.05


sess = tf.Session()
init = tf.initialize_all_variables()
tf.train.write_graph(sess.graph, './','graph.pbtxt')
cost_op = tf.summary.scalar("loss", cost)
merged = tf.summary.merge_all()
sess.run(init)
writer = tf.summary.FileWriter('./', sess.graph)

for i in range(100):
for (x, y) in zip(trX, trY):
sess.run(train_op, feed_dict={X: x, Y: y})
summary_str = sess.run(cost_op, feed_dict={X: x, Y: y})
writer.add_summary(summary_str, i)
b0temp=b.eval(session=sess)
b1temp=w.eval(session=sess)
plt.plot (trX, b0temp + b1temp * trX )
#plt.show()
print(sess.run(w)) # Should be around 2
print(sess.run(b)) #Should be around 0.2

print(sess.run(w)) # Should be around 2
print(sess.run(b)) #Should be around 0.2


plt.scatter(trX,trY)
plt.plot (trX, sess.run(b) + trX * sess.run(w))
plt.show()