在pytorch中nn.CrossEntropyLoss()是nn.logSoftmax()和nn.NLLLoss()的整合,可以直接使用它来替换网络中的这两个操作。
This criterion combines :func:`nn.LogSoftmax` and :func:`nn.NLLLoss` in one single class。
下面是交叉熵计算公式:
`input` has to be a Tensor of size either :math:`(minibatch, C)` or
:math:`(minibatch, C, d_1, d_2, ..., d_K)`
我的理解是输入必须包含minibatch 和类别数,而target则是减少一个相应的C类别的维度。
如果给定了各个类别的权重,还要乘以权重,为一维权重。
损失函数中的weight为权重参数设置,若设置权重,则公式为:
例子
>>> loss = nn.CrossEntropyLoss()
>>> input = torch.randn(3, 5, requires_grad=True)
>>> target = torch.empty(3, dtype=torch.long).random_(5)
>>> output = loss(input, target)
>>> output.backward()