【问题标题】:Pytorch - (Categorical) Cross Entropy Loss using one hot encoding and softmaxPytorch - 使用一种热编码和 softmax 的(分类)交叉熵损失
【发布时间】:2021-03-11 13:32:16
【问题描述】:

我正在寻找 Pytorch 中的交叉熵损失函数,它类似于 Tensorflow 中的 CategoricalCrossEntropyLoss

我的标签是热编码的,预测是 softmax 层的输出。例如(每个样本属于一个类):

targets = [0, 0, 1]
predictions = [0.1, 0.2, 0.7]

我想计算 softmax 值的(分类)交叉熵,将预测的最大值作为标签,然后计算交叉熵。不幸的是,我没有找到合适的解决方案,因为 Pytorch 的 CrossEntropyLoss 不是我想要的,它的 BCELoss 也不是我所需要的(不是吗?)。

有谁知道在 Pytorch 中使用哪个损失函数或如何处理它? 非常感谢!

【问题讨论】:

  • “不将预测的最大值作为标签,然后计算交叉熵”,为什么不呢?

标签: python pytorch one-hot-encoding cross-entropy


【解决方案1】:

我认为 Tensorflow 的 CategoricalCrossEntropyLoss 等同于 PyTorch 的 CrossEntropyLoss,但似乎不是。前者采用 OHE,而后者也采用标签。然而,进口差异似乎是:

  • torch.nn.CrossEntropyLosstorch.nn.LogSoftmaxtorch.nn.NLLLoss() 的组合:

  • tf.keras.losses.CategoricalCrossEntropyLoss 类似于:

您的预测已经通过了 sotfmax。所以只需要应用负对数似然。我可能是错的,但根据here 的讨论,你可以试试这个:

class CategoricalCrossEntropyLoss(nn.Module):
    def __init__(self):
        super(CategoricalCrossEntropyLoss, self).__init__()

    def forward(self, y_hat, y):
        return nn.NLLLoss()(torch.log(y_hat), torch.argmax(y, dim=1))

上面的预测向量从one-hot-encoding转换为带有torch.argmax的标签。


如果这是正确的,为什么不首先使用torch.nn.CrossEntropyLoss?您只需要删除模型最后一层的 softmax 并转换目标标签。

【讨论】:

  • 在前向传球中你没有将y 传给NNLoss
猜你喜欢
  • 2019-04-20
  • 2021-08-25
  • 2020-03-14
  • 2018-04-14
  • 2018-08-07
  • 2019-11-02
  • 2019-09-04
  • 1970-01-01
  • 2017-12-26
相关资源
最近更新 更多