pytorch 计算 CrossEntropyLoss 和 softmax 激活层

pytorch 计算 CrossEntropyLoss 不需要经 softmax 层激活!

pytorch 实现自己的网络时,如果使用CrossEntropyLoss 我总是将网路输出经 softmax激活层后再计算交叉熵损失是不对的。

考虑样本空间的类集合为 {0,1,2},网络最后一层有 3 个神经元(每个神经元激活值代表对不同类的响应强度),某个样本送入网络后的输出记为 net_out: [1,2,3], 该样本的真实标签为 0.

那么交叉熵损失的手动计算结果为:

- ln 【 e1 / ( e1 + e2 + e3 ) 】 = 2.4076

  • 网络输出不经 softmax 层,直接由 CrossEntropyLoss 计算交叉熵损失
from torch.autograd import Variable
from torch import nn

in:

net_out = Variable(torch.Tensor([[1,2,3]]))
target = Variable( torch.LongTensor([0]))

criterion = nn.CrossEntropyLoss()
criterion(net_out,target)

out:

Variable containing:
 2.4076
[torch.FloatTensor of size 1]

 输出结果为 2.4076,与手动计算结果一致。

  • 网络输出先经 softmax 层,再由 CrossEntropyLoss 计算交叉熵损失
in:

from torch.autograd import Variable

net_out = Variable(torch.Tensor([[1,2,3]]))
target = Variable( torch.LongTensor([0]))

softmax = nn.Softmax()
print(softmax(net_out))

criterion = nn.CrossEntropyLoss()
print(criterion(softmax(net_out),target))

out:

Variable containing:
 0.0900  0.2447  0.6652
[torch.FloatTensor of size 1x3]

Variable containing:
 1.3724
[torch.FloatTensor of size 1]

输出结果为 1.3724, 与手动计算结果不一致。事实上,CrossEntropyLoss()softmax 和 负对数损失的结合。明确这点后,就不难明白1.374 是怎么来的了:

- ln 【 e0.09 / ( e0.09 + e0.2447 + e0.6552 ) 】 = 1.374

补充:

如果用 nn.BCELoss()计算二进制交叉熵, 需要先将 logitsigmod()层激活再送入 nn.BCELoss() 计算损失。

posted @ 2020-04-25 00:39  龙雪  阅读(646)  评论(4编辑  收藏  举报