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時忽略。預設為Noneignore_index (int, optional) – 指定一個被忽略的目標值,它不會對輸入梯度做出貢獻。當
size_average為True時,損失在非忽略的目標上進行平均。reduce (bool, optional) – 已棄用 (請參閱
reduction)。預設情況下,損失根據size_average在每個小批次中進行平均或累加。當reduce為False時,返回每個批次元素的損失,並忽略size_average。預設為Nonereduction (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()