如何将旧Keras模型中已弃用的tfa.metrics.F1Score迁移至tf.keras.metrics.F1Score?
问题背景
旧Keras模型编译时使用了TensorFlow Addons中已弃用的F1Score指标,现在需要迁移到TensorFlow官方的tf.keras.metrics.F1Score。当前加载模型的代码为:
custom_objects = { 'F1Score': F1Score(num_classes=4, threshold=0.5) }
替换为新指标后出现错误:
ValueError: Unable to restore custom object of class "Addons>F1Score" (type _tf_keras_metric). Please make sure that this class is included in the
custom_objectsarg when callingload_model(). Also, check that the class implementsget_configandfrom_config.Complete metadata: {'class_name': 'Addons>F1Score', 'name': 'f1_score', 'dtype': 'float32', 'config': {'name': 'f1_score', 'dtype': 'float32', 'num_classes': 4, 'average': None, 'threshold': 0.5}, 'shared_object_id': 32}
解决方法
方法一:映射旧类名到新指标类
模型保存时记录的指标类名是Addons>F1Score,因此需要在custom_objects中用这个旧类名对应新的tf.keras.metrics.F1Score实现:
import tensorflow as tf from tensorflow.keras.metrics import F1Score custom_objects = { 'Addons>F1Score': F1Score } # 加载模型 model = tf.keras.models.load_model('your_model_path.h5', custom_objects=custom_objects)
加载完成后,模型会自动从保存的配置中读取原参数(如num_classes=4、threshold=0.5),用新的F1Score类恢复指标。
方法二:加载模型后重新编译替换指标
如果方法一不生效,可以先跳过指标加载,之后重新编译模型并替换为新指标:
import tensorflow as tf from tensorflow.keras.metrics import F1Score # 加载模型时不编译,跳过指标恢复 model = tf.keras.models.load_model('your_model_path.h5', compile=False) # 重新编译,保留原优化器和损失函数,替换为新指标 model.compile( optimizer=model.optimizer, loss=model.loss, metrics=[F1Score(num_classes=4, threshold=0.5)] )
若原模型的优化器或损失函数也是自定义对象,需要将它们一并加入custom_objects后再加载。
内容的提问来源于stack exchange,提问作者Sime

