公式: f(x) = 2x +5
import tensorflow as tf
x_data = list(range(100))
y_data = [2 * n + 5 for n in x_data]
x = tf.Variable(0.0)
y = tf.Variable(0.0)
w = tf.Variable(0.0, name="w0")
b = tf.Variable(0.0, name="b0")
@tf.function
def pred():
return tf.add(tf.multiply(x, w), b)
loss_func = lambda : tf.reduce_mean(tf.square( y - pred()))
optimizer = tf.optimizers.SGD(learning_rate=0.0001)
for _ in range(20):
for xs, ys in zip(x_data, y_data):
x.assign(xs)
y.assign(ys)
optimizer.minimize(loss_func, var_list=[w, b])
print(w.numpy(), b.numpy())结果: w=2.0466027 b=0.36308017
根据公式,b应该在5附近,但它很远。
有人知道为什么吗?
谢谢
发布于 2020-01-13 07:01:17
计算精度没有什么问题。这并不是优化器和超参数的最佳选择。
我尝试了optimizer = tf.optimizers.Adam(learning_rate=0.01),在100次迭代中,它估计b接近5。
我相信在您的示例中,SGD最终将得出接近5的b估计值,但它将需要20多个时代(1-2千?)。提高学习速度将导致梯度爆炸,因为您在单一数据点上一次训练模型。你可能想一次训练100个数据点的整批模型--这就是tensorflow显示其力量的地方。
https://stackoverflow.com/questions/59711326
复制相似问题