Keras 保存与加载网络模型

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_28413479/article/details/77367665

遇到问题:

keras使用预训练模型做训练时遇到的如下代码:

from keras.utils.data_utils import get_file

WEIGHTS_PATH = 'https://github.com/fchollet/deep-learning-models/releases/download/v0.1/vgg19_weights_tf_dim_ordering_tf_kernels.h5'
filepath = get_file('vgg19_weights_tf_dim_ordering_tf_kernels.h5', WEIGHTS_PATH, cache_subdir='models')

由于网络不稳定,下载时会出现如下报错:

Exception: URL fetch failure on https://github.com/fchollet/deep-learning-models/releases/download/v0.1/vgg19_weights_tf_dim_ordering_tf_kernels.h5: None -- [Errno 104] Connection reset by peer

解决方案:

翻墙使用浏览器下载https://github.com/fchollet/deep-learning-models/releases/download/v0.1/vgg19_weights_tf_dim_ordering_tf_kernels.h5可以断点继续
修改代码将上面的注释掉,开头添加

from keras.models import load_model

网络模型描述完后添加

model = load_model('my_model.h5')

延伸拓展:

你可以使用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)

猜你喜欢

转载自blog.csdn.net/qq_28413479/article/details/77367665