交叉熵公式:
但为什么下面给出loss = 0.7437
代替loss = 0
(since 1*log(1) = 0
)?
import torch
import torch.nn as nn
from torch.autograd import Variable
output = 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, 0, 0, 1]
作为交叉熵的数学定义所需的概率。但 PyTorch 将它们视为输出,不需要求和1
,并且需要首先转换为使用 softmax 函数的概率。
So H(p, q)
变成:
H(p, softmax(output))
翻译输出[0, 0, 0, 1]
转化为概率:
softmax([0, 0, 0, 1]) = [0.1749, 0.1749, 0.1749, 0.4754]
whence:
-log(0.4754) = 0.7437
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)