gpt4 book ai didi

python-3.x - google colaboratory,重量下载(导出保存的模型)

转载 作者:行者123 更新时间:2023-12-03 13:45:14 24 4
gpt4 key购买 nike

我使用Keras库创建了一个模型,并将该模型另存为.json及其权重带有.h5扩展名。如何将其下载到本地计算机上?

保存我遵循的模型link

最佳答案

这对我有用!
使用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')})

现在,检查您的Google驱动器。

下次运行时,请尝试重新加载砝码
# 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:
account.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_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)})

关于python-3.x - google colaboratory,重量下载(导出保存的模型),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48924165/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com