【问题标题】:ValueError: No gradients provided for any variable when defining custom loss functionValueError:定义自定义损失函数时没有为任何变量提供梯度
【发布时间】:2020-11-27 11:39:21
【问题描述】:

你可以在下面找到我的自定义损失函数。

def custom_loss_function(y_true, y_pred):
  
  y_pred_bool = tf.math.less_equal(y_pred, tf.constant(0.5))
  y_pred_float = 1 - tf.cast(y_pred_bool, dtype=tf.int32)
  y_true = tf.cast(y_true, dtype=tf.int32)

  mask_bool_loss = tf.math.less(y_true, tf.constant(0))
  mask_loss = 1 - tf.cast(mask_bool_loss, dtype=tf.int32)
  mask = tf.math.reduce_min(mask_loss, axis=2)

  y_multiply = tf.math.multiply(y_true, y_pred_float)

  y = tf.math.reduce_sum(y_multiply, axis=2)
  y_loss = 1 - y
  y_loss = tf.math.multiply(y_loss, mask)

  return y_loss

我知道tensorflow的一些函数是不可微分的,但我真的不知道哪些函数或者如何绕过它?对我有什么建议吗?

我收到此错误:

ValueError: No gradients provided for any variable: ['bidirectional_7/forward_lstm_7/lstm_cell_22/kernel:0'/, ...

【问题讨论】:

    标签: tensorflow keras lstm loss


    【解决方案1】:

    一旦将变量转换为 int 或 bool,所有梯度信息都会丢失。因此,第一行中的渐变被破坏了。

      y_pred_bool = tf.math.less_equal(y_pred, tf.constant(0.5))
    

    这就是我们通常使用二元交叉熵之类的东西的原因,因为它为我们提供了不可微分的 0-1 损失的可微近似。

    【讨论】:

      猜你喜欢
      • 2021-05-08
      • 1970-01-01
      • 1970-01-01
      • 2022-12-04
      • 1970-01-01
      • 1970-01-01
      • 2019-05-09
      • 2020-04-05
      • 2021-01-08
      相关资源
      最近更新 更多