Keras保存模型/参数以及下载导入

保存和导入模型(包含权重等等信息)

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]))
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值