gpt4 book ai didi

python - PyTorch 中的交叉熵

转载 作者:行者123 更新时间:2023-11-30 08:21:34 25 4
gpt4 key购买 nike

交叉熵公式:

enter image description here

但是为什么下面给出的是 loss = 0.7437 而不是 loss = 0(因为 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 函数的概率。

因此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

关于python - PyTorch 中的交叉熵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49390842/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com