1 Colaboratory 介紹
Colaboratory 是一個 Google 研究項目,旨在幫助傳播機器學習培訓和研究成果。它是一個 Jupyter 筆記本環境,不需要進行任何設置就可以使用,並且完全在雲端運行。
2 搭建 Colaboratory
打開谷歌,使用郵箱登陸你的 Google 賬號。(沒有帳號的使用郵箱注冊一個就行)

登錄 Google 賬號之后,在頁面右上角的 Google 應用里就可進入雲端硬盤里

進入 Google 雲端硬盤之后,需要關聯 Colaboratory。點擊我的雲端硬盤 -> 更多 -> 關聯更多應用。然后,搜索並找到 Colaboratory,然后關聯。(我已經關聯了 Colaboratory,所以展示的已經存在Colaboratory)


3 使用 Colaboratory
3.1 准備
關聯 Colaboratory 之后,新建文件夾(以 app 為例)。

進入 app 文件夾,空白處右鍵點擊更多 -> Colaboratory,即可創建 Jupyter Notebook。

通過點擊文件名實現重命名,例如重命名為 test.ipynb。

配置 Colaboratory,這一步非常重要也是非常強大的。點擊修改 -> 筆記本設置。

選擇使用 Python 2 還是 Python 3。更重要的,可以選擇使用 GPU 硬件加速。設置完畢后點擊保存。

查看GPU是否在colab中
import tensorflow as tf
tf.test.gpu_device_name()
如果結果為空,則不能使用GPU;如果結果為/device:GPU:0,則可以使用GPU。
查看顯卡內存使用上限
from tensorflow.python.client import device_lib
device_lib.list_local_devices()
3.2 運行基本代碼


3.3 運行.py文件
先運行下面這些代碼,來安裝必要的庫、執行授權。
!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}
運行的時候應該會看到下圖所示的結果,看見那個鏈接之后,點擊它,復制驗證碼並粘貼到文本框里。

授權完成后,就可以掛載Google Drive了!
!mkdir -p drive
!google-drive-ocamlfuse drive
注:這個時候輸入!ls
可能看不到根目錄drive,找不到drive就找不到我們雲盤的文件!解決辦法是,鍵入下邊的代碼:
from google.colab import drive
drive.mount('/content/drive/')
點擊出現的鏈接,在鏈接中復制驗證碼,在鏈接下方輸入驗證,顯示Mounted at /content/drive/即為成功。
將想要執行的mnist_cnn.py文件上傳到位於Google雲端硬盤上的app文件夾。然后使用cd
切換到app文件夾下,鍵入如下命令。
!python3 mnist_cnn.py
對於將代碼或者數據集文件傳到google雲盤上,建議安裝Google備份與同步軟件!
4 補充
安裝Keras:
!pip install -q keras
import keras
安裝PyTorch:
!pip install -q http://download.pytorch.org/whl/cu75/torch-0.2.0.post3-cp27-cp27mu-manylinux1_x86_64.whl torchvision
import torch
安裝OpenCV:
!apt-get -qq install -y libsm6 libxext6 && pip install -q -U opencv-python
import cv2
安裝其他庫:
用!pip install或者!apt-get install命令。