keras学习笔记(2)——模型的存储与读取

模型的储存引用
方法一:
会保存
模型的结构,以便重构该模型
模型的权重
训练配置(损失函数,优化器等)
优化器的状态,以便于从上次训练中断的地方开始

from keras.models import load_model
model.save('D:\\tutorials\\Data\\intradayCN\\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('D:\\tutorials\\Data\\intradayCN\\my_model.h5')

如果只是希望保存模型的结构,而不包含其权重或配置信息,可以使用:

#save as JSON
model_json = model.to_json()
with open('D:\\tutorials\\Data\\intradayCN\\my_model2.json', 'w') as file:
    file.write(model_json)
#save as YAML
model_yaml = model.to_yaml()
with open('D:\\tutorials\\Data\\intradayCN\\my_model3.yaml', 'w') as file:
    file.write(model_yaml)

从保存好的json文件或yaml文件中载入模型:

#model reconstruction from JSON:
from keras.models import model_from_json

with open('D:\\tutorials\\Data\\intradayCN\\my_model2.json', 'r') as file:
    model_json = file.read()
 
new_model = model_from_json(model_json)
#model reconstruction from YAML
from keras.models import model_from_yaml

with open('D:\\tutorials\\Data\\intradayCN\\my_model3.yaml', 'r') as file:
    model_yaml = file.read()
 
new_model = model_from_yaml(model_yaml)

如果需要保存模型的权重,可通过下面的代码利用HDF5进行保存。在使用前需要确保已安装了HDF5和其Python库h5py

model.save_weights('D:\\tutorials\\Data\\intradayCN\\my_model_weights.h5')

如果需要在代码中初始化一个完全相同的模型,使用:

model.load_weights('D:\\tutorials\\Data\\intradayCN\\my_model_weights.h5')

如果需要加载权重到不同的网络结构(有些层一样)中,例如fine-tune或transfer-learning,可以通过层名字来加载模型:

model.load_weights('D:\\tutorials\\Data\\intradayCN\\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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值