使用一个热编码和softmax的Pytorch(分类)交叉熵损失

2024-06-23 03:37:10 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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

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

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


Tags: 函数编码tensorflow分类pytorch标签解决方案交叉
1条回答
网友
1楼 · 发布于 2024-06-23 03:37:10

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

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

    enter image description here

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

    enter image description here

你的预测已经通过了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))

上面的预测向量从一个热编码转换为带有torch.argmax的标签


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

相关问题 更多 >

    热门问题