Pytorch。交叉熵损失的重量

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

我试图了解权重是如何在CrossEntropyLoss工作的一个实际例子。因此,我首先运行作为标准的PyTorch代码,然后手动两个。但损失是不一样的。

from torch import nn
import torch
softmax=nn.Softmax()
sc=torch.tensor([0.4,0.36])
loss = nn.CrossEntropyLoss(weight=sc)
input = torch.tensor([[3.0,4.0],[6.0,9.0]])
target = torch.tensor([1,0])
output = loss(input, target)
print(output)
>>1.7529

现在手动计算,首先softmax输入。

print(softmax(input))
>>
tensor([[0.2689, 0.7311],
        [0.0474, 0.9526]])

然后用正确的类概率的负数对数乘以相应的权重

((-math.log(0.7311)*0.36) - (math.log(0.0474)*0.4))/2
>>
0.6662

我有什么不明白的吗?

python pytorch cross-entropy
1个回答
1
投票

对于任何加权损失 (reduction='mean'),损失将被归一化的权重之和。所以在这种情况下,

((-math.log(0.7311)*0.36) - (math.log(0.0474)*0.4))/(.4+.36)
>> 1.7531671457872036
© www.soinside.com 2019 - 2024. All rights reserved.