变量与操作
高级API
# 1)准备数据
x = tf.random_normal(shape=[100, 1])
y_true = tf.matmul(x, [[0.8]]) + 0.7
# 2)构造模型
# 定义模型参数
weights = tf.Variable(initial_value=tf.random_normal(shape=[1, 1]))
bias = tf.Variable(initial_value=tf.random_normal(shape=[1, 1]))
y_predict = tf.matmul(x, weights) + bias
# 3)构造损失函数
loss = tf.reduce_mean(tf.square(y_predict - y_true))
# 4)优化损失
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01).minimize(loss)
# 显式的初始化变量
init = tf.global_variables_initializer()
# 开启会话
with tf.Session() as sess:
sess.run(init)
# 查看初始化模型参数之后的值
print("训练前模型参数为:Weights:%f,bias:%f,loss:%f" % (weights.eval(), bias.eval(), loss.eval()))
# 开始训练
for i in range(1000):
if i % 100 == 0:
sess.run(optimizer)
print("第%f训练后模型参数为:Weights:%f,bias:%f,loss:%f" % (i, weights.eval(), bias.eval(), loss.eval()))