PyTorch torch.nn.L1Loss 関数

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


torch.nn.L1Lossは PyTorch の L1 損失関数で、平均絶対誤差(MAE)とも呼ばれます。

関数定義

torch.nn.L1Loss(reduction='mean')

使用例

例1: 基本的な使い方

実例

import torch
import torch.nn as nn

criterion = nn.L1Loss()

pred = torch.tensor([3.0, 4.0, 5.0])
target = torch.tensor([2.0, 4.5, 5.5])

loss = criterion(pred, target)
print("L1 Loss:", loss.item())

# 手動検証
manual = (pred - target).abs().mean()
print("手動計算:", manual.item())

例2: MSEとの比較

実例

import torch
import torch.nn as nn

pred = torch.tensor([10.0, 20.0])
target = torch.tensor([0.0, 0.0])

print("L1 Loss(外れ値に対してロバスト):", nn.L1Loss()(pred, target).item())
print("MSE Loss(外れ値に敏感):", nn.MSELoss()(pred, target).item())

使用シーン

  • 回帰タスク: ロバスト性が必要
  • 外れ値: ノイズデータ
  • L1正則化: スパース化

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

その他の拡張