Colab可加载.h5预训练模型,本地Jupyter加载失败求助
问题分析与解决方案
核心原因
报错的关键是模型中BatchNormalization层的axis参数被保存为列表格式[3],但你本地的Keras/TensorFlow版本要求axis是整数类型,而Colab环境使用的版本支持列表格式的axis,导致版本兼容性问题。
解决方案
1. 对齐Colab与本地的TensorFlow/Keras版本
在Colab和本地Jupyter中分别执行以下命令查看版本:
import tensorflow as tf print(tf.__version__)
将本地环境的TensorFlow版本升级/降级至与Colab一致,这是最直接解决版本兼容问题的方法。例如如果Colab用的是2.15.0,本地执行:
pip install tensorflow==2.15.0
2. 自定义加载逻辑处理BatchNormalization配置
如果不想调整版本,可以通过自定义对象修正BatchNormalization的配置,将列表格式的axis转为整数:
from keras.models import load_model from keras.layers import BatchNormalization # 修正BatchNormalization的配置,将axis从列表转为整数 def fix_batchnorm_config(config): if 'axis' in config and isinstance(config['axis'], list): config['axis'] = config['axis'][0] return config # 继承BatchNormalization,重载from_config方法 class FixedBatchNormalization(BatchNormalization): @classmethod def from_config(cls, config): config = fix_batchnorm_config(config) return super().from_config(config) # 加载模型时指定自定义对象 model = load_model('Desktop/test_set/eyedetection.h5', custom_objects={'BatchNormalization': FixedBatchNormalization})
3. 验证本地文件路径正确性
确保本地模型路径无误,建议使用绝对路径避免相对路径问题:
- Mac/Linux:
/Users/你的用户名/Desktop/test_set/eyedetection.h5 - Windows:
C:\\Users\\你的用户名\\Desktop\\test_set\\eyedetection.h5
内容的提问来源于stack exchange,提问作者Emrah Tezcan
相关产品推荐
相关产品推荐

