保存和导入模型(包含权重等等信息)
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')
保存模型的结构,无权重
# save as JSON
json_string = model.to_json()
# save as YAML
yaml_string = model.to_yaml()
#从保存好的json文件或yaml文件中载入模型
# model reconstruction from JSON:
from keras.models import model_from_json
model = model_from_json(json_string) # model reconstruction from YAML
model = model_from_yaml(yaml_string)
需要保存模型的权重model.save_weights()
model.save_weights('my_model_weights.h5')
model.load_weights('my_model_weights.h5') #初始化一个完全相同的模型
model.load_weights('my_model_weights.h5', by_name=True) #加载权重到不同的网络结构,例如fine-tuning;可以通过层名字来加载
使用ModelCheckpoint保存模型
预定义保存的hdf5文件名,再初始化ModelCheckpoint,将其加入Keras的callback里。只要模型效果变好就保存:
# checkpoint
filepath="weights-{epoch:02d}-{val_acc:.2f}.hdf5"
checkpoint = ModelCheckpoint(filepath, monitor='val_acc', verbose=1, save_best_only=True, mode='max')
# Fit the model
model.fit(X, Y, validation_split=0.33, epochs=150, batch_size=10, callbacks=[checkpoint], verbose=0)
加载权重
model.load_weights("weights.best.hdf5")
# Compile model
model.compile(...)
# estimate accuracy
scores = model.evaluate(X, Y, verbose=0)
print('{}: {:.2%}'.format(model.metrics_names[1], scores[1]))