损失函数
损失函数衡量模型预测与真实值的差距。训练的目标就是最小化损失。
MSE:均方误差
Section titled “MSE:均方误差”最常用的回归损失:
import torchimport torch.nn as nn
y_true = torch.tensor([3.0, 5.0, 2.0])y_pred = torch.tensor([2.8, 4.5, 2.5])
mse = nn.MSELoss()(y_pred, y_true)print(f"MSE: {mse:.4f}")MAE:平均绝对误差
Section titled “MAE:平均绝对误差”对异常值更鲁棒:
mae = nn.L1Loss()(y_pred, y_true)print(f"MAE: {mae:.4f}")| 损失 | 对异常值 | 梯度 |
|---|---|---|
| MSE | 敏感(平方放大误差) | 随误差线性变化 |
| MAE | 鲁棒 | 恒为 ±1 |
Cross-Entropy:交叉熵
Section titled “Cross-Entropy:交叉熵”分类任务的标准损失:
# 多分类logits = torch.randn(3, 5) # 3 个样本,5 个类别labels = torch.tensor([1, 3, 0])
ce = nn.CrossEntropyLoss()(logits, labels)print(f"Cross-Entropy: {ce:.4f}")
# 二分类bce = nn.BCEWithLogitsLoss()(torch.randn(3), torch.rand(3))print(f"BCE: {bce:.4f}")Triplet Loss
Section titled “Triplet Loss”让同类样本靠近,异类样本远离:
# anchor: 基准样本,positive: 同类,negative: 异类triplet_loss = nn.TripletMarginLoss(margin=1.0)
anchor = torch.randn(10, 128)positive = torch.randn(10, 128)negative = torch.randn(10, 128)
loss = triplet_loss(anchor, positive, negative)print(f"Triplet Loss: {loss:.4f}")损失函数选择指南
Section titled “损失函数选择指南”| 任务 | 损失函数 | 输出层 |
|---|---|---|
| 回归 | MSE 或 MAE | 无激活 |
| 二分类 | BCEWithLogitsLoss | 无激活(内置 Sigmoid) |
| 多分类 | CrossEntropyLoss | 无激活(内置 Softmax) |
| 多标签分类 | BCEWithLogitsLoss | 无激活 |
| 对比学习 | TripletLoss / InfoNCE | L2 归一化 |