调用tf.keras.models.load_model加载模型报错,寻求解决方案
解决Keras加载
.keras模型时的"File not found"错误 问题场景
执行代码:
modeel = tf.keras.models.load_model('trained_model.keras')
触发如下异常(已确认文件在当前工作目录):
ValueError Traceback (most recent call last) Cell In[20], line 1 ----> 1 modeel = tf.keras.models.load_model('trained_model.keras') File c:\Users\arman\AppData\Local\Programs\Python\Python312\Lib\site-packages\keras\src\saving\saving_api.py:193, in load_model(filepath, custom_objects, compile, safe_mode) 189 return legacy_h5_format.load_model_from_hdf5( 190 filepath, custom_objects=custom_objects, compile=compile 191 ) 192 elif str(filepath).endswith(".keras"): --> 193 raise ValueError( 194 f"File not found: filepath={filepath}. " 195 "Please ensure the file is an accessible `.keras` " 196 "zip file." 197 ) 198 else: 199 raise ValueError( 200 f"File format not supported: filepath={filepath}. " 201 "Keras 3 only supports V3 `.keras` files and " (...) 210 "might have a different name)." 211 ) ValueError: File not found: filepath=trained_model.keras. Please ensure the file is an accessible `.keras` zip file.
解决办法
- 验证文件格式:
.keras是Keras 3的压缩格式模型文件,用解压工具尝试打开它。如果无法解压,说明文件损坏或不是标准Keras V3模型。若是旧版Keras保存的,需用Keras 3重新导出,或指定兼容加载方式。 - 确认工作目录:执行以下代码查看当前代码运行的目录,确保文件确实在该路径下:
import os print(os.getcwd()) - 使用绝对路径:直接传入文件完整绝对路径,避免相对路径歧义,示例:
tf.keras.models.load_model('C:/Users/arman/your_actual_folder/trained_model.keras') - 检查文件权限:确保当前用户拥有该文件的读取权限,Windows系统下注意文件是否被锁定或权限受限。
- 重新生成模型:若文件损坏,重新训练模型并使用Keras 3的
model.save('trained_model.keras')命令保存标准格式文件。
内容的提问来源于stack exchange,提问作者Armaan
相关产品推荐
相关产品推荐

