PyTorch torch.nn.BCEWithLogitsLoss 関数

PyTorch torch.nn 参考手册PyTorch torch.nn リファレンスマニュアル


torch.nn.BCEWithLogitsLossPyTorch の二値交差エントロピー損失関数(Sigmoid 付き)です。

Sigmoid と BCE を組み合わせ、数値的に安定しており、二分類タスクに使用されます。

関数定義

torch.nn.BCEWithLogitsLoss(weight=None, reduction='mean', pos_weight=None)

パラメータ:

  • weight: 手動の重み
  • pos_weight: 正クラスの重み。クラスの不均衡に使用します。

使用例

例 1: 基本的な使い方

例

import torch
import torch.nn as nn

criterion = nn.BCEWithLogitsLoss()

# 正規化されていない logits
logits = torch.tensor([2.0, -1.0, 0.5, -3.0])
# 二値ラベル
targets = torch.tensor([1.0, 0.0, 1.0, 0.0])

loss = criterion(logits, targets)
print("BCE Loss:", loss.item())

# 手動検証:Sigmoid + BCE
sigmoid = torch.sigmoid(logits)
bce = nn.BCELoss()(sigmoid, targets)
print("手動 BCE:", bce.item())

例 2: クラスの不均衡

例

import torch
import torch.nn as nn

# 正クラスの重み:正サンプルの重要度を高める
pos_weight = torch.tensor([5.0])
criterion = nn.BCEWithLogitsLoss(pos_weight=pos_weight)

logits = torch.randn(10, 1)
targets = torch.zeros(10, 1)
targets[:2] = 1.0  # 正クラスが少ない

loss = criterion(logits, targets)
print("重み付き BCE Loss:", loss.item())

例 3: マルチラベル分類

例

import torch
import torch.nn as nn

# マルチラベル二分類
criterion = nn.BCEWithLogitsLoss()

# batch=4、5つのクラス、それぞれ 0 または 1
logits = torch.randn(4, 5)
labels = torch.randint(0, 2, (4, 5)).float()

loss = criterion(logits, labels)
print("マルチラベル Loss:", loss.item())

使用シーン

  • 二分類: 単一ラベル
  • マルチラベル分類: 各ラベルが独立
  • クラスの不均衡: pos_weight を使用

注意:入力は logits であり、事前に Sigmoid を適用する必要はありません。


PyTorch torch.nn 参考手册PyTorch torch.nn リファレンスマニュアル

その他の拡張