PyTorch torch.nn.L1Loss 函数
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())
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())
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 参考手册