加载HDF5模型权重时触发OSError(文件截断),原因何在?
HDF5模型加载错误原因解析
错误重现
执行以下代码时触发错误:
# Load the hdf5 files resnet50 = h5py.File('/content/RestNet 50 best_model.hdf5', 'r') ourmodel = h5py.File('/content/best_model.hdf5', 'r') resnet152 = h5py.File('/content/best_model_4.hdf5', 'r') # Get the predictions from each model predictions1 = resnet50.predict(images) predictions2 = ourmodel.predict(images) predictions3 = resnet152.predict(images) # Combine the predictions using a majority vote predictions = np.array([predictions1, predictions2, predictions3]) predictions = np.mean(predictions, axis=0) print(predictions)
错误提示:
OSError: Unable to open file (truncated file: eof = 225443840, sblock->base_addr = 0, stored_eof = 245806944)
核心原因
- 文件被截断/不完整:错误信息明确显示文件实际大小(
eof=225443840)远小于HDF5文件头中记录的预期大小(stored_eof=245806944),说明文件在下载、保存过程中被中断,或是存储介质故障导致写入不完整。 - 文件结构损坏:保存模型时程序意外崩溃、磁盘空间不足,会导致HDF5的内部结构损坏,无法被正常读取。
- 代码使用错误:额外提醒——你用
h5py.File()打开文件后直接调用.predict()是错误的,h5py仅用于读取HDF5文件内容,不能直接作为模型对象调用预测方法。正确做法是用tf.keras.models.load_model()加载完整模型。
内容的提问来源于stack exchange,提问作者Saad Saleem
相关产品推荐
相关产品推荐

