【问题标题】:Saving Model State and Load in Google Colab在 Google Colab 中保存模型状态和加载
【发布时间】:2020-09-14 07:29:20
【问题描述】:

我总共要训练 500 个 epoch。但是在 google colab 中完成每个 epoch 需要 8 分钟。任何人都可以帮助我如何在特定数量的时期完成后保存我的模型状态并从我离开谷歌 Colab 的地方重新开始训练??

【问题讨论】:

  • 欢迎来到 SO。请考虑发布相关代码。
  • 您可以在 colab 上安装您的 Google Drive,并在每个 n epochs 之后将 model_dict 直接保存/加载到您的驱动器中。这是example
  • 这里是如何在 pytorch 中保存和加载检查点的一般示例。 - pytorch.org/tutorials/recipes/recipes/…
  • from imageai.Detection.Custom import DetectionModelTrainer trainer = DetectionModelTrainer() trainer.setModelTypeAsYOLOv3() trainer.setDataDirectory(data_directory="/content/drive/My Drive/Dataset") trainer.setTrainConfig(object_names_array= ["object1","object 2"], batch_size=4, num_experiments=421) trainer.trainModel()
  • 这是我的代码

标签: python tensorflow pytorch


【解决方案1】:

如果你正在使用 tensorflow,你可以使用 keras 的 ModelCheckpoint 回调来做到这一点。挂载您的谷歌驱动器以保存模型。

pip install -q pyyaml h5py  # Required to save models in HDF5 format

filepath = '/content/drive/'
checkpoint_callback = tf.keras.callbacks.ModelCheckpoint(filepath= filepath, 
                                                         save_weights_only=True, save_best_only=True)

model.fit(x_train, y_train, epochs=500, callbacks= [checkpoint_callback])

模型权重会在每个 epoch 结束时保存,如果它是迄今为止最好的。 您可以稍后加载模型权重:

model.load_weights(checkpoint_filepath)

【讨论】:

  • 感谢您的回答!当我在创建模型的 colab 会话中执行 model.load_weights('./path/to/the/model_file.h5') 时,一切正常。但是当我重新启动 colab 笔记本(并且所有变量都被删除)时,我再也找不到这个文件了。它真的会在会话结束时被删除还是我能以某种方式找到它?谢谢
【解决方案2】:

如果您想在 pytorch 中经过一定数量的 epoch 后将模型保存到 google drive,您可以使用

首先挂载谷歌驱动器

from google.colab import drive
drive.mount('/content/gdrive')

然后在 colab 中运行单元并进行身份验证。现在应该安装谷歌驱动器。 现在将路径设置为

PATH = F"/content/gdrive/My Drive/{Model name}/{model_save_name}"

你可以保存模型

    if(epoch%(number_epoch_to_save)==0):
        torch.save(model.state_dict(), PATH)

可以在https://pytorch.org/tutorials/beginner/saving_loading_models.html找到示例文档

【讨论】:

    猜你喜欢
    • 2021-01-06
    • 1970-01-01
    • 2018-09-05
    • 2020-10-28
    • 2018-11-21
    • 2020-06-19
    • 2019-08-30
    • 2011-10-03
    • 1970-01-01
    相关资源
    最近更新 更多