1. 出现问题
在用Keras的时候,保存模型,再次导入模型的时候,出现了如下报错:
from keras.models import load_model
model = load_model('mode.h5')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/yaomengcheng/anaconda3/envs/monolce3/lib/python3.7/site-packages/keras/engine/saving.py", line 492, in load_wrapper
return load_function(*args, **kwargs)
File "/home/yaomengcheng/anaconda3/envs/monolce3/lib/python3.7/site-packages/keras/engine/saving.py", line 584, in load_model
model = _deserialize_model(h5dict, custom_objects, compile)
File "/home/yaomengcheng/anaconda3/envs/monolce3/lib/python3.7/site-packages/keras/engine/saving.py", line 273, in _deserialize_model
model_config = json.loads(model_config.decode('utf-8'))
AttributeError: 'str' object has no attribute 'decode'
开始以为是模型保存的问题,为了解决此类报错,尝试过各种方法,比如对比了一下model.save()和model.save_weights()的区别,这两个区别主要在于保存从区别,具体如下:
- model.save()既保持了模型的图结构,又保存了模型的参数,这种保存的模型可以直接load_model()打开。
- model.save_weights()只保存了模型的参数,但并没有保存模型的图结构,这种打开比较麻烦,具体步骤如下:
from keras.models import Model
from keras.layers import Input, Dense
inputs = Input(shape=(784, ))
x = Dense(64, activation='relu')(inputs)
x = Dense(64, activation='relu')(x)
y = Dense(10, activation='softmax')(x)
model = Model(inputs=inputs, outputs=y)
鉴于此,今后保存模型的话,如果储存没有问题,用model.save()将所有都保存下来。
2. 解决报错
通过前面尝试各种的模型保存方式,发现我们的方式没有什么问题,然后再在网上查询问题,结果发现可能是由于h5py版本的问题,具体的是我们安装keras的时候,自动安装了3.5.0。
pip show h5py
Name: h5py
Version: 3.5.0
Summary: Read and write HDF5 files from Python
Home-page: http://www.h5py.org
Author: Andrew Collette
Author-email: andrew.collette@gmail.com
License: BSD
Location: /home/yaomengcheng/anaconda3/envs/monolce3/lib/python3.7/site-packages
Requires: cached-property, numpy
Required-by: Keras, Keras-Applications
在前人的介绍中,这里应该安装2.10.0,然后我们这里测试了一下,结果完美的解决了问题。
pip install h5py==2.10.0
Looking in indexes: https://pypi.tuna.tsinghua.edu.cn/simple/
Collecting h5py==2.10.0
Downloading https://pypi.tuna.tsinghua.edu.cn/packages/3f/c0/abde58b837e066bca19a3f7332d9d0493521d7dd6b48248451a9e3fe2214/h5py-2.10.0-cp37-cp37m-manylinux1_x86_64.whl (2.9 MB)
|████████████████████████████████| 2.9 MB 1.0 MB/s
Requirement already satisfied: numpy>=1.7 in /home/yaomengcheng/anaconda3/envs/monolce3/lib/python3.7/site-packages (from h5py==2.10.0) (1.21.2)
Requirement already satisfied: six in /home/yaomengcheng/anaconda3/envs/monolce3/lib/python3.7/site-packages (from h5py==2.10.0) (1.16.0)
Installing collected packages: h5py
Attempting uninstall: h5py
Found existing installation: h5py 3.5.0
Uninstalling h5py-3.5.0:
Successfully uninstalled h5py-3.5.0
Successfully installed h5py-2.10.0
3. 总结
- 对于模型的导入,用2.10.0版本的h5py
- 对于模型保存,尽量用model.save()。