交叉熵 = NLL + SOFTMAX Layer
torch.nn.NLLLoss
(weight=None, size_average=None, ignore_index=-100, reduce=None, reduction='mean')
常用于多分类(设为C类)问题,且可以对每个分类提供相应的权重,这对于非平衡数据集的处理非常有用。
输入的数据为一阶张量,数据为对数化的概率,并且nll损失需要一个softmax层,如果不想自己创建该层,则使用交叉熵损失。
输出的数据为在[0,C-1]范围内的一个类别的数据,如:0,1,……,C-1.但是也可以指定ignore_index,就可以忽视某个类。
计算的过程如下:
例子:
#一阶的一个计算的例子
#指定了一个softmax层
import torch
m = torch.nn.LogSoftmax(dim = 1)
loss = torch.nn.NLLLoss()
input = torch.randn(3,5,requires_grad = True)
target = torch.tensor([1,0,4])
output = loss(m(input),target)
output.backward()
torch.nn.CrossEntropyLoss
(weight=None, size_average=None, ignore_index=-100, reduce=None, reduction='mean')
常用于多分类(设为C类)问题,且可以对每个分类提供相应的权重,这对于非平衡数据集的处理非常有用。
输入的数据是没有经过标准化的每一类的“打分”。
输出的数据为在[0,C-1]范围内的一个类别的数据,如:0,1,……,C-1.但是也可以指定ignore_index,就可以忽视某个类。
计算的过程如下:
例子:
#一阶的一个计算的例子
import torch
loss2 = torch.nn.CrossEntropyLoss()
input = torch.randn(3,5,requires_grad = True)
target = torch.tensor([1,0,4])
output2 = loss2(m(input),target)
output2.backward()
pytorch关于NLL的文档
pytorch关于交叉熵的文档