NLLLoss#
- class torch.nn.modules.loss.NLLLoss(weight=None, size_average=None, ignore_index=-100, reduce=None, reduction='mean')[源代码]#
负对数似然损失。它适用于训练一个有 C 个类别的分类问题。
如果提供了可选参数
weight
,它应该是一个一维张量,为每个类别分配权重。当你有一个不平衡的训练集时,这尤其有用。通过前向调用输入的 input 期望包含每个类别的对数概率。 input 必须是一个大小为 或 with for the K-dimensional case. The latter is useful for higher dimension inputs, such as computing NLL loss per-pixel for 2D images.
在神经网络中,通过在网络的最后一层添加 LogSoftmax 层可以轻松获得对数概率。如果你不想添加额外的层,也可以使用 CrossEntropyLoss。
此损失期望的 target 应该是类索引,范围在 内,其中 C = number of classes。如果指定了 ignore_index,此损失也将接受该类索引(该索引不一定在类别范围内)。
未约简的(即
reduction
设置为'none'
)损失可以描述为其中 是输入, 是目标, 是权重, 是批次大小。如果
reduction
不是'none'
(默认为'mean'
),则:- 参数
weight (Tensor, optional) – 手动为每个类别指定的重缩放权重。如果指定,它必须是一个大小为 C 的张量。否则,假定其所有元素为 1。
size_average (bool, optional) – 已弃用 (请参阅
reduction
)。默认情况下,损失在批次中的每个损失元素上进行平均。请注意,对于某些损失,每个样本有多个元素。如果size_average
字段设置为False
,则损失在每个小批次中进行累加。当reduce
设置为False
时忽略。默认为None
ignore_index (int, optional) – 指定一个被忽略的目标值,它不会对输入梯度做出贡献。当
size_average
为True
时,损失在非忽略的目标上进行平均。reduce (bool, optional) – 已弃用 (请参阅
reduction
)。默认情况下,损失根据size_average
在每个小批次中进行平均或累加。当reduce
为False
时,返回每个批次元素的损失,并忽略size_average
。默认为None
reduction (str, optional) – 指定应用于输出的缩减方式:
'none'
|'mean'
|'sum'
。'none'
:不应用缩减,'mean'
:取输出的加权平均值,'sum'
:对输出进行累加。注意:size_average
和reduce
正在被弃用,在此期间,指定其中任何一个参数将覆盖reduction
。默认为'mean'
- 形状:
输入: 或 ,其中 C = number of classes,N = batch size,或者 with for the K-dimensional loss.
Target: or , where each value is , or with in the case of K-dimensional loss.
输出:如果
reduction
是'none'
,形状为 或 with in the case of K-dimensional loss. Otherwise, scalar.
示例
>>> log_softmax = nn.LogSoftmax(dim=1) >>> loss_fn = nn.NLLLoss() >>> # input to NLLLoss is of size N x C = 3 x 5 >>> input = torch.randn(3, 5, requires_grad=True) >>> # each element in target must have 0 <= value < C >>> target = torch.tensor([1, 0, 4]) >>> loss = loss_fn(log_softmax(input), target) >>> loss.backward() >>> >>> >>> # 2D loss example (used, for example, with image inputs) >>> N, C = 5, 4 >>> loss_fn = nn.NLLLoss() >>> data = torch.randn(N, 16, 10, 10) >>> conv = nn.Conv2d(16, C, (3, 3)) >>> log_softmax = nn.LogSoftmax(dim=1) >>> # output of conv forward is of shape [N, C, 8, 8] >>> output = log_softmax(conv(data)) >>> # each element in target must have 0 <= value < C >>> target = torch.empty(N, 8, 8, dtype=torch.long).random_(0, C) >>> # input to NLLLoss is of size N x C x height (8) x width (8) >>> loss = loss_fn(output, target) >>> loss.backward()