如何编写一个基于领域知识的自定义损失函数(如医学图像中的 Dice Loss)?

解读

国内医疗 AI 公司面试时,90% 会追问“为什么不用交叉熵”“梯度爆炸怎么缓解”“多类分割如何泛化”。回答时不能只给出公式,而要展示:①对医学图像数据特点(类别极度不平衡、前景像素占比<1%)的洞察;②对 TF 计算图执行机制的掌握(eager vs graph,@tf.function,XLA);③对分布式训练与混合精度下数值稳定的工程经验。面试官希望听到“我能在 30 min 内写出一个可在 TPUEstimator 里直接替换 compile 的 loss,并在验证集上把 Dice 提升 3 个点”。

知识点

  1. 数据流图与自动求导:任何继承 tf.keras.losses.Loss 的子类,init 里存超参,call 里只写前向;TF 会反向自动构建梯度子图。
  2. 张量类型与设备:float16 在 V100 上能提速 1.5×,但累加必须转 float32,否则 Dice 系数出现 1+1e-8≈1 的截断误差。
  3. 图模式优化:用 @tf.function(experimental_relax_shapes=True) 让动态 batch size 复用计算图,避免每次重编译。
  4. 类别不平衡策略:对前景背景分别加权重 w_foreground = (1 – γ) / γ,其中 γ 为前景像素比例,可在 fit 里用 callback 每 epoch 更新。
  5. 数值稳定:log(0) 用 tf.math.log(tf.maximum(y_pred, 1e-7));平方和用 tf.nn.moments 的 fused 实现,减少一次全局同步。
  6. TPU 兼容性:禁止用 Python 原生 bool 索引,必须转 tf.where;减少 tf.py_function,否则掉回 CPU。
  7. 多类分割:把 one-hot 当 3D 张量 (B,H,W,C),在通道维做 reduce,避免拆循环。
  8. 评估对齐:自定义 loss 返回的是 1 – Dice,而 metrics 返回 Dice,保证 TensorBoard 曲线方向一致。

答案

import tensorflow as tf

class DiceLoss(tf.keras.losses.Loss):
    def __init__(self,
                 class_weights=None,
                 smooth=1e-5,
                 square_denominator=False,
                 from_logits=True,
                 reduction=tf.keras.losses.Reduction.AUTO,
                 name='dice_loss'):
        super().__init__(reduction=reduction, name=name)
        self.class_weights = class_weights or tf.constant(1.0, dtype=tf.float32)
        self.smooth = tf.constant(smooth, dtype=tf.float32)
        self.square = square_denominator
        self.from_logits = from_logits

    def call(self, y_true, y_pred):
        # 1. 统一数据类型与设备
        y_true = tf.cast(y_true, tf.float32)
        if self.from_logits:
            y_pred = tf.nn.sigmoid(y_pred)
        else:
            y_pred = tf.cast(y_pred, tf.float32)

        # 2. flatten 保留 batch 维
        B = tf.shape(y_true)[0]
        y_true = tf.reshape(y_true, [B, -1])
        y_pred = tf.reshape(y_pred, [B, -1])

        # 3. 计算交集与和
        intersection = tf.reduce_sum(y_true * y_pred, axis=1)
        if self.square:
            y_true_sum = tf.reduce_sum(y_true * y_true, axis=1)
            y_pred_sum = tf.reduce_sum(y_pred * y_pred, axis=1)
        else:
            y_true_sum = tf.reduce_sum(y_true, axis=1)
            y_pred_sum = tf.reduce_sum(y_pred, axis=1)

        # 4. Dice 系数
        dice = (2.0 * intersection + self.smooth) / (y_true_sum + y_pred_sum + self.smooth)

        # 5. 加权平均
        weighted_dice = dice * self.class_weights
        loss = 1.0 - tf.reduce_mean(weighted_dice)
        return loss

使用示例(TPU 兼容):

strategy = tf.distribute.TPUStrategy(resolver)
with strategy.scope():
    model = tf.keras.Model(inputs, outputs)
    model.compile(optimizer=tf.keras.optimizers.Adam(1e-3 * strategy.num_replicas_in_sync),
                  loss=DiceLoss(from_logits=True),
                  metrics=[tf.keras.metrics.MeanIoU(num_classes=2)])
model.fit(train_dataset, validation_data=val_dataset, epochs=100)

拓展思考

  1. 多类分割:把 sigmoid 换成 softmax,将 one-hot 后的 y_true 与 y_pred 在通道维做相同运算,得到每类 Dice 后按样本频率加权,可解决“小器官”漏分问题。
  2. 边界加权:在 call 里引入 distance_map,对边界像素乘以 2,让网络更关注轮廓,常用于血管分割。
  3. 混合损失:L = α * DiceLoss + β * FocalLoss,通过 callback 动态调整 α、β,可在训练初期用 Focal 快速收敛,后期用 Dice 微调形状。
  4. 梯度裁剪:在 compile 里加 optimizer=tf.keras.optimizers.Adam(clipnorm=1.0),防止极端前景背景比下梯度爆炸。
  5. 生产部署:SavedModel 导出时,loss 仅用于训练,推理阶段去掉;TF Serving 的 signature 只需输出 softmax,减少 30% 延迟。