import numpy as np
import tensorflow as tf
X = np.array([1, 2, 3, 4, 5], dtype=np.float32)
y = np.array([10, 19, 31, 42, 53], dtype=np.float32)
# X = (X_raw - X_raw.min()) / (X_raw.max() - X_raw.min())
# y = (y_raw - y_raw.min()) / (y_raw.max() - y_raw.min())
# X = tf.constant(X)
# y = tf.constant(y)
w = tf.Variable(initial_value=0.)
b = tf.Variable(initial_value=0.)
variables = [w, b]
num_epoch = 10000
optimizer = tf.optimizers.SGD(learning_rate=1e-3) # 声明了一个梯度下降优化器optimizer,学习率为1e-3
for e in range(num_epoch):
# 使用tf.GradientTape()记录损失函数的梯度信息
with tf.GradientTape() as tape:
y_pred = w * X + b
loss = tf.reduce_mean(tf.square(y_pred - y))
# TensorFlow自动计算损失函数关于自变量(模型参数)的梯度
grads = tape.gradient(loss, variables)
# TensorFlow自动根据梯度更新参数
optimizer.apply_gradients(grads_and_vars=zip(grads, variables))
print(w, b)
print(float(w))
10.8587007522583
print(b.numpy())
-1.5509015
print(w.numpy())
10.858701