BCEWithLogitsLoss在凯拉斯 [英] BCEWithLogitsLoss in Keras

查看:430
本文介绍了BCEWithLogitsLoss在凯拉斯的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在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.?

推荐答案

在TensorFlow中,您可以直接调用

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆