【问题标题】:TensorFlow : optimizer gives nan as ouputTensorFlow:优化器将 nan 作为输出
【发布时间】:2017-11-03 19:57:01
【问题描述】:

我正在运行一个非常简单的 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)]

我做错了什么?

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-12
      • 2018-02-02
      • 2022-10-02
      • 2018-10-02
      • 1970-01-01
      相关资源
      最近更新 更多