Keras 中的 BCEWithLogitsLoss
BCEWithLogitsLoss in Keras
如何在 keras 中实现 BCEWithLogitsLoss
并将其用作自定义损失函数,同时使用 Tensorflow
作为后端。
我在 PyTorch
中使用了 BCEWithLogitsLoss
,这是在 torch
中定义的。
如何在 Keras 中实现相同的功能?
在 TensorFlow 中,您可以直接调用 tf.nn.sigmoid_cross_entropy_with_logits
,它在 TensorFlow 1.x 和 2.0 中都有效。
如果您想坚持使用 Keras API,请使用 tf.losses.BinaryCrossentropy
并在构造函数调用中设置 from_logits=True
。
与 PyTorch 不同,API 中没有明确的每个示例权重。您可以为损失设置 reduction=tf.keras.losses.Reduction.NONE
,通过显式乘法进行加权并使用 tf.reduce_mean
.
减少损失
xent = tf.losses.BinaryCrossEntropy(
from_logits=True,
reduction=tf.keras.losses.Reduction.NONE)
loss = tf.reduce_mean(xent(targets, pred) * weights))
如何在 keras 中实现 BCEWithLogitsLoss
并将其用作自定义损失函数,同时使用 Tensorflow
作为后端。
我在 PyTorch
中使用了 BCEWithLogitsLoss
,这是在 torch
中定义的。
如何在 Keras 中实现相同的功能?
在 TensorFlow 中,您可以直接调用 tf.nn.sigmoid_cross_entropy_with_logits
,它在 TensorFlow 1.x 和 2.0 中都有效。
如果您想坚持使用 Keras API,请使用 tf.losses.BinaryCrossentropy
并在构造函数调用中设置 from_logits=True
。
与 PyTorch 不同,API 中没有明确的每个示例权重。您可以为损失设置 reduction=tf.keras.losses.Reduction.NONE
,通过显式乘法进行加权并使用 tf.reduce_mean
.
xent = tf.losses.BinaryCrossEntropy(
from_logits=True,
reduction=tf.keras.losses.Reduction.NONE)
loss = tf.reduce_mean(xent(targets, pred) * weights))