torch - 如何在 PyTorch 中使用 BCELoss?

标签 torch autoencoder loss pytorch

我想在 PyTorch 中编写一个简单的自动编码器并使用 BCELoss ,但是,我得到了 NaN,因为它期望目标介于 0 和 1 之间。有人可以发布 BCELoss 的简单用例吗?

最佳答案

更新

BCELoss 函数过去在数值上不稳定。查看本期https://github.com/pytorch/pytorch/issues/751 。但是,此问题已通过 Pull #1792 解决。 ,因此 BCELoss 现在在数值上是稳定的!

<小时/>

旧答案

如果您从源代码构建 PyTorch,则可以使用数值稳定函数 BCEWithLogitsLoss(贡献于 https://github.com/pytorch/pytorch/pull/1792 ),该函数将 logits 作为输入。

否则,您可以使用以下函数(由上期中的yzgao贡献):

class StableBCELoss(nn.modules.Module):
       def __init__(self):
             super(StableBCELoss, self).__init__()
       def forward(self, input, target):
             neg_abs = - input.abs()
             loss = input.clamp(min=0) - input * target + (1 + neg_abs.exp()).log()
             return loss.mean()

关于torch - 如何在 PyTorch 中使用 BCELoss?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43708693/

相关文章:

lua - torch/nn - 按元素连接张量数组

lua - 运行Google Deep Q Network Code时遇到的Bug

python - 在 C 中嵌入 Tensorflow/Torch 以集成到更大的项目中

tensorflow - 自定义 DataGenerator tensorflow 错误 'ValueError: Failed to find data adapter that can handle input'

python - 如何在 Keras 中正确实现自定义事件正则化器?

validation - Keras 预测给出与评估不同的错误,与指标不同的损失

batch-file - CNN 上的快速损失收敛意味着什么?

python-3.x - PyTorch 中的左移张量

keras - 变分自动编码器 : Does encoder must have the same number of layers as the decoder?

neural-network - 添加带有卷积神经网络的 SVM