TensorFlow 2.17.0加载ResNet50预训练权重报错Size must be positive的解决方法
解决TensorFlow 2.17.0加载ResNet50预训练权重的报错问题
问题描述
在TensorFlow 2.17.0环境中运行以下代码时触发ValueError: Size must be positive错误,该代码在TensorFlow 2.18.0中可正常执行:
from tensorflow.keras.applications.resnet50 import ResNet50 base_model = ResNet50( input_shape=(224, 224, 3), include_top=False, weights='imagenet' )
错误根源是h5py库与TensorFlow 2.17.0的兼容性问题,导致预训练权重文件解析失败。
解决方案
方案1:手动下载预训练权重并本地加载
- 获取ResNet50的ImageNet预训练权重文件(无顶层全连接层版本,文件名通常为
resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5) - 将文件保存到本地路径,修改代码指定权重路径:
from tensorflow.keras.applications.resnet50 import ResNet50 base_model = ResNet50( input_shape=(224, 224, 3), include_top=False, weights='/your/local/path/resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5' )
方案2:降级h5py版本适配TensorFlow 2.17.0
执行以下命令降级h5py至与TF2.17兼容的版本:
pip install h5py==3.10.0 --force-reinstall
完成后重新运行原代码即可尝试加载预训练权重。
方案3:改用TensorFlow Hub加载ResNet50
通过TensorFlow Hub加载预训练模型,绕开Keras内置权重加载的兼容性问题:
import tensorflow as tf import tensorflow_hub as hub # 加载ResNet50特征提取模型(无顶层分类层,需使用TensorFlow Hub提供的对应模型路径) resnet50_hub = hub.KerasLayer( "resnet_v1_50特征向量模型的Hub路径", input_shape=(224, 224, 3), trainable=False # 如需微调可设置为True ) # 构建特征提取模型 feature_extractor = tf.keras.Sequential([resnet50_hub]) # 测试特征提取 test_input = tf.random.normal((1, 224, 224, 3)) features = feature_extractor(test_input) print(f"特征输出形状: {features.shape}")
内容的提问来源于stack exchange,提问作者Mahdi Safarzadeh
相关产品推荐
相关产品推荐

