加载InceptionResNetV2训练的h5模型遇CustomScaleLayer未知层错误求助
解决加载InceptionResNetV2模型时的
CustomScaleLayer未知层错误 出现ValueError: Unknown layer: 'CustomScaleLayer'是因为你训练时使用的预训练InceptionResNetV2模型包含自定义层CustomScaleLayer,默认模型加载器无法识别这个未注册的自定义层。你之前尝试的KerasLayer是TensorFlow Hub相关层,和当前问题无关,因此无法解决。
解决方案
加载模型时,需要显式将CustomScaleLayer注册到custom_objects参数中,具体操作如下:
导入对应层
先确保导入InceptionResNetV2及其关联的CustomScaleLayer:from tensorflow.keras.applications.inception_resnet_v2 import InceptionResNetV2, CustomScaleLayer import tensorflow as tf加载模型
在load_model中指定custom_objects:model = tf.keras.models.load_model('detection.h5', custom_objects={'CustomScaleLayer': CustomScaleLayer})若不想单独导入
CustomScaleLayer,也可直接通过模块路径引用:model = tf.keras.models.load_model( 'detection.h5', custom_objects={'CustomScaleLayer': tf.keras.applications.inception_resnet_v2.CustomScaleLayer} )
原理说明
InceptionResNetV2预训练模型内部用CustomScaleLayer处理图像归一化等操作,当你保存包含该预训练模型的自定义模型时,这个层的定义不会被加载器自动识别,必须显式告知加载器该层的定义,才能成功加载模型。
内容的提问来源于stack exchange,提问作者Abhisar Sharma
相关产品推荐
相关产品推荐

