蓝色天空.知识 · 实践 · 创造
我的收藏
PyTorch 教程目录 39章
PyTorch / LEARN BY DOING

PyTorch 损失函数

核对分类/回归/分布/度量/序列对齐全族损失函数的输入形态约定、reduction 与权重忽略索引,并修正多分类 Dice 组合分割损失。

学完这一章,你能够

  • 核对分类/回归/分布/度量/序列对齐全族损失函数的输入形态约定、reduction 与权重忽略索引,并修正多分类 Dice 组合分割损失。

损失函数调用约定与输入形态边界

损失函数衡量模型预测与真实目标的差距,为反向传播提供梯度方向。PyTorch 的内置损失均继承自 nn.Module,调用形式统一为 loss = criterion(pred, target)。初学者最容易踩坑的是不同损失对输入张量形态(原始 logits、Sigmoid 概率还是 log_softmax 概率)及标签类型(整数类别索引还是浮点 0/1)的严格要求,下表集中对照(N 为批次大小,C 为类别数)。

分类任务损失:CrossEntropy、BCE 与 NLLLoss

CrossEntropyLoss 是多分类首选,内部融合了 LogSoftmax 与 NLLLoss(Loss = -sum(y_c * log(p_c))),输入必须是未经 Softmax 的原始 logits,标签为整型类别索引。切忌先做 Softmax 再送入 CrossEntropyLoss:本站实测正常 logits 的交叉熵为 0.164,误做一次 Softmax 后损失被扭曲放大至 0.6522。label_smoothing=0.1 可缓解高置信度过拟合(实测平滑后损失 0.3484)。

二分类与多标签分类方面,BCELoss 要求输入是经 Sigmoid 压缩到 (0, 1) 的概率且标签为同形浮点 0/1,传入越界 logits 易数值失稳;工程上应优先采用内置 Sigmoid 的 BCEWithLogitsLoss(实测二者等价均为 0.2407,且后者支持 pos_weight 提升稀有正样本权重,如 pos_weight=10 实测损失 1.593)。NLLLoss 则接收 log_softmax 后的对数概率,本站核对 NLLLoss(log_softmax(logits), y) 与 CrossEntropyLoss(logits, y) 误差为 0.0。

回归任务损失与离群点鲁棒性

连续值回归中,MSELoss 计算平方差均值,在无异常值时梯度光滑但对大误差极为敏感;L1Loss(MAE)取绝对值误差,对离群点鲁棒但零点梯度不连续;SmoothL1Loss 在 |x| < 1 区间用 0.5x^2、在 |x| >= 1 区间转为 |x| - 0.5,兼顾小误差平稳与抗离群能力。本站对误差向量 [0, 1, 5, 10] 实测逐样本损失:MSE 为 [0.0, 1.0, 25.0, 100.0],L1 为 [0.0, 1.0, 5.0, 10.0],SmoothL1 为 [0.0, 0.5, 4.5, 9.5]。

进阶损失:Huber、KL 散度、排序、三元组与 CTC

HuberLoss 是 SmoothL1 的泛化版,可自定义阈值 delta(delta=1.5 对 [0, 1, 5, 10] 实测 [0.0, 0.5, 6.38, 13.88])。KLDivLoss(reduction='batchmean') 要求首个参数为学生 log_softmax、第二个参数为教师概率分布,同分布时 KL 为 0,知识蒸馏温度 T=4 实测损失 0.6853。MarginRankingLoss 按相对顺序与间隔 margin=0.5 惩罚误排(实测 0.1667);TripletMarginLoss 约束 anchor 距正样本比负样本至少近 margin(合规三元组损失 0.0,反转正负后 > 1.0);CTCLoss(blank=0) 处理语音/OCR 变长未对齐序列(T=30, L=6 实测 9.2079)。

reduction 汇总、类别权重与忽略标签

reduction 支持 'mean'(默认平均)、'sum'(求和)与 'none'(保留逐样本损失)。对 [1,2,3,4] 与 [1.5,2.5,2,5] 实测 MSE:mean=0.625、sum=2.5、none=[0.25, 0.25, 1.0, 1.0];利用 'none' 乘以样本权重 [1,1,2,2] 求均值可得 1.125。类别极度不平衡时可传 CrossEntropyLoss(weight=class_weights);语义分割边界无效像素可设 ignore_index=255 跳过计算且不引入 NaN。

自定义损失与多分类 Dice 组合修正

自定义损失需全程使用可微 PyTorch 张量算子(可写函数或继承 nn.Module)。例如 Focal Loss 通过 (1-p_t)^gamma 压低易分样本权重(本站实测同输入 Focal=0.00247 明显低于标准 CE 0.164)。重要排错修正:直接把接收整型掩码 (N,H,W) 的多分类 CrossEntropyLoss 与期望二值张量的 Sigmoid DiceLoss 拼接会导致形状不匹配崩溃;正确做法是在多分类 DiceLoss 中对 logits 做 softmax(dim=1) 并将整型标签转为 F.one_hot(..., num_classes).permute(0,3,1,2) 后逐类求交并比。本站实测修正后的 CombinedSegLoss(0.4 CE + 0.6 MultiClassDice)前向值 1.0908 且反向梯度有限非零。

常用损失函数的预测值与标签形态约定

损失函数预测值(input)形态标签(target)形态
CrossEntropyLoss(N, C) 原始 logits(勿先 Softmax)(N,) 整型类别索引 int64
BCELoss(N,) 经 Sigmoid 后的 (0,1) 概率(N,) 0/1 浮点数
BCEWithLogitsLoss(N,) 原始 logits(内部融合 Sigmoid)(N,) 0/1 浮点数
MSELoss(N, ...) 任意连续实数(N, ...) 同形连续实数
NLLLoss(N, C) 经 log_softmax 的对数概率(N,) 整型类别索引 int64

按任务类型选择损失函数速查

任务类型推荐损失函数备注
多分类CrossEntropyLoss最通用,优先选择
多分类(类别不平衡)CrossEntropyLoss(weight=...)给少数类赋予更高权重
多分类(标签噪声大)CrossEntropyLoss(label_smoothing=0.1)平滑目标分布缓解过拟合
二分类BCEWithLogitsLoss内置 Sigmoid,比 BCELoss 更稳
多标签分类BCEWithLogitsLoss每个标签通道独立二分类
目标检测(分类头)CrossEntropyLoss / Focal Loss前景背景悬殊时用 Focal Loss
目标检测(回归头)SmoothL1Loss / GIoULoss兼顾小框平滑与大框鲁棒
普通回归MSELoss无显著离群点时首选
含离群点的回归HuberLoss / SmoothL1Loss对大误差线性惩罚
图像分割CrossEntropyLoss + MultiClassDiceLoss多分类 Dice 需配合 softmax + one_hot
语音识别CTCLoss处理输入输出长度不对齐
度量学习 / 人脸识别TripletMarginLoss拉近同类并推远异类嵌入
知识蒸馏KLDivLoss(reduction='batchmean')配合温度 T 与 T^2 缩放

运行全族损失函数、双重 Softmax 陷阱与修正多分类 Dice 分割损失实验

含完整源码 · 194 行
展开查看收起
python
"""Independent PyTorch 2.10 CPU observations for classification, regression, metric, CTC and custom losses."""
import json
import platform

import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim


def focal_loss(logits: torch.Tensor, targets: torch.Tensor, gamma: float = 2.0, alpha: float = 0.25) -> torch.Tensor:
    ce = F.cross_entropy(logits, targets, reduction="none")
    pt = torch.exp(-ce)
    return (alpha * (1.0 - pt) ** gamma * ce).mean()


class MultiClassDiceLoss(nn.Module):
    """Multi-class Dice loss taking raw logits (N,C,H,W) and integer masks (N,H,W)."""

    def __init__(self, smooth: float = 1.0):
        super().__init__()
        self.smooth = smooth

    def forward(self, logits: torch.Tensor, targets: torch.Tensor) -> torch.Tensor:
        probs = torch.softmax(logits, dim=1)
        num_classes = logits.size(1)
        one_hot = F.one_hot(targets, num_classes=num_classes).permute(0, 3, 1, 2).float()
        dims = (0, 2, 3)
        inter = (probs * one_hot).sum(dim=dims)
        denom = probs.sum(dim=dims) + one_hot.sum(dim=dims)
        dice = (2.0 * inter + self.smooth) / (denom + self.smooth)
        return 1.0 - dice.mean()


class CombinedSegLoss(nn.Module):
    def __init__(self, ce_weight: float = 0.4, dice_weight: float = 0.6):
        super().__init__()
        self.ce_weight = ce_weight
        self.dice_weight = dice_weight
        self.ce = nn.CrossEntropyLoss()
        self.dice = MultiClassDiceLoss()

    def forward(self, logits: torch.Tensor, targets: torch.Tensor) -> torch.Tensor:
        return self.ce_weight * self.ce(logits, targets) + self.dice_weight * self.dice(logits, targets)


def run_cases():
    torch.manual_seed(2026)
    cases = []

    # 1. Classification losses: CrossEntropyLoss, NLLLoss equivalence, label_smoothing, soft targets, double-softmax trap
    logits = torch.tensor([[2.0, 0.5, 0.3], [0.1, 3.0, 0.2], [0.2, 0.1, 4.0]])
    targets = torch.tensor([0, 1, 2])
    ce = nn.CrossEntropyLoss()(logits, targets)
    nll = nn.NLLLoss()(torch.log_softmax(logits, dim=1), targets)
    ce_vs_nll_diff = float((ce - nll).abs().item())
    # Double softmax inflates loss artificially
    ce_double_sm = nn.CrossEntropyLoss()(torch.softmax(logits, dim=1), targets)
    ce_smooth = nn.CrossEntropyLoss(label_smoothing=0.1)(logits, targets)
    soft_t = torch.tensor([[0.9, 0.05, 0.05], [0.05, 0.9, 0.05]])
    ce_soft = nn.CrossEntropyLoss()(logits[:2], soft_t)
    c1_ok = ce_vs_nll_diff < 1e-6 and float(ce_double_sm.item()) > float(ce.item()) * 2.0 and float(ce_smooth.item()) > float(ce.item()) and float(ce_soft.item()) > 0.0
    cases.append(dict(
        name="classification_ce_and_nll",
        inputs=dict(batch=3, classes=3, label_smoothing=0.1),
        prerequisites="PyTorch 2.10 CPU",
        action="验证 CrossEntropyLoss 与 LogSoftmax+NLLLoss 精确等价、重复 Softmax 会扭曲损失,以及标签平滑和软标签输入。",
        expected=dict(ce_eq_nll=True, double_softmax_inflates=True, smooth_gt_hard=True, soft_targets_ok=True),
        actual=dict(ce_eq_nll=ce_vs_nll_diff < 1e-6, double_softmax_inflates=float(ce_double_sm.item()) > float(ce.item()) * 2.0, smooth_gt_hard=float(ce_smooth.item()) > float(ce.item()), soft_targets_ok=float(ce_soft.item()) > 0.0),
        measurements=dict(ce=round(float(ce.item()), 4), ce_double_softmax=round(float(ce_double_sm.item()), 4), ce_smooth=round(float(ce_smooth.item()), 4)),
        passed=c1_ok,
    ))

    # 2. BCELoss vs BCEWithLogitsLoss, pos_weight, and int-target TypeError/RuntimeError check
    raw_b = torch.tensor([2.0, -1.0, 0.5, -3.0])
    y_b = torch.tensor([1.0, 0.0, 1.0, 0.0])
    bce_prob = nn.BCELoss()(torch.sigmoid(raw_b), y_b)
    bce_logits = nn.BCEWithLogitsLoss()(raw_b, y_b)
    bce_diff = float((bce_prob - bce_logits).abs().item())
    bce_pw = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([10.0]))(raw_b, y_b)
    int_target_failed = False
    try:
        nn.BCEWithLogitsLoss()(raw_b, torch.tensor([1, 0, 1, 0]))
    except RuntimeError:
        int_target_failed = True
    c2_ok = bce_diff < 1e-6 and float(bce_pw.item()) > float(bce_logits.item()) and int_target_failed
    cases.append(dict(
        name="binary_bce_and_logits",
        inputs=dict(raw=[2.0, -1.0, 0.5, -3.0], pos_weight=10.0),
        prerequisites="对比 BCELoss(sigmoid(x)) 与 BCEWithLogitsLoss(x)",
        action="验证两者数值等价、pos_weight 提升正例惩罚权重,以及整型标签传入 BCEWithLogitsLoss 抛出 RuntimeError。",
        expected=dict(bce_matches_logits=True, pos_weight_increases_loss=True, int_target_rejected=True),
        actual=dict(bce_matches_logits=bce_diff < 1e-6, pos_weight_increases_loss=float(bce_pw.item()) > float(bce_logits.item()), int_target_rejected=int_target_failed),
        measurements=dict(bce=round(float(bce_logits.item()), 4), bce_pos_weight10=round(float(bce_pw.item()), 4)),
        passed=c2_ok,
    ))

    # 3. Regression losses: MSE, L1, SmoothL1, HuberLoss outlier sensitivity
    errs = torch.tensor([0.0, 1.0, 5.0, 10.0])
    zeros = torch.zeros(4)
    mse_v = [round(v, 2) for v in nn.MSELoss(reduction="none")(errs, zeros).tolist()]
    l1_v = [round(v, 2) for v in nn.L1Loss(reduction="none")(errs, zeros).tolist()]
    sl1_v = [round(v, 2) for v in nn.SmoothL1Loss(reduction="none")(errs, zeros).tolist()]
    huber_v = [round(v, 2) for v in nn.HuberLoss(delta=1.5, reduction="none")(errs, zeros).tolist()]
    c3_ok = mse_v == [0.0, 1.0, 25.0, 100.0] and l1_v == [0.0, 1.0, 5.0, 10.0] and sl1_v == [0.0, 0.5, 4.5, 9.5] and huber_v[3] < mse_v[3]
    cases.append(dict(
        name="regression_mse_l1_huber",
        inputs=dict(errors=[0.0, 1.0, 5.0, 10.0], huber_delta=1.5),
        prerequisites="reduction='none' 观察不同误差尺度下的逐样本损失",
        action="核对 MSE 平方放大离群点(100.0)、L1 线性增长(10.0)、SmoothL1(9.5)及 HuberLoss(delta=1.5)。",
        expected=dict(mse=[0.0, 1.0, 25.0, 100.0], l1=[0.0, 1.0, 5.0, 10.0], smooth_l1=[0.0, 0.5, 4.5, 9.5], huber_lt_mse=True),
        actual=dict(mse=mse_v, l1=l1_v, smooth_l1=sl1_v, huber_lt_mse=huber_v[3] < mse_v[3]),
        measurements=dict(huber_delta15=huber_v),
        passed=c3_ok,
    ))

    # 4. Advanced losses: KLDivLoss (distillation), MarginRankingLoss, TripletMarginLoss, CTCLoss
    t_logits = torch.randn(8, 5)
    s_logits = torch.randn(8, 5)
    temp = 4.0
    kl_distill = nn.KLDivLoss(reduction="batchmean")(torch.log_softmax(s_logits / temp, dim=1), torch.softmax(t_logits / temp, dim=1)) * (temp ** 2)
    kl_same = nn.KLDivLoss(reduction="batchmean")(torch.log_softmax(t_logits, dim=1), torch.softmax(t_logits, dim=1))
    mrl = nn.MarginRankingLoss(margin=0.5)(torch.tensor([0.8, 0.3, 0.6]), torch.tensor([0.2, 0.7, 0.5]), torch.tensor([1.0, -1.0, 1.0]))
    a_emb = torch.zeros(4, 16)
    p_emb = torch.full((4, 16), 0.1)
    n_emb = torch.full((4, 16), 2.0)
    triplet_good = nn.TripletMarginLoss(margin=1.0)(a_emb, p_emb, n_emb)
    triplet_bad = nn.TripletMarginLoss(margin=1.0)(a_emb, n_emb, p_emb)
    ctc_lp = torch.log_softmax(torch.randn(30, 2, 10), dim=2)
    ctc_t = torch.randint(1, 10, (12,))
    ctc_loss = nn.CTCLoss(blank=0)(ctc_lp, ctc_t, torch.tensor([30, 30]), torch.tensor([6, 6]))
    c4_ok = float(kl_same.item()) < 1e-6 and float(kl_distill.item()) > 0.0 and abs(float(mrl.item()) - (0.5 / 3.0)) < 1e-4 and float(triplet_good.item()) == 0.0 and float(triplet_bad.item()) > 1.0 and float(ctc_loss.item()) > 0.0
    cases.append(dict(
        name="advanced_kl_ranking_triplet_ctc",
        inputs=dict(temp=4.0, margin_rank=0.5, triplet_margin=1.0, ctc_T=30),
        prerequisites="KLDivLoss(batchmean)、MarginRankingLoss、TripletMarginLoss 与 CTCLoss",
        action="验证同分布 KL 散度为 0、蒸馏 KL>0、排序损失、正负三元组距离对比及 CTC 对齐损失。",
        expected=dict(kl_self_zero=True, kl_distill_pos=True, triplet_good_zero=True, triplet_bad_gt_1=True, ctc_pos=True),
        actual=dict(kl_self_zero=float(kl_same.item()) < 1e-6, kl_distill_pos=float(kl_distill.item()) > 0.0, triplet_good_zero=float(triplet_good.item()) == 0.0, triplet_bad_gt_1=float(triplet_bad.item()) > 1.0, ctc_pos=float(ctc_loss.item()) > 0.0),
        measurements=dict(kl_distill=round(float(kl_distill.item()), 4), margin_ranking=round(float(mrl.item()), 4), ctc_loss=round(float(ctc_loss.item()), 4)),
        passed=c4_ok,
    ))

    # 5. reduction='mean'/'sum'/'none', class weights, and ignore_index=255
    pr = torch.tensor([1.0, 2.0, 3.0, 4.0])
    tr = torch.tensor([1.5, 2.5, 2.0, 5.0])
    r_mean = round(float(nn.MSELoss(reduction="mean")(pr, tr).item()), 4)
    r_sum = round(float(nn.MSELoss(reduction="sum")(pr, tr).item()), 4)
    r_none = nn.MSELoss(reduction="none")(pr, tr).tolist()
    weighted = round(float((nn.MSELoss(reduction="none")(pr, tr) * torch.tensor([1.0, 1.0, 2.0, 2.0])).mean().item()), 4)
    seg_pred = torch.randn(2, 4, 8, 8)
    seg_tgt = torch.randint(0, 4, (2, 8, 8))
    seg_tgt[:, 0, :] = 255
    ign_loss = nn.CrossEntropyLoss(ignore_index=255)(seg_pred, seg_tgt)
    cls_w = torch.tensor([0.1, 1.0, 2.0])
    w_ce = nn.CrossEntropyLoss(weight=cls_w)(logits, targets)
    c5_ok = bool(r_mean == 0.625 and r_sum == 2.5 and r_none == [0.25, 0.25, 1.0, 1.0] and weighted == 1.125 and torch.isfinite(ign_loss).item() and torch.isfinite(w_ce).item())
    cases.append(dict(
        name="reduction_weights_and_ignore_index",
        inputs=dict(ignore_index=255, sample_weights=[1.0, 1.0, 2.0, 2.0]),
        prerequisites="核对 mean/sum/none 汇总方式、逆频类别权重与分割边界忽略索引",
        action="验证 mean=0.625、sum=2.5、加权=1.125,以及含 255 标签像素图正常计算有限损失。",
        expected=dict(mean=0.625, sum=2.5, weighted=1.125, ignore255_finite=True),
        actual=dict(mean=r_mean, sum=r_sum, weighted=weighted, ignore255_finite=bool(torch.isfinite(ign_loss).item())),
        passed=c5_ok,
    ))

    # 6. Custom Focal Loss & fixed CombinedSegLoss (CE + MultiClassDiceLoss) with backward pass
    seg_logits = torch.randn(2, 4, 8, 8, requires_grad=True)
    seg_mask = torch.randint(0, 4, (2, 8, 8))
    comb = CombinedSegLoss(ce_weight=0.4, dice_weight=0.6)
    comb_val = comb(seg_logits, seg_mask)
    comb_val.backward()
    grad_finite = bool(torch.isfinite(seg_logits.grad).all().item()) and float(seg_logits.grad.norm().item()) > 0.0
    # Focal loss down-weights easy high-confidence samples relative to cross-entropy
    fl_val = focal_loss(logits, targets, gamma=2.0, alpha=0.25)
    c6_ok = grad_finite and float(comb_val.item()) > 0.0 and float(fl_val.item()) < float(ce.item())
    cases.append(dict(
        name="custom_focal_and_combined_dice",
        inputs=dict(seg_shape=[2, 4, 8, 8], ce_weight=0.4, dice_weight=0.6),
        prerequisites="修正多分类 Dice 需将整型掩码 (N,H,W) 转为 one-hot 并使用 softmax 概率",
        action="验证 Focal Loss 压低易分样本损失,以及修正后的 CombinedSegLoss 正常反传非零有限梯度。",
        expected=dict(focal_lt_ce=True, combined_grad_finite=True),
        actual=dict(focal_lt_ce=float(fl_val.item()) < float(ce.item()), combined_grad_finite=grad_finite),
        measurements=dict(focal_loss=round(float(fl_val.item()), 5), combined_loss=round(float(comb_val.item()), 4)),
        passed=c6_ok,
    ))

    print(json.dumps(dict(version=platform.python_version(), torch=torch.__version__, system=platform.system(), cases=cases), ensure_ascii=False))


if __name__ == "__main__":
    run_cases()
核对 CE/NLL 等价与双重 Softmax 扭曲、BCEWithLogits+pos_weight、MSE/L1/SmoothL1/Huber、KL/Ranking/Triplet/CTC、reduction 与 ignore_index=255、Focal Loss 及修正版 CombinedSegLoss。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 选择对应构建并运行脚本。

下载本章实验包 (mbskycom202612a409.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:PyTorch

课程关联工程包(登记关联39章) · 含当前章节或实例 · mbskycom202612a409.zip

下载课程关联工程包:PyTorch

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a427.zip

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

CrossEntropyLoss 接收 (N,C,H,W) logits 与整型 (N,H,W) 掩码,二值 DiceLoss 期望同形浮点概率且 Sigmoid 不具多类互斥性;应先对 logits 做 softmax(dim=1) 并将掩码通过 F.one_hot 转为 (N,C,H,W) 后计算多分类 Dice。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习