禁止在PyTorch神经网络的CrossEntropyLoss中使用Softmax

问题描述 投票:0回答:1

[我知道当使用nn.Softmax()作为损失函数时,在神经网络的输出层中不需要使用nn.CrossEntropyLoss函数。

但是我需要这样做,有没有办法抑制在nn.CrossEntropyLoss中实现softmax的实现,而在神经网络本身的输出层上使用nn.Softmax()

Motivation:之后,我将使用shap程序包分析功能影响,在这里我只能输入经过训练的模型作为输入。但是,输出没有任何意义,因为我正在查看未绑定的值而不是概率。

示例:我希望模型的某个类的输出值不是-69.36,而是要在0到1之间,所有类的总和为1。由于我以后无法更改它,因此在训练过程中输出必须已经是这样。

enter image description here

python neural-network pytorch softmax cross-entropy
1个回答
0
投票

您可以使用nn.NLLLoss()nn.CrossEntropyLoss计算输入分数的对数softmax并计算负对数可能性损失。如果您已经具有对数概率,则只需使用nn.NLLLoss()

Here是来自PyTorchs文档的示例

m = nn.LogSoftmax(dim=1)
loss = nn.NLLLoss()
input = torch.randn(3, 5, requires_grad=True)
target = torch.tensor([1, 0, 4])
output = loss(m(input), target)
© www.soinside.com 2019 - 2024. All rights reserved.