一. 保存Keras模型
这里不推荐使用pickle或cPickle来保存Keras模型。
1. 一般使用model.save(filepath)
将Keras模型和权重保存在一个HDF5文件中,该文件将包含:
- 模型的结构,以便重构该模型
- 模型的权重
- 训练配置(损失函数,优化器等)
- 优化器的状态,以便于从上次训练中断的地方开始
使用keras.models.load_model(filepath)
来重新实例化你的模型,如果文件中存储了训练配置的话,该函数还会同时完成模型的编译,例子如下:
from keras.models import load_model
model.save('my_model.h5') # creates a HDF5 file 'my_model.h5'
del model # deletes the existing model
# returns a compiled model
# identical to the previous one
model = load_model('my_model.h5')
2. 如果你只是希望保存模型的结构,而不包含其权重或配置信息,可以使用:
# save as JSON
json_string = model.to_json()
# save as YAML
yaml_string = model.to_yaml()
当然,你也可以从保存好的json文件或yaml文件中载入模型:
# mod