您的位置:首页 > 其它

keras如何保存模型,进行加载预测

2020-02-05 17:22 162 查看

注:我是从keras中文文档上摘过来的
https://keras-cn.readthedocs.io/en/latest/for_beginners/FAQ/#keras_1
如何保存Keras模型?

我们不推荐使用pickle或cPickle来保存Keras模型

你可以使用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’)
如果你只是希望保存模型的结构,而不包含其权重或配置信息,可以使用:

save as JSON

json_string = model.to_json()

save as YAML

yaml_string = model.to_yaml()
这项操作将把模型序列化为json或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)
如果需要保存模型的权重,可通过下面的代码利用HDF5进行保存。注意,在使用前需要确保你已安装了HDF5和其Python库h5py

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)
例如:

“”"
假如原模型为:
model = Sequential()
model.add(Dense(2, input_dim=3, name=“dense_1”))
model.add(Dense(3, name=“dense_2”))

model.save_weights(fname)
“”"

new model

model = Sequential()
model.add(Dense(2, input_dim=3, name=“dense_1”)) # will be loaded
model.add(Dense(10, name=“new_dense”)) # will not be loaded

load weights from first model; will only affect the first layer, dense_1.

model.load_weights(fname, by_name=True)

  • 点赞
  • 收藏
  • 分享
  • 文章举报
酆小强 发布了14 篇原创文章 · 获赞 0 · 访问量 2541 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: