交叉熵公式:
但是为什么下面的代码会得到loss = 0.7437
而不是loss = 0
(因为1*log(1) = 0
)呢?
import torchimport torch.nn as nnfrom torch.autograd import Variableoutput = Variable(torch.FloatTensor([0,0,0,1])).view(1, -1)target = Variable(torch.LongTensor([3]))criterion = nn.CrossEntropyLoss()loss = criterion(output, target)print(loss) # 0.7437
回答:
在您的例子中,您将输出[0, 0, 0, 1]
视为概率,这符合交叉熵的数学定义。但PyTorch将它们视为输出,这些输出不需要总和为1
,并且需要先通过softmax函数转换为概率。
因此,H(p, q)
变为:
H(p, softmax(output))
将输出[0, 0, 0, 1]
转换为概率:
softmax([0, 0, 0, 1]) = [0.1749, 0.1749, 0.1749, 0.4754]
由此得出:
-log(0.4754) = 0.7437