【问题标题】:Tensorflow loss minimization is increasing lossTensorflow 损失最小化正在增加损失
【发布时间】:2017-03-31 16:48:35
【问题描述】:

我实现了 Tensorflow 主页上显示的线性回归模型:https://www.tensorflow.org/get_started/get_started

import numpy as np
import tensorflow as tf

# Model parameters
W = tf.Variable([.3], tf.float32)
b = tf.Variable([-.3], tf.float32)
# Model input and output
x = tf.placeholder(tf.float32)
linear_model = W * x + b
y = tf.placeholder(tf.float32)
# loss
loss = tf.reduce_sum(tf.square(linear_model - y)) # sum of the squares
# optimizer
optimizer = tf.train.GradientDescentOptimizer(0.01)
train = optimizer.minimize(loss)
# training data
x_train = [1,2,3,4]
y_train = [0,-1,-2,-3]
# training loop
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init) # reset values to wrong
for i in range(1000):
  sess.run(train, {x:x_train, y:y_train})

# evaluate training accuracy
curr_W, curr_b, curr_loss  = sess.run([W, b, loss], {x:x_train, y:y_train})
print("W: %s b: %s loss: %s"%(curr_W, curr_b, curr_loss))

但是,当我将训练数据更改为 x_train=[2,4,6,8] 和 y_train=[3,4,5,6] 时, 随着时间的推移损失开始增加,直到达到'nan'

【问题讨论】:

  • 随着时间的推移,您的体重和偏见如何变化?另外请注意,您应该使用 reduce_mean 而不是 reduce_sum。
  • 我的权重和偏差值越来越大,它们在大的正值和负值之间交替。您是否要求我使用 reduce_mean,因为计算出的梯度低于使用 reduce_sum 得到的梯度?但我看不出这有什么帮助。
  • 嗯,我唯一能想到的另一件事就是降低学习率。老实说,其他一切似乎都很好。如果你的学习率太大,它可能会导致你在损失方面不断做得更差,因为梯度会随着每一步而继续增加。试着把它变小,然后告诉我。

标签: tensorflow training-data gradient-descent tensorboard


【解决方案1】:

正如Steven 所建议的,您可能应该使用reduce_mean(),这似乎可以解决增加损失函数的问题。请注意,我还增加了训练步骤的数量,因为 reduce_mean() 似乎需要更长的时间才能收敛。提高学习率时要小心,因为这可能会重现问题。相反,如果训练时间不是关键因素,您可能希望降低学习率并进一步增加训练迭代次数。

在将学习率从 0.01 降低到 0.001 后,使用 reduce_sum() 函数对我来说效果很好。再次感谢Steven 的建议。

import numpy as np
import tensorflow as tf

# Model parameters
W = tf.Variable([.3], tf.float32)
b = tf.Variable([-.3], tf.float32)
# Model input and output
x = tf.placeholder(tf.float32)
linear_model = W * x + b
y = tf.placeholder(tf.float32)
# loss
loss = tf.reduce_mean(tf.square(linear_model - y)) # sum of the squares
# optimizer
optimizer = tf.train.GradientDescentOptimizer(0.01)
train = optimizer.minimize(loss)
# training data
x_train = [2,4,6,8]
y_train = [0,3,4,5]
# training loop
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init) # reset values to wrong
for i in range(5000):
    sess.run(train, {x:x_train, y:y_train})

    # evaluate training accuracy
    curr_W, curr_b, curr_loss  = sess.run([W, b, loss], {x:x_train, y:y_train})
    print("W: %s b: %s loss: %s"%(curr_W, curr_b, curr_loss))

【讨论】:

    猜你喜欢
    • 2018-04-25
    • 2017-08-14
    • 1970-01-01
    • 1970-01-01
    • 2017-12-02
    • 1970-01-01
    • 2021-07-18
    • 1970-01-01
    • 2021-04-07
    相关资源
    最近更新 更多