PyTorch中的`CrossEntropyLoss()`函数

交叉熵公式:

enter image description here

但是为什么下面的代码会得到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

Related Posts

L1-L2正则化的不同系数

我想对网络的权重同时应用L1和L2正则化。然而,我找不…

使用scikit-learn的无监督方法将列表分类成不同组别,有没有办法?

我有一系列实例,每个实例都有一份列表,代表它所遵循的不…

f1_score metric in lightgbm

我想使用自定义指标f1_score来训练一个lgb模型…

通过相关系数矩阵进行特征选择

我在测试不同的算法时,如逻辑回归、高斯朴素贝叶斯、随机…

可以将机器学习库用于流式输入和输出吗?

已关闭。此问题需要更加聚焦。目前不接受回答。 想要改进…

在TensorFlow中,queue.dequeue_up_to()方法的用途是什么?

我对这个方法感到非常困惑,特别是当我发现这个令人费解的…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注