【问题标题】:GradientDescentOptimizer requiring a loss function without arguments in eager modeGradientDescentOptimizer 在急切模式下需要不带参数的损失函数
【发布时间】:2019-04-25 08:13:10
【问题描述】:

tf.train.Optimizer 的 API 说: “当启用急切执行时,损失应该是一个不带参数并计算要最小化的值的 Python 函数。”

我很困惑,损失函数如何在没有给出预测和标签的情况下计算损失?

我尝试了 tf.losses.mean_squared_error,但正如预期的那样,它不起作用,因为它需要参数。

opt = tf.train.GradientDescentOptimizer(learning_rate=.1)

opt_op = opt.minimize(tf.losses.mean_squared_error, var_list=[model.W, model.b])
# TypeError: mean_squared_error() missing 2 required positional arguments: 'labels' and 'predictions'

【问题讨论】:

    标签: tensorflow tensorflow2.0


    【解决方案1】:

    tf.losses.mean_squared_error 需要两个位置参数。

    给定pred 一个预测和label 预期结果。

    pred  # computed
    label # computed
    def custom_loss() :
      return tf.losses.mean_squared_error(pred, label)
    
    opt.minimize(custom_loss, var_list=[model.W, model.b])
    

    【讨论】:

    • 您的意思可能是这样的:opt_op = opt.minimize(lambda x, y: loss(x,y), var_list=model.trainable_variables) 这也会引发与原始问题相同的错误:#TypeError: <lambda>() missing 2 required positional arguments: 'x' and 'y' 否则,您的代码 opt.minimize 会抛出 TypeError,因为它收到了太多的输入变量。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-23
    • 2016-01-01
    • 1970-01-01
    • 2020-01-29
    • 1970-01-01
    • 1970-01-01
    • 2018-10-11
    相关资源
    最近更新 更多