KerasTuner RandomSearch自定义F1、AUC等目标指标报错问题
KerasTuner调优F1、AUC指标的解决方案
问题根源
Keras默认不会自动在训练日志中记录val_f1、val_auc这类指标——只有accuracy这类内置字符串式指标能直接被识别。要让KerasTuner读取到这些指标,必须在模型编译阶段显式添加对应的指标计算逻辑,否则训练日志里没有对应字段,自然会触发KeyError。
解决步骤
1. 显式添加指标到模型编译
在构建模型的build_model函数中,必须把AUC、F1等指标加入model.compile()的metrics参数,这样训练时才会计算并记录val_xxx格式的验证指标。
方法一:使用Keras内置指标类(推荐,TensorFlow 2.7+支持)
直接调用Keras提供的预定义指标类,同时指定name参数方便后续引用:
import tensorflow as tf import kerastuner as kt def build_model(hp): model = tf.keras.Sequential() model.add(tf.keras.layers.Dense(hp.Int('units', 32, 128, step=16), activation='relu')) model.add(tf.keras.layers.Dense(1, activation='sigmoid')) # 显式添加AUC和F1指标,指定name model.compile( optimizer=tf.keras.optimizers.Adam(hp.Float('lr', 1e-4, 1e-2, sampling='log')), loss='binary_crossentropy', metrics=[ 'accuracy', tf.keras.metrics.AUC(name='auc'), tf.keras.metrics.F1Score(name='f1', average='binary', threshold=0.5) # 二分类用binary,多分类选macro/micro ] ) return model # 初始化RandomSearch,指定多目标调优 tuner = kt.RandomSearch( build_model, objective=[ kt.Objective("val_auc", direction="max"), kt.Objective("val_f1", direction="max") ], max_trials=10, directory='tuner_logs', project_name='auc_f1_tuning' ) # 启动调优(必须传入validation_data才会生成val_xxx指标) tuner.search( x_train, y_train, epochs=15, validation_data=(x_val, y_val), callbacks=[tf.keras.callbacks.EarlyStopping(patience=3)] )
方法二:自定义指标函数(兼容旧版TensorFlow)
如果你的TensorFlow版本低于2.7,没有内置F1Score,可以自定义F1计算函数:
from tensorflow.keras import backend as K def f1_metric(y_true, y_pred): true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1))) possible_positives = K.sum(K.round(K.clip(y_true, 0, 1))) predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1))) precision = true_positives / (predicted_positives + K.epsilon()) recall = true_positives / (possible_positives + K.epsilon()) f1_val = 2 * (precision * recall) / (precision + recall + K.epsilon()) return f1_val # 在build_model的compile中添加: model.compile( optimizer=..., loss='binary_crossentropy', metrics=['accuracy', tf.keras.metrics.AUC(name='auc'), f1_metric] ) # 此时调优目标要写函数名:kt.Objective("val_f1_metric", direction="max")
2. 多目标调优的权重配置
如果需要同时优化AUC和F1,可以给不同指标设置权重,KerasTuner会按加权平均结果排序:
objective=[ kt.Objective("val_auc", direction="max", weight=0.6), kt.Objective("val_f1", direction="max", weight=0.4) ]
3. 指标名称校验
训练时查看控制台日志,确认验证指标的名称(比如val_auc、val_f1)和你在kt.Objective中指定的完全一致——大小写、拼写都不能错,否则会触发KeyError。
常见排查点
- 必须传入
validation_data到tuner.search(),否则不会生成val_xxx前缀的验证指标。 - 多分类任务中,
F1Score的average参数要改成macro、micro或weighted,匹配任务需求。 - 自定义指标如果没指定
name,默认会用函数名作为指标名称,调优时要对应上。
内容的提问来源于stack exchange,提问作者R_Student
相关产品推荐
相关产品推荐

