Google Colab使用教程

簡介

Google Colaboratory是谷歌開放的雲服務平臺,提供免費的CPU、GPU和TPU服務器。

目前深度學習在圖像和文本上的應用越來越多,不斷有新的模型、新的算法獲得更好的效果,然而,一方面對資源的要求越來越高,另一方面很多開源的模型在國內無法使用。例如,前段時間研究的圖片風格快速轉換中用到的模型訓練,在GPU上運行需要4個多小時,在CPU上無法想象。再者,tensorflow-hub開源的很多模型,我在使用某種軟件的前提下,依然無法訪問。

解決上述問題的一種方法,就是使用谷歌的Colab平臺。他提供的GPU型號是Tesla K80,並且預安裝了常用的框架,例如TensorFlow等。

賬號

Colab 和 Google Drive使用同一賬號登錄。

Google Drive: https://drive.google.com/drive
Colab: https://colab.research.google.com/drive/

使用流程

我將谷歌雲盤作爲Colab的外掛硬盤使用,每次啓動需要使用以下步驟:

  1. 在“我的雲端硬盤”中創建文件夾“Colab”,用於存放Colab中相關文件。(注意最好不要有空格,以避免不必要的錯誤)
  2. 點擊左上角“新建”,選擇Colaboratory。首次使用,需要關聯Colab應用。
  3. 創建新應用後,Drive的當前路徑下會生成 Unititled*.ipynb,也就是保存當前Colab窗口內容的文件。 每次新建,都需要重新配置環境。
  4. 配置“筆記本設置”。選擇“修改”-“筆記本設置”,設置python版本和服務器類型。
  5. 安裝必要的包和軟件。
!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}
  1. 關聯Google Drive。
!mkdir -p drive
!google-drive-ocamlfuse drive

點擊左側菜單,可以看到“文件”下方生成了一個“drive”文件夾,和雲盤中文件夾保持同步。
5. 安裝需要的工具(可以省略)。

其他操作

(1) colab中使用linux命令,前面需要加上"!",例如,創建文件夾:

!mkdir colab

(2) 切換工作目錄使用chdir函數

import os
os.chdir("/content/drive/Colab")

(3) 設置方便可用的快捷鍵。

打開“工具”-“鍵盤快捷鍵”進行設置。

(4) 左側菜單中間“代碼段”中,可用根據需要選擇常用代碼,例如加載drive中的數據,保存文件到本地系統。

(5)Colab最多連續使用12小哥,超過時間系統會強制停止,再次使用需重新配置。

下載TF-hub模型

因爲某種原因,國內無法訪問tf-hub,其中提供的很多模型也無法使用。如果直接在Colab中使用,可以按照官網指定代碼運行使用。如果想要下載到本地使用,需要在colab中運行以下代碼:

以下載通用句子編碼(universal-sentence-encoder model)爲例:

# Create a folder for the TF hub module.
$ mkdir /tmp/moduleA
# Download the module, and uncompress it to the destination folder. You might want to do this manually.
$ curl -L "https://tfhub.dev/google/universal-sentence-encoder/2?tf-hub-format=compressed" | tar -zxvC /tmp/moduleA
# Test to make sure it works.
$ python
> import tensorflow_hub as hub
> hub.Module("/tmp/moduleA")

其他模型和示例參考:https://github.com/tensorflow/hub/tree/master/examples”

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章