我想在 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/