案例:
minimize(error)
代码:
def linear_regression():
# 自实现线性回归
# 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)构造损失函数
error = tf.reduce_mean(tf.square(y_predict - y_true))
# 4)优化损失
# optimizer = tf.train.GradientDescentOptimizer(learning_rate = 0.01).minimize(error)
optimizer = tf.compat.v1.train.GradientDescentOptimizer(learning_rate=0.01).minimize(error)
# 显示初始化变量
init = tf.global_variables_initializer()
# 开启会话
with tf.Session() as sess:
#初始化变量
sess.run(init)
# 查看初始化模型参数之后的值
print("训练前模型参数为:权重%f,偏置%f" % (weights.eval(),bias.eval()))
# 开始训练
for i in range(100):
sess.run(optimizer)
print("训练后模型参数为:权重%f,偏置%f" % (weights.eval(), bias.eval()))
return None