BCEWithLogitsLoss在凯拉斯 [英] BCEWithLogitsLoss in Keras
问题描述
如何在keras中实现BCEWithLogitsLoss
并将其用作自定义损失函数,同时将Tensorflow
作为后端.
How to implement BCEWithLogitsLoss
in keras and use it as custom loss function while using Tensorflow
as backend.
我在torch
中定义的PyTorch
中使用了BCEWithLogitsLoss
.
I have used BCEWithLogitsLoss
in PyTorch
which was defined in torch
.
如何在Keras中实现相同功能?
How to implement the same in Keras.?
推荐答案
In TensorFlow, you can directly call tf.nn.sigmoid_cross_entropy_with_logits
which works both in TensorFlow 1.x and 2.0.
如果您想使用Keras API,请使用 tf.losses.BinaryCrossentropy
并在构造函数调用中设置from_logits=True
.
If you want to stick to Keras API, use tf.losses.BinaryCrossentropy
and set from_logits=True
in the constructor call.
与PyTorch不同,API中没有明确的示例权重.您可以改为将reduction=tf.keras.losses.Reduction.NONE
设置为损失,通过显式乘法进行加权,并使用tf.reduce_mean
减少损失.
Unlike PyTorch, there are not explicit per-example weights in the API. You can instead set reduction=tf.keras.losses.Reduction.NONE
for the loss, do your weighting by explicit multiplication and reduce your loss using tf.reduce_mean
.
xent = tf.losses.BinaryCrossEntropy(
from_logits=True,
reduction=tf.keras.losses.Reduction.NONE)
loss = tf.reduce_mean(xent(targets, pred) * weights))
这篇关于BCEWithLogitsLoss在凯拉斯的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!