在VS Code中使用TensorFlow和Keras加载模型时出错求助
解决模型加载时的Unknown Layer错误
确保自定义层代码一致:VS Code环境中必须包含训练模型时用到的所有自定义层的完整代码,类名、继承关系、内部方法(
__init__、call等)要和训练时完全一致,不能有任何修改。用
custom_object_scope注册自定义层:加载模型时,通过keras.utils.custom_object_scope将自定义层映射到对应的类,示例代码如下:from keras.models import load_model from keras.utils import custom_object_scope # 导入你定义的自定义层类,路径根据实际情况调整 from your_module import MyCustomLayer with custom_object_scope({'MyCustomLayer': MyCustomLayer}): model = load_model('modelName.h5')完善自定义层的
get_config方法:如果自定义层没有正确实现get_config,模型保存时无法完整序列化层的参数,导致加载失败。示例实现:import keras class MyCustomLayer(keras.layers.Layer): def __init__(self, my_param, **kwargs): super().__init__(**kwargs) self.my_param = my_param def call(self, inputs): # 自定义层的运算逻辑 return inputs * self.my_param def get_config(self): config = super().get_config() config['my_param'] = self.my_param return config核对环境版本:确认Jupyter和VS Code中TensorFlow/Keras的版本完全相同,版本不匹配也可能引发此类错误。可在两个环境中运行以下命令查看版本:
import tensorflow as tf import keras print(tf.__version__) print(keras.__version__)
内容的提问来源于stack exchange,提问作者Amandeep Singh
相关产品推荐
相关产品推荐

