Sre*_* TP 3 python deep-learning keras loss-function
如何BCEWithLogitsLoss在 keras 中实现并将其用作自定义损失函数,同时用作Tensorflow后端。
我已经使用了BCEWithLogitsLoss其中PyTorch定义的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))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4648 次 |
| 最近记录: |