Keras,优化时保存状态的最佳方法

2024-06-16 10:41:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我只是想知道在优化模型的同时保存模型状态的最佳方法是什么。我想这样做,这样我就可以运行它一段时间,保存它,稍后再回来。我知道有一个函数用于保存权重,另一个函数用于将模型保存为JSON。在学习过程中,我需要保存模型的权重和参数。这包括动量和学习率等参数。有没有办法将模型和权重都保存在同一个文件中。我读到用泡菜不被认为是好的做法。另外,gradident decept的动量是否包含在JSON模型中或权重中?在


Tags: 文件方法函数模型json参数过程状态
2条回答

您可以创建一个包含权重和体系结构的tar归档文件,以及一个pickle文件,其中包含model.optimizer.get_state()返回的优化器状态。在

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?

相关问题 更多 >