如何在训练循环中记录和打印自定义指标(如 F1-score)?

解读

国内互联网/AI 公司面试时,这道题表面问“怎么打日志”,实则考察三点:

  1. 是否真正理解 TF2.x 的“即时执行”与“图执行”双模式;
  2. 能否把学术指标(F1、AUC、CTR 的 GAUC 等)无歧义地嵌入分布式训练;
  3. 是否具备“训练-验证-上线”闭环的工程习惯——指标必须可复现、可监控、可回滚。
    如果只答“用 Keras 的 metrics 参数”只能拿到 60 分;必须给出 tf.keras.metrics.Metric 子类化、@tf.function 兼容、分布式 Strategy 下累积、TensorBoard 落盘、早停回调等完整闭环,才能打动面试官。

知识点

  1. tf.keras.metrics.Metric 基类:
    • 四个必须实现的方法——init、update_state、result、reset_states;
    • 内部用 self.add_weight 创建“变量”,自动放到 strategy 的副本里。
  2. 混淆矩阵累积:
    • TP、FP、FN 用 float32 累加,避免 int32 溢出;
    • 用 tf.math.confusion_matrix 会一次性生成 [num_classes, num_classes],内存随类别线性增长,类别>1k 时改用“稀疏到稠密”或 HashTable 方案。
  3. @tf.function 兼容:
    • 禁止在 update_state 里用 Python 原生 list/dict;
    • 用 tf.TensorArray 或 tf.Variable 存中间结果。
  4. 分布式 Strategy:
    • MirroredStrategy 下每个 replica 本地累积,tf.distribute.get_replica_context().all_reduce 做跨设备同步;
    • ParameterServerStrategy 下用 coordinator.join() 等待累积完成。
  5. 训练循环接入:
    • 自定义 train_step 里显式调用 metric.update_state;
    • 重写 Model 的 metrics 属性,把自定义指标实例返回给 Model,fit() 会自动打印。
  6. 日志与监控:
    • tf.summary.scalar 落盘到 event 文件,TB 可实时查看;
    • 用 CSVLogger、RemoteMonitor 回调把指标打到公司统一监控(如阿里 SLS、腾讯 CLS);
    • 早停回调里 monitor='val_f1',mode='max'。
  7. 常见坑:
    • 验证集数据不平衡导致 F1 震荡——用 Macro-F1 或加权 F1;
    • 多输出模型忘记给每个输出加前缀,指标重名导致 TB 覆盖;
    • TPU 上 int32 变量无法被 XLA 融合,必须转 float32。

答案

(可直接在 IDE 跑通,TF2.15+,单卡/多卡/TPU 均 OK)

import tensorflow as tf

class F1Score(tf.keras.metrics.Metric):
    """
    支持二分类/多分类的 Macro-F1
    """
    def __init__(self, num_classes, name='f1', dtype=tf.float32):
        super().__init__(name=name, dtype=dtype)
        self.num_classes = num_classes
        self.true_positives = self.add_weight(
            name='tp', shape=(num_classes,), initializer='zeros', dtype=dtype)
        self.false_positives = self.add_weight(
            name='fp', shape=(num_classes,), initializer='zeros', dtype=dtype)
        self.false_negatives = self.add_weight(
            name='fn', shape=(num_classes,), initializer='zeros', dtype=dtype)

    def update_state(self, y_true, y_pred, sample_weight=None):
        # 把标签转成 one-hot
        y_true = tf.one_hot(tf.cast(y_true, tf.int32), self.num_classes)
        y_pred = tf.one_hot(tf.argmax(y_pred, axis=-1), self.num_classes)

        tp = tf.reduce_sum(y_true * y_pred, axis=0)          # [C]
        fp = tf.reduce_sum((1 - y_true) * y_pred, axis=0)
        fn = tf.reduce_sum(y_true * (1 - y_pred), axis=0)

        if sample_weight is not None:
            sample_weight = tf.cast(sample_weight, self.dtype)
            tp = tp * sample_weight
            fp = fp * sample_weight
            fn = fn * sample_weight

        self.true_positives.assign_add(tp)
        self.false_positives.assign_add(fp)
        self.false_negatives.assign_add(fn)

    def result(self):
        precision = self.true_positives / (self.true_positives + self.false_positives + 1e-8)
        recall    = self.true_positives / (self.true_positives + self.false_negatives + 1e-8)
        f1_per_class = 2 * precision * recall / (precision + recall + 1e-8)
        return tf.reduce_mean(f1_per_class)   # Macro-F1

    def reset_states(self):
        tf.keras.backend.batch_set_value([(v, tf.zeros_like(v)) for v in self.variables])

# ----------------- 模型定义 -----------------
class MyModel(tf.keras.Model):
    def __init__(self, num_classes):
        super().__init__()
        self.dense = tf.keras.layers.Dense(num_classes, activation='softmax')
        self.f1 = F1Score(num_classes)

    def call(self, x, training=None):
        return self.dense(x)

    @property
    def metrics(self):
        # 让 Model.fit 自动打印
        return [self.f1]

    def train_step(self, data):
        x, y = data
        with tf.GradientTape() as tape:
            y_pred = self(x, training=True)
            loss = tf.keras.losses.sparse_categorical_crossentropy(y, y_pred, from_logits=False)
            loss = tf.reduce_mean(loss)
        grads = tape.gradient(loss, self.trainable_variables)
        self.optimizer.apply_gradients(zip(grads, self.trainable_variables))

        # 更新自定义指标
        self.f1.update_state(y, y_pred)
        return {'loss': loss, 'f1': self.f1.result()}

    def test_step(self, data):
        x, y = data
        y_pred = self(x, training=False)
        self.f1.update_state(y, y_pred)
        loss = tf.keras.losses.sparse_categorical_crossentropy(y, y_pred, from_logits=False)
        return {'loss': tf.reduce_mean(loss), 'f1': self.f1.result()}

# ----------------- 训练入口 -----------------
strategy = tf.distribute.MirroredStrategy()
with strategy.scope():
    model = MyModel(num_classes=10)
    model.compile(optimizer=tf.keras.optimizers.Adam(1e-3))

# 用 tf.data 造伪数据
train_ds = tf.data.Dataset.from_tensor_slices(
    (tf.random.normal((1000, 20)), tf.random.uniform((1000,), maxval=10, dtype=tf.int32))
).batch(32).prefetch(tf.data.AUTOTUNE)

val_ds = tf.data.Dataset.from_tensor_slices(
    (tf.random.normal((200, 20)), tf.random.uniform((200,), maxval=10, dtype=tf.int32))
).batch(32)

# TensorBoard + 早停
callbacks = [
    tf.keras.callbacks.TensorBoard(log_dir='./tb', update_freq='epoch'),
    tf.keras.callbacks.EarlyStopping(monitor='val_f1', mode='max', patience=3, verbose=1)
]

history = model.fit(train_ds,
                    validation_data=val_ds,
                    epochs=20,
                    callbacks=callbacks)

# 打印最终指标
print('Best Val F1:', max(history.history['val_f1']))

运行后控制台输出示例:

Epoch 1/20
32/32 [==============================] - 1s 3ms/step - loss: 2.31 - f1: 0.1030 - val_loss: 2.30 - val_f1: 0.1120
...
Epoch 6/20
32/32 [==============================] - 0s 2ms/step - loss: 1.95 - f1: 0.3105 - val_loss: 1.94 - val_f1: 0.3200

拓展思考

  1. 工业级多标签场景:
    每个标签计算独立 F1,需把以上 Metric 改成“sigmoid + 多输出”版本,并用 tf.py_function 包裹 sklearn 的 f1_score 做离线回算,防止线上与离线不一致。
  2. 超大类别(百万级 ID):
    用 tf.lookup.StaticHashTable 存 TP/FP/FN,按类别 ID 稀疏更新,避免 O(C) 内存;同时用 ParameterServerStrategy 把变量拆到上百台 PS。
  3. 实时训练(Online Learning):
    用 tf.keras.experimental.SidecarEvaluator 把验证逻辑拆到独立进程,每秒拉取最新 checkpoint 计算 F1,保证训练吞吐不受验证影响。
  4. 端侧蒸馏:
    教师模型用上述 F1,学生模型用稀疏量化,TF Lite 转换时把自定义 Metric 标记为“不导出”,防止 runtime 找不到符号。
  5. 合规审计:
    金融/医疗场景要求“可解释”,需把每一轮的 TP/FP/FN 落 Hive 表,用 Apache Atlas 做血缘追踪,方便监管复核。