【发布时间】:2017-05-09 14:39:29
【问题描述】:
我大致遵循this 教程来感受简单的张量流计算。对于那些不想点击链接的人来说,这是一个简单的OLS问题,拟合y = Wx + b,真解:y = 2x
并具有以下代码和输出
import tensorflow as tf
tf.reset_default_graph()
import numpy as np
x = tf.placeholder(tf.float32, [None, 1]) # 1d input vector
W = tf.Variable(tf.zeros([1,1]))
b = tf.Variable(tf.zeros([1]))
y = tf.matmul(x,W) + b
y_res = tf.placeholder(tf.float32, [None, 1])
cost = tf.reduce_sum(tf.pow(y - y_res, 2))
x_l = np.array([[i] for i in range(100)])
y_l = 2 * x_l
train = tf.train.GradientDescentOptimizer(0.000001).minimize(cost)
init = tf.initialize_all_variables()
with tf.Session() as sess:
sess.run(init)
for i in range(5):
feed = {x: x_l,y_res:y_l}
sess.run(train, feed_dict=feed)
print ("iteration", i)
print ("W", sess.run(W))
print ("B", sess.run(b))
我得到了合理的答案
('iteration', 0)
('W', array([[ 1.31340003]], dtype=float32))
('B', array([ 0.0198], dtype=float32))
('iteration', 1)
('W', array([[ 1.76409423]], dtype=float32))
('B', array([ 0.02659338], dtype=float32))
('iteration', 2)
('W', array([[ 1.91875029]], dtype=float32))
('B', array([ 0.02892353], dtype=float32))
('iteration', 3)
('W', array([[ 1.97182059]], dtype=float32))
('B', array([ 0.02972212], dtype=float32))
('iteration', 4)
('W', array([[ 1.99003172]], dtype=float32))
('B', array([ 0.02999515], dtype=float32))
但是,我一直在寻求进一步了解并了解其他一些已实现的优化器,特别是 ADAM
为了看这个优化器的效果,我把相关行改成了
train = tf.train.AdamOptimizer().minimize(cost)
这给出了稍微奇怪的结果:
('iteration', 0)
('W', array([[ 0.001]], dtype=float32))
('B', array([ 0.001], dtype=float32))
('iteration', 1)
('W', array([[ 0.00199998]], dtype=float32))
('B', array([ 0.00199998], dtype=float32))
('iteration', 2)
('W', array([[ 0.00299994]], dtype=float32))
('B', array([ 0.00299994], dtype=float32))
('iteration', 3)
('W', array([[ 0.00399987]], dtype=float32))
('B', array([ 0.00399987], dtype=float32))
('iteration', 4)
('W', array([[ 0.00499976]], dtype=float32))
('B', array([ 0.00499976], dtype=float32))
现在,我在这里搞砸了学习率等,但我有点困惑为什么这很难收敛。有没有人知道为什么这个优化器在这样一个微不足道的问题上失败了
【问题讨论】:
标签: python tensorflow