TensorFlow:优化器给出nan作为输出

时间:2017-11-03 19:57:01

标签: python tensorflow deep-learning python-3.6 gradient-descent

我正在运行一个非常简单的张量流程序

W = tf.Variable([.3],tf.float32)
b = tf.Variable([-.3],tf.float32)
x = tf.placeholder(tf.float32)

linear_model = W*x + b

y = tf.placeholder(tf.float32)

squared_error = tf.square(linear_model - y)

loss = tf.reduce_sum(squared_error)

optimizer = tf.train.GradientDescentOptimizer(0.1)

train = optimizer.minimize(loss)

init = tf.global_variables_initializer()

with tf.Session() as s:
    file_writer = tf.summary.FileWriter('../../tfLogs/graph',s.graph)
    s.run(init)
    for i in range(1000):
        s.run(train,{x:[1,2,3,4],y:[0,-1,-2,-3]})
    print(s.run([W,b]))

这给了我

[array([ nan], dtype=float32), array([ nan], dtype=float32)]

我做错了什么?

1 个答案:

答案 0 :(得分:4)

您使用loss = tf.reduce_sum(squared_error)代替reduce_mean。使用reduce_sum,当您拥有更多数据时,您的损失会变得更大,即使使用这个小例子,也意味着您的渐变大到足以导致模型分歧。

可能导致此类问题的其他问题是当您的学习率过高时。在这种情况下,您也可以通过将学习率从0.1更改为0.01来修复它,但如果您仍在使用reduce_sum,则在添加更多分数时它会再次中断。

相关问题