簡體   English   中英

google colaboratory,重量下載(導出保存的模型)

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

我使用 Keras 庫創建了一個模型,並將模型保存為 .json 及其權重,擴展名為 .h5。 我怎樣才能把它下載到我的本地機器上?

為了保存模型,我點擊了這個鏈接

這對我有用!! 使用 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)})

試試這個

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

這是一個對我有用的解決方案:

設置 b/w Google Colab 和您的驅動器身份驗證:

步驟:

- 粘貼代碼如下

- 此過程將生成兩個 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}

完成此身份驗證后,使用以下代碼建立連接:

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

現在查看您的 Google Drive 中的文件列表:

!ls drive

將 Keras 模型輸出保存到 Drive,過程與存儲在本地驅動器完全相同:

- 像往常一樣運行 Keras 模型

訓練模型后,假設您要將模型輸出(.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")

您將在 Google Drive 的相應文件夾中找到這些文件,您可以從那里下載,如下所示:

在此處輸入圖片說明

files.download不允許您直接下載大文件。 一種解決方法是使用下面的 pydrive 代碼段將您的權重保存在 Google 驅動器上。 只需更改您的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')))

要將模型下載到本地系統,可以使用以下代碼 - 下載 json 文件:

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

files.download("model1.json")

下載權重:

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

下載到本地系統:

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

您可以在訓練后運行以下操作。

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

然后檢查保存 ckpt 文件的位置。

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

最后下載有重量的文件!

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

只需使用model.save()。 下面我創建了一個變量來存儲模型的名稱,然后我用 model.save() 保存它。 我使用了 google collab,但它應該適用於其他人在此處輸入圖片描述

我只是將模型拖放到內容文件夾中。 它在我的谷歌驅動器中。 在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM