Keras模型保存笔记

整理自Keras官方文档

https://keras-cn.readthedocs.io/en/latest/for_beginners/FAQ/#save_model

https://keras-cn.readthedocs.io/en/latest/other/callbacks/

1.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()


# 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)



3) 只保存模型的权重
model.save_weights('my_model_weights.h5')

# 初始化一个完全相同的模型
model.load_weights('my_model_weights.h5')

# 加载权重到不同的网络结构(有些层一样)中,例如fine-tune
# 或transfer-learning,可以通过层名字来加载模型:model.load_weights('my_model_weights.h5', by_name=True)

2.Keras保存checkpoint

from keras.callbacks import ModelCheckpoint

checkpointer = ModelCheckpoint(filepath="checkpoint-{epoch:02d}e
-val_acc_{val_acc:.2f}.hdf5", 
save_best_only=True, verbose=1,  period=50)

model.fit(data, labels, epochs=10, batch_size=32,
   callbacks=[checkpointer])    #callbacks为一个list,可有多个回调函数



filepath:checkpoint保存路径,上面加入了变量值来命名

verbose:信息展示模式,0或1

save_best_only:当设置为True时,将只保存在验证集上性能最好的模型,设为True避免保存过多不必要的模型

period:CheckPoint之间的间隔的epoch数,可避免训练前期保存不必要的模型

保存的checkpoint,可以直接作为 1. 1) 中保存的model调用,用来分类

model = load_model('checkpoint-05e-val_acc_0.58.hdf5')



也可以作为继续训练之前加载权重

猜你喜欢

转载自blog.csdn.net/luopeiyuan1990/article/details/83572885