【问题标题】:Mismatch output between custom loss function and in-built loss function自定义损失函数和内置损失函数之间的不匹配输出
【发布时间】:2021-01-22 00:26:30
【问题描述】:

我正在尝试实现二进制交叉熵损失,而不是使用 keras 函数。这是我的代码:

def softmax_fn(val):
  return tf.math.exp(val) / tf.math.reduce_sum(tf.math.exp(val))

def bce_fn(y_true, y_pred):
  y_pred_softmax = softmax_fn(y_pred)
  bce_loss = tf.cast(y_true, tf.float32) * tf.math.log(y_pred_softmax) + (1.0 - tf.cast(y_true, tf.float32)) * tf.math.log(1.0 - y_pred_softmax)
  return -tf.math.reduce_mean(bce_loss) 

我的问题是我的损失和 keras 之间的输出不匹配:

# keras loss
cross_entropy = tf.keras.losses.BinaryCrossentropy(from_logits=True)

y_true = [1.0, 1.0, 0.0, 0.0]
y_pred = [1.0, 0.0, 1.0, 0.0]

print(cross_entropy(y_true,y_pred))  # 0.75320446
print(bce_fn(y_true,y_pred))  # 0.903049

谁能解释一下为什么会这样?

编辑

我发现了错误:在内置损失函数中使用 from_logits=True 意味着我们像 sigmoid 函数而不是 softmax 函数那样计算概率。 This discussion helped me

def bce_fn(y_true, y_pred):
  y_pred_sigmoid = tf.math.sigmoid(y_pred)  # sigmoid activation
  bce_loss = tf.math.reduce_mean(tf.cast(y_true, tf.float32) * -tf.math.log(y_pred_sigmoid) + (1 - tf.cast(y_true, tf.float32) ) * -tf.math.log(1 - y_pred_sigmoid))
  return bce_loss

现在内置函数和我的自定义函数具有相同的输出。

【问题讨论】:

  • 我认为二进制熵的最后一个维度应该等于2
  • 这是什么意思?我只有 1 和 0,所以维度已经是 2。

标签: tensorflow keras


【解决方案1】:

感谢 Alexandru Ropotica 的更新。为了社区的利益,请在答案部分发布解决方案。

# BinaryCrossentropy 自定义内置函数:

def bce_fn(y_true, y_pred):
  y_pred_sigmoid = tf.math.sigmoid(y_pred) 
  bce_loss = tf.math.reduce_mean(tf.cast(y_true, tf.float32) * -tf.math.log(y_pred_sigmoid) + (1 - tf.cast(y_true, tf.float32) ) * -tf.math.log(1 - y_pred_sigmoid))
  return bce_loss

cross_entropy = tf.keras.losses.BinaryCrossentropy(from_logits=True)

y_true = [1.0, 1.0, 0.0, 0.0]
y_pred = [1.0, 0.0, 1.0, 0.0]

print(cross_entropy(y_true,y_pred))  
print(bce_fn(y_true,y_pred))

输出:

tf.Tensor(0.75320446, shape=(), dtype=float32)
tf.Tensor(0.75320446, shape=(), dtype=float32)

【讨论】:

    猜你喜欢
    • 2019-11-01
    • 2020-10-07
    • 2020-12-05
    • 2017-12-16
    • 1970-01-01
    • 1970-01-01
    • 2020-12-19
    • 2017-04-04
    • 2017-12-18
    相关资源
    最近更新 更多