keras只包含两种神经网络模型,分别是Sequantial模型和泛化模型。模型的保存和使用方法如下:
1、只保存和使用模型结构,不包含配置和权重
#保存成json格式的文件
json_string = model.to_json()
open('my_model_architecture.json','w').write(json_string)
from keras.models import model_from_json
model = model_from_json(open('my_model_architecture.json').read())
#保存成yaml文件
yaml_string = model.to_yaml()
open('my_model_architectrue.yaml','w').write(yaml_string)
from keras.models import model_from_yaml
model = model_from_yaml(open('my_model_architecture.yaml').read())
2、只保存和使用权重
#利用HDF5进行保存
model.save_weights('my_model_weights.h5')
model.load_weights('my_model_weights.h5')
3、从配置中构造模型--也可以存成文件,然后从文件中重构
config = model.get_config()
from keras.models import Model
model = Model.from_config(config)
# or, for Sequential
from keras.models import Sequential model = Sequential.from_config(config)
4、保存
和使用
模型、权重、配置
model.save(filepath)
import keras.models import load_model
model = load_model(filepath)