如何通过已打开的文件对象加载Keras模型?
Great question! The short answer is: yes, you can load a Keras model using an open file object—but you need to make sure you're opening the file in the right mode.
Your original code fails because when you call open("/mypath/model.h5") without specifying a mode, it defaults to text mode ('r'), which doesn't work for binary HDF5 model files. HDF5 files are binary, so you need to open them in read-binary mode ('rb').
Correct Code Example
Here's how to make it work properly:
from keras.models import load_model # Recommended: Use a context manager to auto-close the file with open("/mypath/model.h5", "rb") as file: model = load_model(file)
If you prefer to manage the file handle manually (just remember to close it afterward!):
from keras.models import load_model file = open("/mypath/model.h5", "rb") model = load_model(file) file.close()
Why This Works
Keras relies on the h5py library under the hood to handle HDF5 model files, and h5py supports reading from file objects as long as they're opened in binary mode. Your initial attempt used text mode, which caused corrupted data reads and led to the failure.
This approach is especially handy if you're working with file-like objects (like streams from cloud storage or in-memory bytes) instead of local file paths directly.
内容的提问来源于stack exchange,提问作者Ismael

