PyTorch torch.nn.NLLLoss 関数
torch.nn.NLLLossこれは PyTorch における負の対数尤度損失です。
多クラス分類タスクに使用され、LogSoftmax と組み合わせて使用する必要があります。
関数定義
torch.nn.NLLLoss(weight=None, ignore_index=-100, reduction='mean')
使用例
例 1: 基本的な使い方
例
import torch
import torch.nn as nn
# 先に LogSoftmax、次に NLLLoss
log_softmax = nn.LogSoftmax(dim=1)
nll = nn.NLLLoss()
# モデル出力 (logits)
logits = torch.randn(4, 10)
# log softmax を通過
log_probs = log_softmax(logits)
# 正解ラベル
targets = torch.tensor([2, 5, 1, 7])
loss = nll(log_probs, targets)
print("NLL Loss:", loss.item())
import torch.nn as nn
# 先に LogSoftmax、次に NLLLoss
log_softmax = nn.LogSoftmax(dim=1)
nll = nn.NLLLoss()
# モデル出力 (logits)
logits = torch.randn(4, 10)
# log softmax を通過
log_probs = log_softmax(logits)
# 正解ラベル
targets = torch.tensor([2, 5, 1, 7])
loss = nll(log_probs, targets)
print("NLL Loss:", loss.item())
例 2: CrossEntropyLoss と同等
例
import torch
import torch.nn as nn
logits = torch.randn(4, 10)
targets = torch.tensor([2, 5, 1, 7])
# 方法1:CrossEntropyLoss を直接使用
loss1 = nn.CrossEntropyLoss()(logits, targets)
# 方法2:LogSoftmax + NLLLoss
loss2 = nn.NLLLoss()(nn.LogSoftmax(dim=1)(logits), targets)
print("CrossEntropyLoss:", loss1.item())
print("LogSoftmax + NLLLoss:", loss2.item())
print(結果は同じ:, abs(loss1 - loss2) < 1e-5)
import torch.nn as nn
logits = torch.randn(4, 10)
targets = torch.tensor([2, 5, 1, 7])
# 方法1:CrossEntropyLoss を直接使用
loss1 = nn.CrossEntropyLoss()(logits, targets)
# 方法2:LogSoftmax + NLLLoss
loss2 = nn.NLLLoss()(nn.LogSoftmax(dim=1)(logits), targets)
print("CrossEntropyLoss:", loss1.item())
print("LogSoftmax + NLLLoss:", loss2.item())
print(結果は同じ:, abs(loss1 - loss2) < 1e-5)
使用シーン
- 多クラス分類: LogSoftmax と組み合わせる
- カスタム損失: 特別なニーズ
注意:CrossEntropyLoss には LogSoftmax が含まれているため、通常は直接使用します。
その他の拡張
PyTorch torch.nn リファレンスマニュアル