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

时间:2019-09-07 03:26:42

标签: python python-3.x tensorflow machine-learning gradient-descent

我正在使用张量实现简单的梯度下降算法。它学习两个参数 m c
 普通的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)

张量流的输出:

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

存储库还包含通过张量板在事件目录中获得的图的图像

1 个答案:

答案 0 :(得分:3)

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

sess.run([upm, upc])