NLLLoss
- classtorch.nn.NLLLoss(weight=None, size_average=None, ignore_index=-100, reduce=None, reduction='mean')[源代码]
-
负对数似然损失。它适用于训练包含C个类别的分类问题。
如果提供了可选参数
weight
,它应该是一个1D张量,用于为每个类别分配权重。这对于处理不平衡的训练集尤其有用。通过前向调用提供的input应包含每个类别的对数概率。input必须是一个张量,其大小为$(minibatch, C)$或$(minibatch, C, d_1, d_2, ..., d_K)$(其中$K \geq 1$),适用于K-维情况。后者对于高维度输入特别有用,例如计算2D图像中每个像素的NLL损失。
在神经网络中获取对数概率的方法是在最后一层添加一个 LogSoftmax 层。如果你想避免增加额外的层,也可以选择使用 CrossEntropyLoss。
此损失函数期望的target应该是范围内的一个类索引$[0, C-1]$\,其中C = 类别数量。如果指定了ignore_index,该损失函数也会接受这个类别索引(此索引不一定在类别范围内)。
当
reduction
设置为'none'
时,损失可以描述为未减少的:$\ell(x, y) = L = \{l_1,\dots,l_N\}^\top, \quad l_n = - w_{y_n} x_{n,y_n}, \quad w_{c} = \text{weight}[c] \cdot \mathbb{1}\{c \not= \text{ignore\_index}\},$其中$x$ 是输入,$y$ 是目标,$w$ 是权重,$N$ 是批量大小。如果
reduction
不是'none'
(默认为'mean'
),则$\ell(x, y) = \begin{cases} \sum_{n=1}^N \frac{1}{\sum_{n=1}^N w_{y_n}} l_n, & \text{if reduction} = \text{`mean';}\\ \sum_{n=1}^N l_n, & \text{if reduction} = \text{`sum'.} \end{cases}$- 参数
-
-
weight (Tensor, 可选) – 每个类别的手动重缩放权重。如果提供,它必须是一个大小为 C 的张量;否则,默认所有值都为1。
-
size_average (bool, optional) – 已弃用(请参见
reduction
)。默认情况下,损失值会在批次中的每个元素上进行平均计算。需要注意的是,对于某些损失函数,每个样本包含多个元素。如果将size_average
设置为False
,则损失值会针对每个小批量求和。当reduce
为False
时,此参数会被忽略。默认值:None
-
ignore_index (int, 可选) – 指定一个被忽略的目标值,该目标值不会对输入梯度产生影响。当
size_average
为True
时,损失会基于非忽略的目标进行平均计算。 -
reduce (bool, optional) – 已弃用(请参见
reduction
)。默认情况下,损失根据size_average
在每个小批量中进行平均或求和。当reduce
为False
时,返回每批元素的损失,并忽略size_average
设置。默认值:None
-
reduction (str, 可选) – 指定要应用于输出的缩减方式:
'none'
|'mean'
|'sum'
。'none'
: 不进行任何缩减,'mean'
: 计算加权平均值,'sum'
: 对输出求和。注意:size_average
和reduce
正在被弃用,在此期间,指定这两个参数中的任何一个将覆盖reduction
参数。默认值:'mean'
-
- 形状:
-
-
输入: (N, C) 或 (C),其中 C = 类别数量, N = 批量大小。在K-维损失的情况下,输入为 (N, C, d_1, d_2, ..., d_K),且 $K \geq 1$
-
目标: $(N)$ 或 $()$,其中每个值满足 $0 \leq \text{targets}[i] \leq C-1$。在 K 维损失的情况下,目标为 $(N, d_1, d_2, ..., d_K)$ 且 $K \geq 1$。
-
输出:如果
reduction
是'none'
,形状为 $(N)$ 或 $(N, d_1, d_2, ..., d_K)$(其中 K 维损失的情况下 $K \geq 1$)。否则为标量。
-
示例:
>>> 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()