是否可以将 PyTorch 的 BatchNorm1d 与 BCELossWithLogits 一起使用?

原文标题Is it possible to use PyTorch’s `BatchNorm1d` with `BCELossWithLogits`?

我正在尝试规范化使用BCELossWithLogits作为其损失函数一部分的分类器的输出。据我所知,这在内部实现了 Sigmoid 函数并输出了损失。

我想在计算损失之前标准化 sigmoid 函数的输出。 BatchNorm1dBCELossWithLogits可以用吗?还是将输出张量传递给torch.sigmoidtoBatchNorm1d并单独计算BCELoss是唯一可能的解决方案?

谢谢。

原文链接:https://stackoverflow.com//questions/71547905/is-it-possible-to-use-pytorchs-batchnorm1d-with-bcelosswithlogits

回复

我来回复
  • ndrwnaguib的头像
    ndrwnaguib 评论

    可以用BCELoss代替BCELossWithLogits,描述为:

    这种损失将 Sigmoid 层和 BCELoss 组合在一个类中。这个版本比使用简单的 Sigmoid 后跟 BCELoss 在数值上更稳定

    例如,

    m = nn.Sigmoid()
    bn = nn.BatchNorm1d(3)
    loss = nn.BCELoss()
    input = torch.randn((2, 3), requires_grad=True)
    target = torch.empty(2, 3).random_(2)
    output = loss(m(bn(input)), target)
    output.backward()
    
    2年前 0条评论