google colaboratory,权重下载(导出保存的模型)

新手上路,请多包涵

我使用 Keras 库创建了一个模型,并将模型保存为 .json 及其权重,扩展名为 .h5。我怎样才能将它下载到我的本地机器上?

保存模型我点击了这个 链接

原文由 Nishank Lakkakula 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 411
1 个回答

这对我有用!使用 PyDrive API

 !pip install -U -q PyDrive
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
from google.colab import auth
from oauth2client.client import GoogleCredentials

# 1. Authenticate and create the PyDrive client.
auth.authenticate_user()
gauth = GoogleAuth()
gauth.credentials = GoogleCredentials.get_application_default()
drive = GoogleDrive(gauth)

# 2. Save Keras Model or weights on google drive

# create on Colab directory
model.save('model.h5')
model_file = drive.CreateFile({'title' : 'model.h5'})
model_file.SetContentFile('model.h5')
model_file.Upload()

# download to google drive
drive.CreateFile({'id': model_file.get('id')})

重量相同

model.save_weights('model_weights.h5')
weights_file = drive.CreateFile({'title' : 'model_weights.h5'})
weights_file.SetContentFile('model_weights.h5')
weights_file.Upload()
drive.CreateFile({'id': weights_file.get('id')})

现在,检查你的谷歌驱动器。

下次运行时,尝试重新加载权重

# 3. reload weights from google drive into the model

# use (get shareable link) to get file id
last_weight_file = drive.CreateFile({'id': '1sj...'})
last_weight_file.GetContentFile('last_weights.mat')
model.load_weights('last_weights.mat')

一种更好的新方法(更新后)……忘记以前的(也有效)

 # Load the Drive helper and mount
from google.colab import drive
drive.mount('/content/drive')

系统将提示您授权 在浏览器中转到此 URL:类似于:accounts.google.com/o/oauth2/auth?client_id=…..

从链接中获取授权码,将您的授权码粘贴到空格中

然后你就可以正常使用驱动器作为你自己的磁盘

直接保存权重甚至完整模型

model.save_weights('my_model_weights.h5')
model.save('my_model.h5')

更好的方法是使用回调,它会自动检查模型在每个时期的表现是否优于保存的最佳模型,并保存迄今为止具有最佳验证损失的模型。

 my_callbacks = [
    EarlyStopping(patience=4, verbose=1),
    ReduceLROnPlateau(factor=0.1, patience=3, min_lr=0.00001, verbose=1),
    ModelCheckpoint(filepath = filePath + 'my_model.h5',
    verbose=1, save_best_only=True, save_weights_only=False)
    ]

并在 model.fit 中使用回调

model.fit_generator(generator = train_generator,
                    epochs = 10,
                    verbose = 1,
                    validation_data = vald_generator,
                    callbacks = my_callbacks)

您可以稍后加载它,即使使用以前的用户定义的损失函数

from keras.models import load_model
model = load_model(filePath + 'my_model.h5',
        custom_objects={'loss':balanced_cross_entropy(0.20)})

原文由 Samer Ayoub 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进