Keras 笔记

本章部分摘自博客
问题一:怎么保存Keras模型结构
(1)如果只保存模型结构(不包含其权重和配置信息),代码如下:

# save as JSON  
json_string = model.to_json()  
# save as YAML  
yaml_string = model.to_yaml()  
# model reconstruction from JSON:  
from keras.modelsimport model_from_json  
model = model_from_json(json_string)  

# model reconstruction from YAML  
model =model_from_yaml(yaml_string) 

(2)如果需要保存数据

model.save_weights('my_model_weights.h5')  
model.load_weights('my_model_weights.h5')  

(3)综合运用:

json_string = model.to_json()  
open('my_model_architecture.json','w').write(json_string)  
model.save_weights('my_model_weights.h5')  
model = model_from_json(open('my_model_architecture.json').read())  
model.load_weights('my_model_weights.h5')  

(4)更简单的方法:
使用model.save(filepath)将Keras模型和权重保存在一个HDF5文件中,该文件将包含:
1、模型的结构,以便重构该模型
2、模型的权重
3、训练配置(损失函数,优化器等)
4、优化器的状态,以便于从上次训练中断的地方开始
使用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')

问题二:将中间层的输出可视化
通过Theano function的output.示例如下:

# with a Sequential model  
get_3rd_layer_output =theano.function([model.layers[0].input],  
 model.layers[3].get_output(train=False))  
layer_output =get_3rd_layer_output(X)  

# with a Graph model  
get_conv_layer_output =theano.function([model.inputs[i].inputfor iin model.input_order],model.outputs['conv'].get_output(train=False), on_unused_input='ignore')  
conv_output = get_conv_output(input_data_dict)  

问题三:在训练时,数据会如何被随机打乱
如果model.fit中的参数suffle=True时,会随机打算每一次epoch的数据。(默认打乱)
但是验证数据默认不会打乱。

问题四:当验证损失不再继续降低时,中断训练:
用EarlyStopping回调函数,代码如下:

from keras.callbacksimport EarlyStopping  
early_stopping =EarlyStopping(monitor='val_loss', patience=2)  
model.fit(X, y, validation_split=0.2, callbacks=[early_stopping])  

问题五:记录每一次epoch的训练/验证损失/准确度:
Model.fit函数会返回一个 History 回调,该回调有一个属性history包含一个封装有连续损失/准确的lists。代码如下:

hist = model.fit(X, y,validation_split=0.2)  
print(hist.history) 

问题六:让Keras脚本每次产生确定的数据
在引入Kerans之前,引入numpy,并且用其random.seed(种子)产生一个随机数对象。这样在相同硬件的机器上运行时,每次产生的随机数的顺序都是一样的。

import numpy as np  
np.random.seed(1234)  

# Keras imports start here  
from keras import ...  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值