正确继承方式是直接子类化tf.keras.metrics.Metric并重写__init__、update_state、result、reset_state四个方法;状态变量须用add_weight创建,update_state需加@tf.function且参数名为y_true/y_pred,result须返回tf.float32标量。

TensorFlow 2.x 中 tf.keras.metrics.Metric 的正确继承方式
直接子类化 tf.keras.metrics.Metric 是唯一可靠的方式;用普通函数或 @tf.function 包裹的函数无法被 Keras 训练循环识别为指标,也不会在 model.evaluate() 或训练日志中更新。
关键点在于必须重写四个方法:__init__、update_state、result、reset_state。漏掉 reset_state 会导致多轮 evaluate 结果累积出错;漏掉 update_state 的 @tf.function 装饰(推荐加)可能引发图模式下张量未追踪问题。
常见错误现象:ValueError: Metric does not support graph mode —— 很可能是 update_state 没加 @tf.function,或内部用了非 TensorFlow 原生操作(如 np.argmax)。
- 所有状态变量(如
self.total、self.count)必须用self.add_weight()创建,不能用 Python 数值或tf.Variable手动初始化 -
update_state的输入参数名必须是y_true和y_pred(Keras 会按名传参),顺序不能颠倒 - 确保
result()返回标量tf.Tensor,类型建议显式转成tf.float32
实现一个带阈值的自定义 F1 分数(binary F1)
F1 是典型需要累积 TP/TN/FP/FN 的指标,不能靠单批次结果简单平均。重点在于状态设计和逐批次更新逻辑是否与全局统计一致。
以下是最简可行实现(省略注释,仅保留核心):
class BinaryF1Score(tf.keras.metrics.Metric):
def __init__(self, threshold=0.5, name='binary_f1', **kwargs):
super().__init__(name=name, **kwargs)
self.threshold = threshold
self.true_positives = self.add_weight(name='tp', initializer='zeros')
self.false_positives = self.add_weight(name='fp', initializer='zeros')
self.false_negatives = self.add_weight(name='fn', initializer='zeros')
<pre class="brush:php;toolbar:false;">@tf.function
def update_state(self, y_true, y_pred, sample_weight=None):
y_pred = tf.cast(y_pred > self.threshold, tf.bool)
y_true = tf.cast(y_true, tf.bool)
tp = tf.math.count_nonzero(y_pred & y_true)
fp = tf.math.count_nonzero(y_pred & ~y_true)
fn = tf.math.count_nonzero(~y_pred & y_true)
self.true_positives.assign_add(tf.cast(tp, tf.float32))
self.false_positives.assign_add(tf.cast(fp, tf.float32))
self.false_negatives.assign_add(tf.cast(fn, tf.float32))
def result(self):
precision = self.true_positives / (self.true_positives + self.false_positives + 1e-6)
recall = self.true_positives / (self.true_positives + self.false_negatives + 1e-6)
return 2 * ((precision * recall) / (precision + recall + 1e-6))
def reset_state(self):
self.true_positives.assign(0)
self.false_positives.assign(0)
self.false_negatives.assign(0)
注意:分母加 1e-6 是防止除零,不是可选优化——不加会在全负样本批次触发 NaN;tf.math.count_nonzero 必须作用于 bool 张量,否则结果不可靠。
让 macOS 自动化像说话一样简单 —— 用代码控制你的 Mac,无需学习 AppleScript 系统要求 macOS 14+ (Sonoma) Python 3.9+ 需要开启:辅助功能 + 屏幕录制权限
在 model.compile() 中注册和使用时的兼容性陷阱
自定义指标对象可以直接传入 metrics 列表,但必须保证每次调用都返回新实例(不能复用同一对象),否则多个模型共用一个状态会互相污染。
- ✅ 正确:
model.compile(..., metrics=[BinaryF1Score(), 'accuracy']) - ❌ 错误:
f1 = BinaryF1Score(); model.compile(..., metrics=[f1, 'accuracy'])—— 多次fit()或多模型时状态混乱 - 如果需动态传参(如不同阈值),必须在
compile前创建实例,不能用 lambda 或闭包包装 - Keras 2.9+ 支持字符串形式注册(通过
tf.keras.metrics.get),但自定义类不支持该机制,只能传实例
验证是否生效:运行 model.evaluate() 后检查返回列表长度是否匹配你传入的指标数;若缺失,大概率是类没正确继承或构造失败被静默跳过。
调试自定义指标时最常忽略的两件事
一是忘记在 update_state 中处理 sample_weight 参数。虽然多数场景不用加权,但如果你的数据用了 class_weight 或 sample_weight,而指标里完全忽略它,结果就会系统性偏移。
二是混淆 y_pred 形状。二分类任务中,y_pred 通常是 (batch_size, 1) 或 (batch_size,),直接跟 y_true 做布尔运算前必须 reshape 或 squeeze。常见报错 Incompatible shapes 就源于此。
建议在 update_state 开头加断言:assert len(y_true.shape) == len(y_pred.shape),并统一用 tf.squeeze 对齐维度。复杂任务(如多标签)还要考虑 axis 选择,这些细节不显式处理,指标值就只是看起来“跑通了”。
Python免费学习笔记(深入):立即使用
在学习笔记中,你将探索 Python 的核心概念和高级技巧!










