使用张量计算错误值的梯度下降

gradient descent using tensors calculating wrong values

我正在使用张量实现简单的梯度下降算法。它学习两个参数 mc.
它的正常 python 代码是:

for i in range(epochs): 
    Y_pred = m*X + c  # The current predicted value of Y
    D_m = (-2/n) * sum(X * (Y - Y_pred))  # Derivative wrt m
    D_c = (-2/n) * sum(Y - Y_pred)  # Derivative wrt c
    m = m - L * D_m  # Update m
    c = c - L * D_c  # Update c
    print (m, c) 

python 的输出:

0.7424335285442664 0.014629895049575754
1.1126970531591416 0.021962519495058154
1.2973530613155333 0.025655870599552183
1.3894434413955663 0.027534253868790198
1.4353697670010162 0.028507481513901086

Tensorflow 等效代码:

#Graph of gradient descent
y_pred = m*x + c
d_m = (-2/n) * tf.reduce_sum(x*(y-y_pred)) 
d_c = (-2/n) * tf.reduce_sum(y-y_pred)  
upm = tf.assign(m, m - learning_rate * d_m)
upc = tf.assign(c, c - learning_rate * d_c)

#starting session
sess = tf.Session()

#Training for epochs
for i in range(epochs):
    sess.run(y_pred)
    sess.run(d_m)
    sess.run(d_c)
    sess.run(upm)
    sess.run(upc)
    w = sess.run(m)
    b = sess.run(c)
    print(w,b)

tensorflow 的输出:

0.7424335285442664 0.007335550424492317
1.1127687194584988 0.011031122807663662
1.2974962163433057 0.012911024540805463
1.3896400798226038 0.013885244876397126
1.4356019721347115 0.014407698787092268

参数 m 对两者具有相同的值,但 参数 c 对两者具有不同的值,尽管两者的实现相同。
输出包含参数 m 和 c 的前 5 个值。参数c使用张量的输出大约是正常的一半python.
我不知道我的错误在哪里。

重新创建整个输出: Repo containing data along with both implementations

repo 还包含通过 tensorboard 在 events 目录中获取的图形图像

问题在于,在 TF 实现中,更新不是自动执行的。换句话说,算法的实现是以交错的方式更新 mc(例如,更新 c 时使用 m 的新值)。要使更新成为原子更新,您应该同时 运行 upmupc:

sess.run([upm, upc])