在使用 TensorFlow Keras 加载 .h5
模型文件时,如果模型文件不存在,通常会抛出一个 FileNotFoundError
异常。为了避免这种情况,可以在尝试加载模型之前检查文件是否存在。以下是一个示例代码,展示了如何实现这一点:
import os
from tensorflow.keras.models import load_model
def load_keras_model(model_path):
if not os.path.isfile(model_path):
print(f"Model file not found: {model_path}")
return None
try:
model = load_model(model_path)
print(f"Model loaded successfully from {model_path}")
return model
except Exception as e:
print(f"Failed to load model: {e}")
return None
# Example usage
model_path = 'path/to/your/model.h5'
model = load_keras_model(model_path)
if model is not None:
# Proceed with using the model
pass
else:
# Handle the case where the model could not be loaded
pass
os.path.isfile
检查指定的模型文件路径是否存在。如果不存在,则打印一条消息并返回 None
。None
。这种检查文件存在性的方法适用于任何需要加载模型的场景,例如:
通过这种方式,可以优雅地处理模型文件不存在的情况,避免程序因异常而中断。