在 keras 中保存和加载权重 [英] Save and load weights in keras
问题描述
我正在尝试从我训练的模型中保存和加载权重.
Im trying to save and load weights from the model i have trained.
我用来保存模型的代码是.
the code im using to save the model is.
TensorBoard(log_dir='/output')
model.fit_generator(image_a_b_gen(batch_size), steps_per_epoch=1, epochs=1)
model.save_weights('model.hdf5')
model.save_weights('myModel.h5')
让我知道这是否是一种不正确的方法,或者是否有更好的方法.
Let me know if this an incorrect way to do it,or if there is a better way to do it.
但是当我尝试加载它们时,使用这个,
but when i try to load them,using this,
from keras.models import load_model
model = load_model('myModel.h5')
但我收到此错误:
ValueError Traceback (most recent call
last)
<ipython-input-7-27d58dc8bb48> in <module>()
1 from keras.models import load_model
----> 2 model = load_model('myModel.h5')
/home/decentmakeover2/anaconda3/lib/python3.5/site-
packages/keras/models.py in load_model(filepath, custom_objects, compile)
235 model_config = f.attrs.get('model_config')
236 if model_config is None:
--> 237 raise ValueError('No model found in config file.')
238 model_config = json.loads(model_config.decode('utf-8'))
239 model = model_from_config(model_config,
custom_objects=custom_objects)
ValueError: No model found in config file.
对我可能做错了什么有什么建议吗?提前致谢.
Any suggestions on what i may be doing wrong? Thank you in advance.
推荐答案
这是一个 YouTube 视频,它准确地解释了您想要做什么:保存和加载 Keras 模型
Here is a YouTube video that explains exactly what you're wanting to do: Save and load a Keras model
Keras 提供了三种不同的保存方法.这些在上面的视频链接(带有示例)和下面都有描述.
There are three different saving methods that Keras makes available. These are described in the video link above (with examples), as well as below.
首先,您收到错误的原因是您错误地调用了 load_model
.
First, the reason you're receiving the error is because you're calling load_model
incorrectly.
要保存和加载模型的权重,您首先要使用
To save and load the weights of the model, you would first use
model.save_weights('my_model_weights.h5')
保存权重,如您所显示的.要加载权重,您首先需要构建模型,然后在模型上调用 load_weights
,如
to save the weights, as you've displayed. To load the weights, you would first need to build your model, and then call load_weights
on the model, as in
model.load_weights('my_model_weights.h5')
另一种保存技术是model.save(filepath)
.这个 save
函数保存:
Another saving technique is model.save(filepath)
. This save
function saves:
- 模型的架构,允许重新创建模型.
- 模型的权重.
- 训练配置(损失、优化器).
- 优化器的状态,允许从上次中断的地方继续训练.
要加载这个保存的模型,您可以使用以下内容:
To load this saved model, you would use the following:
from keras.models import load_model
new_model = load_model(filepath)'
最后,model.to_json()
,只保存模型的架构.要加载架构,您将使用
Lastly, model.to_json()
, saves only the architecture of the model. To load the architecture, you would use
from keras.models import model_from_json
model = model_from_json(json_string)
这篇关于在 keras 中保存和加载权重的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!