【发布时间】:2020-01-09 19:54:07
【问题描述】:
我正在使用张量实现简单的梯度下降算法。它学习了两个参数 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
repo 还包含通过 tensorboard 在 events 目录中获得的图形图像
【问题讨论】:
标签: python python-3.x tensorflow machine-learning gradient-descent