PyTorch 損失関数

損失関数(Loss Function)は、モデルの予測値と真の値の差を測定し、ニューラルネットワークトレーニングの中心的な指針です。オプティマイザは損失関数を最小化することでモデルのパラメータを更新します。

PyTorch は、torch.nnモジュール内に十数種類の一般的な損失関数を組み込んでおり、分類・回帰・ランキングなどの主要なタスクタイプをカバーしています。


1. 損失関数の基礎

基本的な使い方

すべてのPyTorch損失関数は、nn.Moduleのサブクラスで、使用方法は統一されています:

例

import torch
import torch.nn as nn

# 1. 損失関数をインスタンス化する
criterion = nn.CrossEntropyLoss()

# 2. 損失を計算する(予測値が前、真の値が後)
loss = criterion(predictions, targets)

# 3. 逆伝播する
loss.backward()

予測値の形状の取り決め

損失関数によって入力の形状に対する要件が異なり、これは初心者が最も間違いやすいポイントです:

損失関数予測値(input)の形状ラベル(target)の形状
CrossEntropyLoss(N, C)元のロジット(N,)整数のクラスインデックス
BCELoss(N,)Sigmoidを適用した確率(N,)0/1の浮動小数点数
BCEWithLogitsLoss(N,)元のロジット(N,)0/1の浮動小数点数
MSELoss(N,)任意の実数(N,)任意の実数
NLLLoss(N, C)log_softmaxを適用した確率(N,)整数のクラスインデックス

N = batch size,C= クラス数


2. 分類タスクの損失関数

2.1 CrossEntropyLoss 交差エントロピー損失

最も一般的な多クラス分類の損失関数で、内部で自動的に Softmax + 対数 + 負号 を実行します、モデルの出力に手動でSoftmaxを適用する必要はありません。

数式:

Loss = -sum(y_c * log(p_c))

ここで p_c = exp(x_c) / sum_j exp(x_j) は Softmax の出力です。

例

import torch
import torch.nn as nn

criterion = nn.CrossEntropyLoss()

# モデル出力:元のロジット、shape (batch_size, num_classes)
# 事前にSoftmaxを実行する必要はありません!
predictions = torch.tensor([
    [2.0, 0.5, 0.3],   # サンプル1、最も可能性が高いのはクラス0
    [0.1, 3.0, 0.2],   # サンプル2、最も可能性が高いのはクラス1
    [0.2, 0.1, 4.0],   # サンプル3、最も可能性が高いのはクラス2
])

# ラベル:整数のクラスインデックス、shape (batch_size,)
targets = torch.tensor([0, 1, 2])

loss = criterion(predictions, targets)
print(f"Loss: {loss.item():.4f}")  # Loss: 0.1763

ソフトラベル(ラベルスムージング)に対応:

例

# ラベルスムージング、過適合を緩和、画像分類コンペでよく使用される
criterion = nn.CrossEntropyLoss(label_smoothing=0.1)

# ソフトラベル(確率分布)を直接渡すこともサポート
soft_targets = torch.tensor([
    [0.9, 0.05, 0.05],
    [0.05, 0.9, 0.05],
])
predictions = torch.randn(2, 3)
loss = criterion(predictions, soft_targets)

適用シーン:多クラス分類(猫/犬/鳥)、画像分類、テキスト分類など、すべての多クラス分類タスク。


2.2 BCELoss バイナリ交差エントロピー損失

専用に使用されるのは二値分類或マルチラベル分類タスクで、入力は必ずSigmoid処理後の確率値(0〜1)である必要があります。

数式:

Loss = -[y * log(p) + (1-y) * log(1-p)]

例

criterion = nn.BCELoss()

# モデル出力は必ずSigmoidを通過する必要があり、値の範囲は (0, 1)
raw_output = torch.tensor([2.0, -1.0, 0.5, -3.0])
predictions = torch.sigmoid(raw_output)   # [0.88, 0.27, 0.62, 0.05]

# ラベル:浮動小数点型の0.0または1.0
targets = torch.tensor([1.0, 0.0, 1.0, 0.0])

loss = criterion(predictions, targets)
print(f"Loss: {loss.item():.4f}")  # Loss: 0.2824

# マルチラベル分類(各サンプルは複数のクラスに属することができる)
# predictions shape: (batch_size, num_labels)
predictions_ml = torch.sigmoid(torch.randn(4, 5))
targets_ml     = torch.randint(0, 2, (4, 5)).float()
loss_ml = criterion(predictions_ml, targets_ml)

BCELoss入力が (0, 1) の範囲にあることを要求し、元のロジットを渡すと数値が不安定になったりNaNになることがあります。以下の使用を推奨します。BCEWithLogitsLoss。


2.3 BCEWithLogitsLoss

BCELossの改良版で、内部で自動的にSigmoidを実行します、数値がより安定しており、優先的に使用することをお勧めします。

例

criterion = nn.BCEWithLogitsLoss()

# 元のロジットを直接渡すので、手動のSigmoidは不要
predictions = torch.tensor([2.0, -1.0, 0.5, -3.0])
targets     = torch.tensor([1.0,  0.0, 1.0,  0.0])

loss = criterion(predictions, targets)
print(f"Loss: {loss.item():.4f}")

# 次と同等(ただし数値的により安定):
# loss = BCELoss(Sigmoid(predictions), targets)

正サンプルの重み付き(クラスの不均衡の処理):

例

# pos_weight:正サンプルの重み。値が大きいほど正サンプルに注目
# 例:負サンプルが正サンプルの10倍の場合、pos_weight=10に設定
pos_weight = torch.tensor([10.0])
criterion = nn.BCEWithLogitsLoss(pos_weight=pos_weight)

適用シーン:二値分類(スパムメール判定)、マルチラベル分類(文章のマルチラベル付与)、物体検出(前景/背景判定)。


2.4 NLLLoss 負の対数尤度損失

モデルの出力に手動でlog_softmaxを実行する必要があり、柔軟性が高くなります。CrossEntropyLoss = LogSoftmax + NLLLoss。

例

criterion = nn.NLLLoss()

# 事前に手動でlog_softmaxを実行する必要があります
raw_output   = torch.randn(4, 3)   # (batch, num_classes)
log_probs    = torch.log_softmax(raw_output, dim=1)

targets = torch.tensor([0, 2, 1, 0])
loss = criterion(log_probs, targets)

使用シーン:中間ステップでlog確率を使用する必要がある場合(CTC、ビームサーチなど)。それ以外の場合は、次を優先的に使用します。CrossEntropyLoss。


3. 回帰タスクの損失関数

3.1 MSELoss 平均二乗誤差

最も古典的な回帰損失で、大きな誤差に非常に敏感です(二乗によって大きな誤差の影響が拡大されるため)。

数式:

MSELoss = (1/N) * sum((y_i - y_hat_i)^2)

例

criterion = nn.MSELoss()

predictions = torch.tensor([2.5, 0.5, 2.0, 8.0])
targets     = torch.tensor([3.0, -0.5, 2.0, 7.0])

loss = criterion(predictions, targets)
print(f"MSE Loss: {loss.item():.4f}")  # MSE Loss: 0.3750

# 手動で検証
manual = ((predictions - targets) ** 2).mean()
print(f"手動計算: {manual.item():.4f}")  # 0.3750

適用シーン:住宅価格予測、気温予測などの連続値回帰で、データに明確な外れ値がない場合に効果的です。


3.2 L1Loss 平均絶対誤差

に対して外れ値(outlier)に対してよりロバストです二乗ではなく絶対値を取るため、大きな誤差が過度に拡大されることはありません。

数式:

L1Loss = (1/N) * sum(|y_i - y_hat_i|)

例

criterion = nn.L1Loss()

predictions = torch.tensor([2.5, 0.5, 2.0, 8.0])
targets     = torch.tensor([3.0, -0.5, 2.0, 7.0])

loss = criterion(predictions, targets)
print(f"L1 Loss: {loss.item():.4f}")  # L1 Loss: 0.5000

3.3 SmoothL1Loss Huber損失

MSEとL1の利点を融合:誤差が小さい場合はMSE(平滑で勾配が安定)、誤差が大きい場合はL1(外れ値に頑健)を使用します。物体検出(Faster R-CNN)における標準的な損失です。

数式:

SmoothL1(x) = 0.5*x^2 if |x| < 1, else |x| - 0.5

例

criterion = nn.SmoothL1Loss()

predictions = torch.tensor([2.5, 0.5, 2.0, 8.0])
targets     = torch.tensor([3.0, -0.5, 2.0, 7.0])

loss = criterion(predictions, targets)
print(f"SmoothL1 Loss: {loss.item():.4f}")

3つの回帰損失の比較:

例

import torch
import torch.nn as nn

predictions = torch.tensor([0.0, 1.0, 5.0, 10.0])  # 異なる大きさの誤差をシミュレーション
targets     = torch.zeros(4)

for name, fn in [("MSELoss", nn.MSELoss(reduction='none')),
                 ("L1Loss",  nn.L1Loss(reduction='none')),
                 ("SmoothL1",nn.SmoothL1Loss(reduction='none'))]:
    losses = fn(predictions, targets)
    print(f"{name:12s}: {[f'{l:.2f}' for l in losses.tolist()]}")
输出示例:
MSELoss     : ['0.00', '1.00', '25.00', '100.00']   # 大误差被平方放大
L1Loss      : ['0.00', '1.00',  '5.00',  '10.00']   # 线性增长
SmoothL1    : ['0.00', '0.50',  '4.50',   '9.50']   # 中间值

適用シーン:物体検出のバウンディングボックス回帰、深度推定など、小さな誤差と外れ値の両方が存在する回帰タスク。


4. 発展的な損失関数

4.1 HuberLoss

SmoothL1Lossの汎用版で、カスタム切替閾値を許可しますdelta(デフォルトは1.0)。

例

# delta は MSE と L1 の切り替えポイントを制御する
criterion = nn.HuberLoss(delta=1.5)

predictions = torch.randn(10)
targets     = torch.randn(10)
loss = criterion(predictions, targets)

4.2 KLDivLoss KLダイバージェンス

2つの確率分布の差異を測るもので、よく使われるのは知識蒸留と変分オートエンコーダー(VAE)。

数式:

KL(P || Q) = sum(P(i) * log(P(i) / Q(i)))

例

criterion = nn.KLDivLoss(reduction='batchmean')

# input は log 確率(対数確率)である必要があり、target は通常の確率
log_predictions = torch.log_softmax(torch.randn(4, 5), dim=1)
targets         = torch.softmax(torch.randn(4, 5), dim=1)

loss = criterion(log_predictions, targets)
print(f"KL Div Loss: {loss.item():.4f}")

知識蒸留での典型的な使い方:

例

temperature = 4.0  # 温度係数。大きいほどソフトになる

# 教師モデルの出力
teacher_logits = torch.randn(32, 10)
# 生徒モデルの出力
student_logits = torch.randn(32, 10)

soft_labels = torch.softmax(teacher_logits / temperature, dim=1)
soft_preds  = torch.log_softmax(student_logits / temperature, dim=1)

distill_loss = nn.KLDivLoss(reduction='batchmean')(soft_preds, soft_labels)
distill_loss *= temperature ** 2  # 勾配の大きさを元に戻す

4.3 MarginRankingLoss ランキング損失

2つの入力の相対的な順序を判定するもので、よく使われるのはランキング学習と類似度学習。

例

criterion = nn.MarginRankingLoss(margin=0.5)

# x1 は x2 よりも target に近いはず(y=1 は x1 > x2 を意味する)
x1 = torch.tensor([0.8, 0.3, 0.6])
x2 = torch.tensor([0.2, 0.7, 0.5])
y  = torch.tensor([1.0, -1.0, 1.0])  # 1: x1>x2, -1: x1<x2

loss = criterion(x1, x2, y)

4.4 TripletMarginLoss トリプレット損失

メトリック学習に使用され、以下の条件を要求するanchor(アンカー)とpositive(同類)との距離がnegative(異類)との距離よりも小さいこと。

例

criterion = nn.TripletMarginLoss(margin=1.0)

# 各ベクトルの次元は embedding_dim
anchor   = torch.randn(32, 128)   # アンカーサンプル
positive = torch.randn(32, 128)   # 同類サンプル
negative = torch.randn(32, 128)   # 異類サンプル

loss = criterion(anchor, positive, negative)
# 目標:dist(anchor, positive) + margin < dist(anchor, negative)

適用シーン:顔認証、画像検索、Few-Shot Learning。


4.5 CTCLoss 系列ラベリング損失

使用されるのは入力と出力の長さが一致しない系列タスク。例:音声認識(音響系列 -> テキスト系列)、手書き文字認識。

例

criterion = nn.CTCLoss(blank=0)  # blank ラベルインデックス

# log_probs: (T, N, C) T=タイムステップ, N=batch, C=クラス数
T, N, C = 50, 4, 20
log_probs    = torch.log_softmax(torch.randn(T, N, C), dim=2)
targets      = torch.randint(1, C, (N * 10,))   # 連結したターゲット系列
input_lengths  = torch.full((N,), T, dtype=torch.long)
target_lengths = torch.full((N,), 10, dtype=torch.long)

loss = criterion(log_probs, targets, input_lengths, target_lengths)

5. reductionパラメータの詳細

すべての損失関数がサポートするreductionパラメータは、サンプル損失をどのように集約するかを制御する:

例

predictions = torch.tensor([1.0, 2.0, 3.0, 4.0])
targets     = torch.tensor([1.5, 2.5, 2.0, 5.0])

# 単一サンプルの誤差: [0.25, 0.25, 1.00, 1.00]

# mean(デフォルト):全サンプルの平均を取る
loss_mean = nn.MSELoss(reduction='mean')(predictions, targets)
print(f"mean:  {loss_mean.item():.4f}")   # 0.6250

# sum:全サンプルの合計を取る
loss_sum  = nn.MSELoss(reduction='sum')(predictions, targets)
print(f"sum:   {loss_sum.item():.4f}")    # 2.5000

# none:各サンプルの独立した損失を返す(重み付けによく使われる)
loss_none = nn.MSELoss(reduction='none')(predictions, targets)
print(f"none:  {loss_none.tolist()}")     # [0.25, 0.25, 1.0, 1.0]

reduction='none'の実際の応用——異なるサンプルへの重み付け:

例

# 誤差が大きいサンプルにより高い重みを与える(フォーカル損失の考え方)
per_sample_loss = nn.MSELoss(reduction='none')(predictions, targets)
weights = torch.tensor([1.0, 1.0, 2.0, 2.0])   # 手動で重みを設定
weighted_loss = (per_sample_loss * weights).mean()

6. クラス重みとサンプル重み

クラス重み(クラスの不均衡の処理)

データセット内の特定のクラスのサンプルが極端に少ない場合、少数クラスにより高い重みを与えられる:

例

# 3クラス分類とする。クラス 0 は 1000 個、クラス 1 は 100 個、クラス 2 は 50 個
# 重みは頻度に反比例
class_counts = torch.tensor([1000.0, 100.0, 50.0])
weights = 1.0 / class_counts
weights = weights / weights.sum() * len(weights)  # 正規化

criterion = nn.CrossEntropyLoss(weight=weights)

特定のラベルを無視する

セマンティックセグメンテーションなどのタスクでは、境界ピクセル(ラベル 255)を無視する必要があることがよくある:

例

# ignore_index:損失計算時にこのラベルを無視する
criterion = nn.CrossEntropyLoss(ignore_index=255)

# セマンティックセグメンテーションのシーン
predictions = torch.randn(2, 21, 256, 256)   # (N, C, H, W)
targets     = torch.randint(0, 22, (2, 256, 256))
targets[targets == 21] = 255                  # 境界は 255 とラベル付けされる

loss = criterion(predictions, targets)

7. カスタム損失関数

組み込みの損失関数で要件を満たせない場合、2つの方法でカスタマイズできる:

方法1:関数形式(簡単)

例

import torch
import torch.nn.functional as F

def focal_loss(predictions, targets, gamma=2.0, alpha=0.25):
    """
Focal Loss:物体検出における正負サンプルの深刻な不均衡問題を解決する
分類が容易なサンプルの重みを下げ、モデルを困難なサンプルに集中させる
    """

    ce_loss = F.cross_entropy(predictions, targets, reduction='none')
    pt = torch.exp(-ce_loss)                          # 正しく予測された確率
    focal_weight = alpha * (1 - pt) ** gamma          # 困難なサンプルの重みがより高い
    return (focal_weight * ce_loss).mean()


# 使用
predictions = torch.randn(8, 10)
targets     = torch.randint(0, 10, (8,))
loss = focal_loss(predictions, targets)

方法2:nn.Moduleを継承(推奨)

例

import torch
import torch.nn as nn

class DiceLoss(nn.Module):
    """
Dice Loss:画像セグメンテーションでよく使われ、Dice 係数を直接最適化する
クラスの不均衡(例:小物体のセグメンテーション)に対して CrossEntropy よりロバスト
    """

    def __init__(self, smooth=1.0):
        super().__init__()
        self.smooth = smooth

    def forward(self, predictions, targets):
        # predictions: (N, C, H, W) -> sigmoid を通過した確率
        # targets: (N, C, H, W) -> one-hot エンコードされたラベル
        predictions = torch.sigmoid(predictions)

        # (N, -1) にフラット化
        pred_flat   = predictions.view(predictions.size(0), -1)
        target_flat = targets.view(targets.size(0), -1).float()

        intersection = (pred_flat * target_flat).sum(dim=1)
        dice = (2.0 * intersection + self.smooth) / (
            pred_flat.sum(dim=1) + target_flat.sum(dim=1) + self.smooth
        )
        return 1 - dice.mean()


class CombinedLoss(nn.Module):
    """
組み合わせ損失:CrossEntropy + Dice。ピクセルレベルの分類と領域の重なりを両立する
画像セグメンテーションでよく使われる組み合わせ
    """

    def __init__(self, ce_weight=0.5, dice_weight=0.5):
        super().__init__()
        self.ce_weight   = ce_weight
        self.dice_weight = dice_weight
        self.ce   = nn.CrossEntropyLoss()
        self.dice = DiceLoss()

    def forward(self, predictions, targets):
        return (self.ce_weight   * self.ce(predictions, targets) +
                self.dice_weight * self.dice(predictions, targets))


# 使用
criterion = CombinedLoss(ce_weight=0.4, dice_weight=0.6)

8. 損失関数選択ガイド

タスクの種類に応じて選択する

タスクの種類推奨損失関数備考
多クラス分類CrossEntropyLoss最も汎用的で、優先的に選択
多クラス分類(クラスの不均衡)CrossEntropyLoss(weight=...)少数クラスに重み付け
多クラス分類(ラベルノイズが大きい)CrossEntropyLoss(label_smoothing=0.1)過学習を防ぐ
二値分類BCEWithLogitsLossBCELoss より安定
マルチラベル分類BCEWithLogitsLoss各ラベルを独立に判定
物体検出(分類ヘッド)CrossEntropyLoss / Focal Loss正負サンプルの不均衡時は Focal を使用
物体検出(回帰ヘッド)SmoothL1Loss / GIoULoss標準的な手法
通常の回帰MSELoss外れ値がない場合は第一候補
外れ値を含む回帰HuberLoss / SmoothL1Lossロバスト回帰
画像セグメンテーションCrossEntropyLoss + DiceLoss組み合わせて使うと効果的
音声認識CTCLoss系列アライメント
メトリック学習 / 顔認証TripletMarginLoss特徴空間の距離を学習
知識蒸留KLDivLossソフトラベルの分布を学習

よくある誤用と注意点

例

# 誤り:CrossEntropyLoss の前に手動で Softmax を行った
output = torch.softmax(model(x), dim=1)   # 余分な softmax
loss   = nn.CrossEntropyLoss()(output, targets)  # 内部でさらに一度行われる

# 正しい:logits を直接渡す
output = model(x)  # 生の logits
loss   = nn.CrossEntropyLoss()(output, targets)


# 誤り:BCELoss に sigmoid を適用していない生の値を渡した
loss = nn.BCELoss()(model(x), targets)    # [0,1] を超える可能性があり、数値が不安定

# 正しい:BCEWithLogitsLoss を使用
loss = nn.BCEWithLogitsLoss()(model(x), targets)


# 誤り:ラベルの型が一致しない(整数型 vs 浮動小数点型)
targets = torch.tensor([1, 0, 1])                     # int 型
loss    = nn.BCEWithLogitsLoss()(preds, targets)       # エラーになる!

# 正しい:BCEWithLogitsLoss は float ラベルが必要
targets = torch.tensor([1.0, 0.0, 1.0])               # float 型
loss    = nn.BCEWithLogitsLoss()(preds, targets)       # 正しい


# 誤り:loss に .item() を使っていないため、計算グラフが蓄積し続け、GPUメモリがオーバーフローする
total_loss += loss      # loss はテンソルであり、計算グラフを保持している

# 正しい:.item() でスカラーを取り出す
total_loss += loss.item()

完全なトレーニング例

例

import torch
import torch.nn as nn
import torch.optim as optim

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

# モデル & 損失関数 & オプティマイザ
model     = MyModel().to(device)
criterion = nn.CrossEntropyLoss(label_smoothing=0.1)
optimizer = optim.Adam(model.parameters(), lr=1e-3)

for epoch in range(num_epochs):
    model.train()
    total_loss, correct = 0.0, 0

    for inputs, labels in train_loader:
        inputs = inputs.to(device)
        labels = labels.to(device)

        optimizer.zero_grad()
        outputs = model(inputs)          # 生の logits

        loss = criterion(outputs, labels)
        loss.backward()
        optimizer.step()

        total_loss += loss.item() * inputs.size(0)    # .item() でスカラーを取得
        correct    += (outputs.argmax(1) == labels).sum().item()

    avg_loss = total_loss / len(train_loader.dataset)
    accuracy = correct / len(train_loader.dataset)
    print(f"Epoch {epoch+1} | Loss: {avg_loss:.4f} | Acc: {accuracy:.4f}")
その他の拡張