Skip to content

05. 损失函数

损失函数(Loss Function)衡量预测与真实标签的差距,是模型学习的核心信号。

5.1 损失 vs 评估指标

损失函数 评估指标
可微 ✅ 必须 ❌ 不要求
用途 训练(求梯度) 评估(人看)
特点 平滑、连续 可理解

5.2 回归损失

MSE (Mean Squared Error / L2 Loss)

$$ L = \frac{1}{N}\sum_i (y_i - \hat{y}_i)^2 $$

  • 平方放大异常点 → 对离群值敏感
  • 凸、可微
nn.MSELoss()

MAE (Mean Absolute Error / L1 Loss)

$$ L = \frac{1}{N}\sum_i |y_i - \hat{y}_i| $$

  • 对异常值鲁棒
  • 0 处不可导
nn.L1Loss()

Huber Loss

$$ L_\delta(y, \hat{y}) = \begin{cases} 0.5(y - \hat{y})^2 & |y - \hat{y}| \leq \delta \ \delta(|y - \hat{y}| - 0.5\delta) & \text{else} \end{cases} $$

  • 平方 + 绝对结合
  • 异常鲁棒
nn.HuberLoss(delta=1.0)

Smooth L1

PyTorch 中(Fast R-CNN 引入):

nn.SmoothL1Loss(beta=1.0)

Quantile Loss

$$ L_\tau(y, \hat{y}) = \tau \max(y - \hat{y}, 0) + (1-\tau) \max(\hat{y} - y, 0) $$

分位数回归。

5.3 分类损失

Cross-Entropy (CE)

二分类:

$$ L = -\frac{1}{N}\sum_i [y_i \log \hat{y}_i + (1-y_i)\log(1 - \hat{y}_i)] $$

多分类 (Softmax + CE):

$$ L = -\frac{1}{N}\sum_i \sum_c y_{i,c} \log p_{i,c} $$

nn.CrossEntropyLoss()           # logits + CE + Softmax 一体
nn.NLLLoss()                    # 接收 log-softmax
nn.BCEWithLogitsLoss()          # 二分类 + Sigmoid

注意:CrossEntropyLoss 内部已包含 Softmax,输入应为原始 logits。

Focal Loss

$$ L = -\alpha (1-p)^\gamma \log p $$

  • 解决类别不平衡
  • 难样本权重高
  • RetinaNet 提出 (2017)
class FocalLoss(nn.Module):
    def __init__(self, alpha=1, gamma=2):
        super().__init__()
        self.alpha = alpha
        self.gamma = gamma

    def forward(self, logits, targets):
        ce = F.cross_entropy(logits, targets, reduction='none')
        pt = torch.exp(-ce)
        return (self.alpha * (1 - pt) ** self.gamma * ce).mean()

Hinge Loss (SVM 风格)

$$ L = \max(0, 1 - y \cdot \hat{y}) $$

nn.MultiMarginLoss()
nn.HingeEmbeddingLoss()

5.4 多标签损失

BCE (Binary Cross-Entropy)

$$ L = -\frac{1}{N}\sum_{i,c} [y_{i,c} \log \hat{y}{i,c} + (1 - y{i,c})\log(1 - \hat{y}_{i,c})] $$

nn.BCELoss()                    # 接收 sigmoid 后概率
nn.BCEWithLogitsLoss()          # 推荐:logits

Multi-Label Soft Margin

nn.MultiLabelSoftMarginLoss()

5.5 序列生成损失

CTC Loss

语音识别 / OCR 等对齐未知任务:

$$ L = -\log P(y | x) $$

nn.CTCLoss(blank=0)

Label Smoothing

将 one-hot 软化为:

$$ y' = (1 - \epsilon) y + \frac{\epsilon}{K} $$

防止过自信:

nn.CrossEntropyLoss(label_smoothing=0.1)

5.6 对比/嵌入损失

Contrastive Loss

$$ L = (1-Y) \frac{1}{2} D^2 + Y \frac{1}{2} \max(0, m - D)^2 $$

  • $Y=0$:相似对
  • $Y=1$:不相似对
  • $D$:距离,$m$:margin
nn.CosineEmbeddingLoss(margin=0.5)

Triplet Loss

$$ L = \max(0, d(a, p) - d(a, n) + m) $$

人脸识别:anchor / positive / negative

nn.TripletMarginLoss(margin=1.0)

InfoNCE / NT-Xent (对比学习)

$$ L = -\log \frac{\exp(s(z_i, z_j)/\tau)}{\sum_{k=1}^{2N} \mathbb{1}_{k \neq i} \exp(s(z_i, z_k)/\tau)} $$

  • SimCLR / MoCo / CLIP 使用
  • $\tau$:温度

5.7 重建损失 (生成模型)

L1 / L2

  • 像素级重建

Perceptual Loss (VGG Loss)

  • 用 VGG 提取特征后算距离

LPIPS

  • 学习型感知相似度

5.8 扩散模型损失

DDPM 简化损失

$$ L = \mathbb{E}{t, x_0, \epsilon} | \epsilon - \epsilon\theta(\sqrt{\bar{\alpha}_t} x_0 + \sqrt{1-\bar{\alpha}_t} \epsilon, t) |^2 $$

详见 11-生成模型。

5.9 排序损失 (Ranking)

MarginRankingLoss

$$ L = \max(0, -y(x_1 - x_2) + m) $$

Listwise (LambdaLoss / ListNet)

详见 机器学习/12-推荐。

5.10 蒸馏损失

KL Divergence

$$ \text{KL}(p || q) = \sum p \log \frac{p}{q} $$

nn.KLDivLoss(reduction='batchmean')
F.kl_div(logits_student.log_softmax(-1), logits_teacher.softmax(-1))

5.11 强化学习损失

Policy Gradient (REINFORCE)

$$ L = -\mathbb{E}[R_t \log \pi(a_t | s_t)] $$

PPO Clip

$$ L = \min\left(\frac{\pi_\theta(a_t | s_t)}{\pi_{\theta_{old}}(a_t | s_t)} A_t, \text{clip}(\cdot, 1-\epsilon, 1+\epsilon) A_t\right) $$

详见 机器学习/14-强化学习。

5.12 损失函数选择

任务 损失
二分类 BCE / BCEWithLogits
多分类 CrossEntropy (with Softmax)
多标签 BCE / MultiLabelSoftMargin
回归 MSE / MAE / Huber
检测 Smooth L1 + Focal
分割 CE + Dice
嵌入 Triplet / InfoNCE
生成 L1 / L2 / Perceptual
序列 CTC / CE
蒸馏 KL Divergence

5.13 自定义损失

class DiceLoss(nn.Module):
    """Dice Loss for segmentation."""
    def __init__(self, smooth=1.0):
        super().__init__()
        self.smooth = smooth

    def forward(self, logits, targets):
        probs = torch.sigmoid(logits)
        intersection = (probs * targets).sum()
        union = probs.sum() + targets.sum()
        dice = (2.0 * intersection + self.smooth) / (union + self.smooth)
        return 1 - dice

5.14 数值稳定性

Softmax + CE

PyTorch CrossEntropyLoss 内部:

# 已数值稳定
log_softmax(x) - log_sum_exp(x)

避免 exp 爆炸

# 错
logits.exp().sum().log()
# 对
torch.logsumexp(logits, dim=-1)

混合精度损失缩放

scaler.scale(loss).backward()

5.15 参考

  • Goodfellow et al., 2016 Deep Learning Ch. 7
  • Lin et al., 2017 Focal Loss for Dense Object Detection
  • van den Oord et al., 2018 Representation Learning with Contrastive Predictive Coding
  • Hadsell et al., 2006 Dimensionality Reduction by Learning an Invariant Mapping
  • Cox & Pinto, 2011 Beyond simple features: A large-scale feature search approach to unconstrained face recognition (Faster R-CNN / Smooth L1)