nll_loss
torhc.nn.functional中给出的关于nll_loss的一个样例
target: 数值 <= C-1, 一般可以看作一个一维列表,存放的是真实类别编号
先经过softmax,再经过log,最后再使用nll_loss
# input is of size N x C = 3 x 5
input = torch.randn(3, 5, requires_grad=True)
# each element in target has to have 0 <= value < C
target = torch.tensor([1, 0, 4])
output = F.nll_loss(F.log_softmax(input), target)
output.backward()
cross_entropy
cross_entropy只是在输入上和nll_loss有所不同,我们不需要对input进行softmax和log
def cross_entropy(input, target, weight=None, size_average=None, ignore_index=-100,
reduce=None, reduction='mean'):
return nll_loss(log_softmax(input, 1), target, weight, None, ignore_index, None, reduction)
可以看到源码中依旧调用了nll_loss方法,我们只是在输入时不需要进行过多处理
总结
使用看个人习惯