Keras,优化时保存状态的最佳方式
Keras, best way to save state when optimizing
我只是想知道在优化模型时保存模型状态的最佳方法是什么。我想这样做,这样我就可以 运行 它一段时间,保存它,稍后再回来使用它。我知道有一个函数可以保存权重,另一个函数可以将模型保存为 JSON。在学习过程中,我需要保存模型的权重和参数。这包括动量和学习率等参数。有没有办法将模型和权重保存在同一个文件中。我读到使用 pickle 不被认为是好的做法。梯度体面的动量也会包含在模型中 JSON 或权重中吗?
您可以创建一个包含权重和架构的 tar 存档,以及一个包含 model.optimizer.get_state()
返回的优化器状态的 pickle 文件。
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')
You can use model.save(filepath) to save a Keras model into a single
HDF5 file which will contain:
- the architecture of the model, allowing to re-create the model
- the weights of the model
- the training configuration (loss, optimizer)
- the state of the optimizer, allowing to resume training exactly where you left off.
You can then use keras.models.load_model(filepath) to reinstantiate your model. load_model will also take care of compiling the model using the saved training configuration (unless the model was never compiled in the first place).
Keras 常见问题解答:How can I save a Keras model?
我只是想知道在优化模型时保存模型状态的最佳方法是什么。我想这样做,这样我就可以 运行 它一段时间,保存它,稍后再回来使用它。我知道有一个函数可以保存权重,另一个函数可以将模型保存为 JSON。在学习过程中,我需要保存模型的权重和参数。这包括动量和学习率等参数。有没有办法将模型和权重保存在同一个文件中。我读到使用 pickle 不被认为是好的做法。梯度体面的动量也会包含在模型中 JSON 或权重中吗?
您可以创建一个包含权重和架构的 tar 存档,以及一个包含 model.optimizer.get_state()
返回的优化器状态的 pickle 文件。
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')
You can use model.save(filepath) to save a Keras model into a single HDF5 file which will contain:
- the architecture of the model, allowing to re-create the model
- the weights of the model
- the training configuration (loss, optimizer)
- the state of the optimizer, allowing to resume training exactly where you left off.
You can then use keras.models.load_model(filepath) to reinstantiate your model. load_model will also take care of compiling the model using the saved training configuration (unless the model was never compiled in the first place).
Keras 常见问题解答:How can I save a Keras model?