# 线性回归
import tensorflow as tf
# 定义输入x,y
x = tf.placeholder(tf.float32, shape=[5], name='x')
y = tf.placeholder(tf.float32, shape=[5], name='y')
# 定义变量w,b
w = tf.Variable(0., dtype=tf.float32, name='weight')
b = tf.Variable(0., dtype=tf.float32, name='bias')
# 得到预测值
predict = w * x + b
# 最小二乘法获得损失
loss = tf.reduce_mean(tf.square(predict - y))
# 梯度下降法获取最小损失
optimizer = tf.train.GradientDescentOptimizer(0.01).minimize(loss=loss)
# 初始化
init = tf.global_variables_initializer()
# 训练
with tf.Session() as sess:
sess.run(init)
for index in range(2000):
sess.run(optimizer, feed_dict={x: [1, 2, 3, 4, 5], y: [6, 7, 8, 9, 10]})
print("weight = ", sess.run(w), ",bias = ", sess.run(b))
网友评论