简体   繁体   English

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

[英]google colaboratory, weight download (export saved models)

I created a model using Keras library and saved the model as .json and its weights with .h5 extension.我使用 Keras 库创建了一个模型,并将模型保存为 .json 及其权重,扩展名为 .h5。 How can I download this onto my local machine?我怎样才能把它下载到我的本地机器上?

to save the model I followed this link为了保存模型,我点击了这个链接

This worked for me !!这对我有用!! Use PyDrive API使用 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')})

Same for weights重量相同

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')})

Now, check your google drive.现在,检查您的谷歌驱动器。

On next run, try reloading the weights下次运行时,尝试重新加载权重

# 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')

A Better NEW way to do it (post update) ... forget the previous (also works)一种更好的新方法(更新后)......忘记以前的(也有效)

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

You will be prompted for authorization Go to this URL in a browser: something like : accounts.google.com/o/oauth2/auth?client_id=.....系统将提示您进行授权 在浏览器中转到此 URL:类似于:accounts.google.com/o/oauth2/auth?client_id=.....

obtain the auth code from the link, paste your authorization code in the space从链接中获取授权码,在空白处粘贴您的授权码

Then you can use drive normally as your own disk然后你可以正常使用驱动器作为你自己的磁盘

Save weights or even the full model directly直接保存权重甚至完整模型

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

Even a Better way, use call backs, which automatically checks if the model at each epoch achieved better than the best saved one and save the one with best validation loss so far.更好的方法是使用回调,它会自动检查每个时期的模型是否比保存得最好的模型更好,并保存迄今为止验证损失最好的模型。

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) 
    ]

And use the call back in the model.fit并使用 model.fit 中的回调

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

You can load it later, even with a previous user defined loss function您可以稍后加载它,即使使用以前的用户定义的损失函数

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

Try this试试这个

from google.colab import files
files.download("model.json")

Here is a solution that worked for me:这是一个对我有用的解决方案:

Setup authentication b/w Google Colab and Your Drive:设置 b/w Google Colab 和您的驱动器身份验证:

Steps:步骤:

-Paste the code as is below - 粘贴代码如下

-This process will generate two URLs for authentication to complete, where you would have to copy the tokens and paste in the bar provided - 此过程将生成两个 URL 以完成身份验证,您必须在其中复制令牌并粘贴到提供的栏中

!apt-get install -y -qq software-properties-common python-software-properties module-init-tools
!add-apt-repository -y ppa:alessandro-strada/ppa 2>&1 > /dev/null
!apt-get update -qq 2>&1 > /dev/null
!apt-get -y install -qq google-drive-ocamlfuse fuse
from google.colab import auth
auth.authenticate_user()
from oauth2client.client import GoogleCredentials
creds = GoogleCredentials.get_application_default()
import getpass
!google-drive-ocamlfuse -headless -id={creds.client_id} -secret={creds.client_secret} < /dev/null 2>&1 | grep URL
vcode = getpass.getpass()
!echo {vcode} | google-drive-ocamlfuse -headless -id={creds.client_id} -secret={creds.client_secret}

Once this authentication is done, use the following codes to establish the connection:完成此身份验证后,使用以下代码建立连接:

!mkdir -p drive
!google-drive-ocamlfuse drive

Now to see the list of files in your Google Drive:现在查看您的 Google Drive 中的文件列表:

!ls drive

To save the Keras model output to Drive, the process is exactly the same as storing in local drive:将 Keras 模型输出保存到 Drive,过程与存储在本地驱动器完全相同:

-Run the Keras model as usual - 像往常一样运行 Keras 模型

Once the model is trained say you want to store your model outputs (.h5 and json) into the app folder of your Google Drive:训练模型后,假设您要将模型输出(.h5 和 json)存储到 Google Drive 的app文件夹中:

model_json = model.to_json()
with open("drive/app/model.json", "w") as json_file:
    json_file.write(model_json)
# serialize weights to HDF5
model.save_weights("drive/app/model_weights.h5")
print("Saved model to drive")

You will find the files in the respective folder of Google Drive, from where you can download as we can see below:您将在 Google Drive 的相应文件夹中找到这些文件,您可以从那里下载,如下所示:

在此处输入图片说明

files.download does not let you directly download large files. files.download不允许您直接下载大文件。 A workaround is to save your weights on Google drive, using this pydrive snippet below.一种解决方法是使用下面的 pydrive 代码段将您的权重保存在 Google 驱动器上。 Just change the filename.txt for your weights.h5 file只需更改您的weights.h5文件的filename.txt

# Install the PyDrive wrapper & import libraries.
# This only needs to be done once in a notebook.
!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

# Authenticate and create the PyDrive client.
# This only needs to be done once in a notebook.
auth.authenticate_user()
gauth = GoogleAuth()
gauth.credentials = GoogleCredentials.get_application_default()
drive = GoogleDrive(gauth)

# Create & upload a file.
uploaded = drive.CreateFile({'title': 'filename.csv'})
uploaded.SetContentFile('filename.csv')
uploaded.Upload()
print('Uploaded file with ID {}'.format(uploaded.get('id')))

To download the model to the local system, the following code would work- Downloading json file:要将模型下载到本地系统,可以使用以下代码 - 下载 json 文件:

model_json = model.to_json()
with open("model1.json","w") as json_file:
     json_file.write(model_jason)

files.download("model1.json")

Downloading weights:下载权重:

model.save('weights.h5')
files.download('weights.h5')

For downloading to local system:下载到本地系统:

from google.colab import files

#For model json
model_json = model.to_json()
with open("model1.json","w") as json_file:
     json_file.write(model_json)
files.download("model1.json")

#For weights
model.save('weights.h5')
files.download('weights.h5')

You can run the following after training.您可以在训练后运行以下操作。

saver = tf.train.Saver()
save_path = saver.save(session, "data/dm.ckpt")
print('done saving at',save_path)

Then check the location where the ckpt files were saved.然后检查保存 ckpt 文件的位置。

import os
print( os.getcwd() )
print( os.listdir('data') )

Finally download the files with weight!最后下载有重量的文件!

from google.colab import files
files.download( "data/dm.ckpt.meta" ) 

simply use model.save().只需使用model.save()。 Below here i created a variable to store the name of the model then i saved it with model.save().下面我创建了一个变量来存储模型的名称,然后我用 model.save() 保存它。 I used google collab but it should work for other s enter image description here我使用了 google collab,但它应该适用于其他人在此处输入图片描述

I just drag and dropped the model to drive in the contents folder.我只是将模型拖放到内容文件夹中。 And there it was in my google drive.它在我的谷歌驱动器中。 在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM