在医学图像分割中,如何自定义 DiceLoss 并处理类别不平衡?
解读
国内医疗 AI 公司(联影、推想、深睿、商汤医疗等)面试时,90% 会追问“为什么不用 CrossEntropy,而要用 DiceLoss?”以及“如果前景体积极小,DiceLoss 仍失效怎么办?”
本题考察三点:
- 对 Dice 系数数学本质的理解(集合相似度,对像素数量不敏感);
- 用 PyTorch 实现时,如何兼顾数值稳定、反向传播正确、多类别扩展;
- 类别不平衡的“医学特色”——极端前景占比(<0.1%)及多器官任务中“器官大小差异巨大”的解决方案。
面试官常让你现场写代码,并追问“不加 smooth 会怎样”“为什么用 softmax 而不用 sigmoid”“多类别时权重怎么设”。
知识点
- Dice 系数:DSC = 2|X∩Y|/(|X|+|Y|) → Loss = 1-DSC
- 数值稳定:分子分母加 smooth,防止 0/0 及初期梯度爆炸
- 多类别:One-hot 后按类别计算再平均,或加权平均;背景是否参与计算要说明
- 不平衡策略:
- 类别权重(Weighted Dice)
- 困难区域采样(OHEM、Focal 改造)
- 混合 Loss(Dice+Focal、Dice+Tversky、Dice+Boundary)
- PyTorch 实现要点:
- 禁用 softmax 后再转 one-hot,避免二义性
- 用 torch.einsum 或 dim=(0,2,3) 降维,保持 batch 维度可加权
- 训练/验证阶段对 DSC 阈值 0.5 与 0.9 分别监控,防止过拟合伪影
答案
以下给出“可直接抄白板”的工业级实现,支持 2D/3D、多类别、类别权重、平滑项、忽略背景,并附带“极端小目标”补救策略。
import torch
import torch.nn as nn
class GeneralizedDiceLoss(nn.Module):
"""
支持任意维输入 (N, C, H, W, (D)),可指定类别权重与平滑项
用法:
criterion = GeneralizedDiceLoss(activation='softmax', smooth=1e-5,
weight=torch.tensor([0,1,1,2]), ignore_index=0)
loss = criterion(pred, target) # target: (N, H, W, (D)) 整数编码
"""
def __init__(self, activation='softmax', smooth=1e-5,
weight=None, ignore_index=None, squared=True):
super().__init__()
self.activation = activation # 'softmax' or 'sigmoid'
self.smooth = smooth
self.weight = weight # tensor of shape (C,)
self.ignore_index = ignore_index # 通常是背景 0
self.squared = squared # 用平方项可进一步抑制 FP
def forward(self, pred, target):
# 1. 维度统一
ndim = pred.ndim
assert ndim in [4, 5], "only 2D/3D images"
if ndim == 4:
N, C, H, W = pred.shape
else:
N, C, H, W, D = pred.shape
# 2. 激活
if self.activation == 'softmax':
pred = torch.softmax(pred, dim=1)
else:
pred = torch.sigmoid(pred)
# 3. 转 one-hot
if target.ndim == ndim - 1: # 整数标签
target = torch.nn.functional.one_hot(target.long(), num_classes=C)
if ndim == 4:
target = target.permute(0, 3, 1, 2).contiguous()
else:
target = target.permute(0, 4, 1, 2, 3).contiguous()
target = target.float()
# 4. 忽略指定类别
if self.ignore_index is not None:
mask = torch.ones(C, dtype=torch.bool, device=pred.device)
mask[self.ignore_index] = False
pred = pred[:, mask, ...]
target = target[:, mask, ...]
C = mask.sum().item()
# 5. 计算交集与和
reduce_dims = list(range(2, ndim)) # (H, W, (D))
intersection = torch.sum(pred * target, dim=reduce_dims) # (N, C)
if self.squared:
pred_sum = torch.sum(pred * pred, dim=reduce_dims)
target_sum = torch.sum(target * target, dim=reduce_dims)
else:
pred_sum = torch.sum(pred, dim=reduce_dims)
target_sum = torch.sum(target, dim=reduce_dims)
# 6. 类别权重
if self.weight is None:
weight = torch.ones(C, device=pred.device)
else:
weight = self.weight.to(pred.device)
if self.ignore_index is not None:
weight = weight[mask]
weight = weight / weight.sum() # 归一化
# 7. Dice 系数
dice = (2. * intersection + self.smooth) / (pred_sum + target_sum + self.smooth)
dice = dice * weight.unsqueeze(0) # (N, C)
dice = dice.sum(dim=1) # (N,)
# 8. 返回 loss
return 1. - dice.mean()
使用技巧(面试可主动说):
- 极端小目标:当某类别像素占比 <0.05%,把 weight 调高 5~10 倍,或改用 TverskyLoss(α=0.3, β=0.7)强调召回。
- 训练初期:把 smooth 调大到 1e-3,防止梯度消失;后期降到 1e-5,让指标更接近真实 DSC。
- 混合 Loss:loss = 0.5 * DiceLoss + 0.5 * FocalLoss(gamma=2),可同时解决“边界模糊”与“难样本”问题。
- 验证阶段:除 loss 外,额外计算 DSC@0.5 与 95% Hausdorff Distance,方便与影像科医生对齐。
拓展思考
- 如果 GPU 显存不足,无法一次性 whole-slide 推理,如何把 DiceLoss 改成“滑窗聚合”且保持梯度正确?
提示:把窗口预测累积到两张全图张量(sum_prob, sum_lab),最后一次性算 Dice,避免窗口边界重复惩罚。 - 多器官分割中,某些器官在 20% 病例里完全缺失,如何动态调整权重?
提示:在 getitem 里统计该病例是否存在该器官,生成动态权重 mask,并在 loss 里把缺失类别的梯度置 0。 - 如果公司要求 TensorRT 部署,TorchScript traced 的 DiceLoss 节点会被融合掉,如何保持指标一致?
提示:训练阶段用 DiceLoss,推理阶段用 argmax 后计算 DSC,无需重新实现;但需把 smooth 固定为 0,否则指标对不齐。