TensorFlow:优化器将 nan 作为输出

TensorFlow : optimizer gives nan as ouput

我是运行一个很简单的tensorflow程序

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)]

我做错了什么?

您使用的是 loss = tf.reduce_sum(squared_error) 而不是 reduce_meanreduce_sum 当你拥有更多数据时,你的损失会更大,即使是这个小例子,它也意味着你的梯度大到足以导致你的模型发散。

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