NLLLoss¶
- class torch.nn.NLLLoss(weight=None, size_average=None, ignore_index=-100, reduce=None, reduction='mean')[source][source]¶
负对数似然损失(Negative Log Likelihood Loss)。它对于训练 C 类别的分类问题非常有用。
如果提供,可选参数
weight
应是一个 1D 张量,为每个类别分配权重。这在训练集不平衡时特别有用。input 在前向传播中应包含每个类别的对数概率。input 必须是大小为 或 的张量,其中对于 K 维情况,。后者对于更高维度的输入很有用,例如计算二维图像的每个像素的 NLL 损失。
在神经网络中获得对数概率很容易,只需在网络的最后一层添加一个 LogSoftmax 层即可。如果您不想添加额外的层,可以使用 CrossEntropyLoss 代替。
此损失函数期望的 target 应为类别索引,范围在 之间,其中 C = 类别数量;如果指定了 ignore_index,此损失函数也接受该类别索引(此索引不一定在类别范围内)。
未约简(即
reduction
设置为'none'
)的损失可以描述为其中 是输入, 是目标, 是权重, 是批量大小。如果
reduction
不是'none'
(默认为'mean'
),则- 参数
weight (Tensor, 可选) – 为每个类别手动设置的缩放权重。如果给定,它必须是一个大小为 C 的张量。否则,它将被视为全为 1。
size_average (bool, 可选) – 已弃用(参见
reduction
)。默认情况下,损失在批次中的每个损失元素上取平均。注意,对于某些损失,每个样本有多个元素。如果字段size_average
设置为False
,则改为对每个 minibatch 中的损失求和。当reduce
为False
时忽略。默认值:None
ignore_index (int, 可选) – 指定一个将被忽略且不贡献输入梯度的目标值。当
size_average
为True
时,损失将在未被忽略的目标上取平均。reduce (bool, 可选) – 已弃用(参见
reduction
)。默认情况下,损失会根据size_average
在每个 minibatch 的观察值上取平均或求和。当reduce
为False
时,返回每个批次元素的损失,并忽略size_average
。默认值:None
reduction (str, 可选) – 指定应用于输出的约简方式:
'none'
|'mean'
|'sum'
。'none'
:不应用任何约简,'mean'
:计算输出的加权平均值,'sum'
:对输出求和。注意:size_average
和reduce
正在被弃用,在此期间,指定这两个参数中的任何一个都会覆盖reduction
。默认值:'mean'
- 形状:
输入: 或 ,其中 C = 类别数量,N = 批量大小,或 ,其中 ,在K维损失的情况下。
目标: 或 ,其中每个值满足 ,或 ,其中 ,在K维损失的情况下。
输出: 如果
reduction
为'none'
,形状为 或 ,其中 ,在K维损失的情况下。否则,为标量。
示例
>>> 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()