[譯] Google Colab 免費 GPU 使用教程

leeyang-tju發表於2018-12-04

Google Colab 免費 GPU 使用教程

現在你可以使用 Google Colaboratory(帶有免費的 Tesla K80 GPU)使用 KerasTensorflowPyTorch 來開發深度學習的程式了。

[譯] Google Colab 免費 GPU 使用教程

大家好!我將向大家展示如何使用 Google 面向 AI 開發者的免費雲服務 —— Google Colab。在 Colab 上,你可以使用免費的 GPU 來開發深度學習應用程式。

感謝 KDnuggets!

我很高興地宣佈,這篇博文在 2018 年 2 月被選為 KDnuggets 的銀質博文!文章內容可以在 KDnuggets 看到。

[譯] Google Colab 免費 GPU 使用教程

Google Colab 是什麼?

Google Colab 是一個免費的雲服務,現在它還支援免費的 GPU!

你可以:

  • 提高你的 Python 語言的編碼技能。
  • 使用 KerasTensorFlowPyTorchOpenCV 等流行庫開發深度學習應用程式。

Colab 與其它免費的雲服務最重要的區別在於:Colab 提供完全免費的 GPU。

關於這項服務的詳細資訊可以在 faq 頁面上找到。

準備好使用 Google Colab

在 Google Drive 上建立資料夾

[譯] Google Colab 免費 GPU 使用教程

由於 Colab 是在 Google Drive 上工作的,所以我們需要首先指定工作資料夾。我在 Google Drive 上建立了一個名為 “app” 的資料夾。當然,你可以使用不同的名稱或選擇預設的 Colab Notebooks 資料夾,而不是 app 資料夾

[譯] Google Colab 免費 GPU 使用教程

我建立了一個空的 “app” 資料夾

建立新的 Colab 筆記(Notebook)

通過 右鍵點選 > More > Colaboratory 步驟建立一個新的筆記。

[譯] Google Colab 免費 GPU 使用教程

右鍵點選 > More > Colaboratory

通過點選檔名來重新命名筆記

[譯] Google Colab 免費 GPU 使用教程

設定免費的 GPU

通過很簡單的步驟就可以將預設硬體從 CPU 更改為 GPU,或者反過來。依照下面的步驟 Edit > Notebook settings 或者進入 Runtime > Change runtime type,然後選擇 GPU 作為 Hardware accelerator(硬體加速器)

[譯] Google Colab 免費 GPU 使用教程

使用 Google Colab 執行基本的 Python 程式碼

現在我們可以開始使用 Google Colab 了。

[譯] Google Colab 免費 GPU 使用教程

我會執行一些 Python Numpy 教程關於基本資料型別的程式碼。

[譯] Google Colab 免費 GPU 使用教程

可以正常執行!:) 如果你對在 AI 中最流行的程式語言 Python 還不是很瞭解,我推薦你去學習這個簡明教程。

在 Google Colab 中執行或匯入 .py 檔案

首先執行這些程式碼,以便安裝一些必要的庫並執行授權。

from google.colab import drive
drive.mount('/content/drive/')
複製程式碼

執行上面的程式碼,會得到如下的結果:

[譯] Google Colab 免費 GPU 使用教程

點選 這個連結,複製驗證程式碼並貼上到下面的文字框中。

完成授權流程後,應該可以看到:

[譯] Google Colab 免費 GPU 使用教程

現在可以通過下面的命令訪問你的 Google Drive 了:

!ls "/content/drive/My Drive/"
複製程式碼

安裝 Keras

!pip install -q keras
複製程式碼

上傳檔案 mnist_cnn.py 到你的 Google Driveapp 資料夾中。

[譯] Google Colab 免費 GPU 使用教程

mnist_cnn.py 檔案內容

MNIST 資料集上執行下面的程式碼來訓練一個簡單的卷積網路(convnet)。

!python3 "/content/drive/My Drive/app/mnist_cnn.py"
複製程式碼

[譯] Google Colab 免費 GPU 使用教程

從結果可以看到,每輪次(epoch)執行只用了 11 秒

下載 Titanic 資料集(.csv 檔案)並顯示檔案的前 5 行內容

如果你想從一個 url 中下載 .csv 檔案到 “app” 資料夾,只需執行下面的命令:

!wget raw.githubusercontent.com/vincentarel… -P "/content/drive/My Drive/app"

不使用 wget 方法,你可以直接將自己的 .csv 檔案上傳到 “app” 資料夾中。

[譯] Google Colab 免費 GPU 使用教程

讀取 “app” 資料夾中的 .csv 檔案並顯示前 5 行的內容

import pandas as pd
titanic = pd.read_csv(“/content/drive/My Drive/app/Titanic.csv”)
titanic.head(5)
複製程式碼

[譯] Google Colab 免費 GPU 使用教程

克隆 GitHub 倉庫到 Google Colab

使用 Git 可以很輕鬆克隆 GitHub 倉庫。

步驟 1: 找到 GitHub 倉庫並獲取 “Git” 連結

找到所需的 GitHub 倉庫。

比如: github.com/wxs/keras-m…

點選 Clone or download(克隆或下載) > Copy the link(複製連結)!

[譯] Google Colab 免費 GPU 使用教程

2. 使用 Git 克隆

執行以下命令即可:

!git clone github.com/wxs/keras-m…

[譯] Google Colab 免費 GPU 使用教程

3. 開啟 Google Drive 中對應的資料夾

當然,Google Drive 中對應的資料夾與 GitHub 倉庫名是相同的。

[譯] Google Colab 免費 GPU 使用教程

4. 開啟筆記

右鍵點選 > Open With > Colaboratory

[譯] Google Colab 免費 GPU 使用教程

5. 執行

現在你可以在 Google Colab 中執行 GitHub 倉庫程式碼了。

[譯] Google Colab 免費 GPU 使用教程

一些有用的提示

1. 如何安裝第三方庫?

Keras

!pip install -q keras
import keras
複製程式碼

PyTorch

from os import path
from wheel.pep425tags import get_abbr_impl, get_impl_ver, get_abi_tag
platform = '{}{}-{}'.format(get_abbr_impl(), get_impl_ver(), get_abi_tag())
accelerator = 'cu80' if path.exists('/opt/bin/nvidia-smi') else 'cpu'
複製程式碼

!pip install -q download.pytorch.org/whl/{accele… torchvision
import torch

或者試試這個:

!pip3 install torch torchvision

MxNet

!apt install libnvrtc8.0
!pip install mxnet-cu80
import mxnet as mx
複製程式碼

OpenCV

!apt-get -qq install -y libsm6 libxext6 && pip install -q -U opencv-python
import cv2
複製程式碼

XGBoost

!pip install -q xgboost==0.4a30
import xgboost
複製程式碼

GraphViz

!apt-get -qq install -y graphviz && pip install -q pydot
import pydot
複製程式碼

7zip 閱讀器

!apt-get -qq install -y libarchive-dev && pip install -q -U libarchive
import libarchive
複製程式碼

其它庫

!pip install 或者 !apt-get install 安裝其它庫。

2. GPU 是否正常工作?

要檢視是否在 Colab 中正確使用了 GPU,可以執行下面的程式碼進行交叉驗證:

import tensorflow as tf
tf.test.gpu_device_name()
複製程式碼

[譯] Google Colab 免費 GPU 使用教程

3. 我使用的是哪一個 GPU?

from tensorflow.python.client import device_lib
device_lib.list_local_devices()
複製程式碼

目前, Colab 只提供了 Tesla K80

[譯] Google Colab 免費 GPU 使用教程

4. 輸出 RAM 資訊?

!cat /proc/meminfo
複製程式碼

[譯] Google Colab 免費 GPU 使用教程

5. 輸出 CPU 資訊?

!cat /proc/cpuinfo
複製程式碼

[譯] Google Colab 免費 GPU 使用教程

6. 改變工作資料夾

一般,當你執行下面的命令:

!ls
複製程式碼

你會看到 datalab 和 drive 資料夾。

因此,在定義每一個檔名時,需要在前面新增 drive/app

要解決這個問題,更改工作目錄即可。(在本教程中,我將其更改為 app 資料夾)可以使用下面的程式碼:

import os
os.chdir("drive/app") 
# 譯者注:掛載網盤目錄後,前面沒有切換過目錄,這裡應該輸入
# os.chdir("drive/My Drive/app")
複製程式碼

執行上述程式碼後,如果你再次執行

!ls
複製程式碼

你會看到 app 資料夾的內容,不需要再一直新增 drive/app 了。

7. “No backend with GPU available” 錯誤解決方案

如果你遇到這個錯誤:

Failed to assign a backend No backend with GPU available. Would you like to use a runtime with no accelerator? #指定後端失敗。沒有可用的 GPU 後端。需要使用沒有加速器的執行時嗎?

可以稍後再試一次。有許多人現在都在使用 GPU,當所有 GPU 都在使用時,就會出現這種錯誤資訊。

參考這裡

8. 如何清空所有單元行的執行輸出?

可以依次點選 Tools>>Command Palette>>Clear All Outputs

9. “apt-key output should not be parsed (stdout is not a terminal)” 警告

如果你遇到這個警告:

Warning: apt-key output should not be parsed (stdout is not a terminal) #警告:apt-key 輸出無法被解析(當前 stdout 不是終端)
複製程式碼

這意味著你已經完成了授權。只需要掛載 Google Drive 即可:

!mkdir -p drive
!google-drive-ocamlfuse drive
複製程式碼

10. 如何在 Google Colab 中使用 Tensorboard?

我推薦參考這個倉庫程式碼:

github.com/mixuala/col…

11. 如何重啟 Google Colab?

要重啟(或重置)你開啟的虛擬機器器,執行下面的命令即可:

!kill -9 -1
複製程式碼

12. 如何向 Google Colab 中新增表單(Form)?

為了避免每次在程式碼中更改超引數,你可以簡單地向 Google Colab 中新增表單。

[譯] Google Colab 免費 GPU 使用教程

例如,我新增了一個包含有 learning_rate(學習率) 變數和 optimizer(優化器) 字串的表單。

[譯] Google Colab 免費 GPU 使用教程

13. 如何檢視方法的引數?

在 TensorFlow、Keras 等框架中檢視方法的引數,可以在方法名稱後面新增問號識別符號(?)

[譯] Google Colab 免費 GPU 使用教程

這樣不需要點選 TensorFlow 的網站就可以看到原始文件。

[譯] Google Colab 免費 GPU 使用教程

14. 如何將大檔案從 Colab 傳送到 Google Drive?

# 需要傳送哪個檔案?
file_name = "REPO.tar"

from googleapiclient.http import MediaFileUpload
from googleapiclient.discovery import build

auth.authenticate_user()
drive_service = build('drive', 'v3')

def save_file_to_drive(name, path):
  file_metadata = {'name': name, 'mimeType': 'application/octet-stream'}
  media = MediaFileUpload(path, mimetype='application/octet-stream', resumable=True)
  created = drive_service.files().create(body=file_metadata, media_body=media, fields='id').execute()
  
  return created

save_file_to_drive(file_name, file_name)
複製程式碼

15. 如何在 Google Colab 中執行 Tensorboard?

如果你想在 Google Colab 中執行 Tensorboard,執行下面的程式碼。

# 你可以更改目錄名
LOG_DIR = 'tb_logs'

!wget https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-linux-amd64.zip
!unzip ngrok-stable-linux-amd64.zip

import os
if not os.path.exists(LOG_DIR):
  os.makedirs(LOG_DIR)
  
get_ipython().system_raw(
    'tensorboard --logdir {} --host 0.0.0.0 --port 6006 &'
    .format(LOG_DIR))

get_ipython().system_raw('./ngrok http 6006 &')

!curl -s http://localhost:4040/api/tunnels | python3 -c \
    "import sys, json; print(json.load(sys.stdin)['tunnels'][0]['public_url'])"
複製程式碼

你可以通過建立 ngrok.io 連結來追蹤 Tensorboard 日誌。你可以在輸出的最後找到這個 URL 連結。

注意,你的 Tensorboard 日誌將儲存到 tb_logs 目錄。當然,你可以更改這個目錄名。

[譯] Google Colab 免費 GPU 使用教程

之後,我們就可以看到 Tensorboard 了!執行下面的程式碼,可以通過 ngrok URL 連結來追蹤 Tensorboard 日誌。

from __future__ import print_function
import keras
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras import backend as K
from keras.callbacks import TensorBoard

batch_size = 128
num_classes = 10
epochs = 12

# 輸入影象維度
img_rows, img_cols = 28, 28

# the data, shuffled and split between train and test sets
(x_train, y_train), (x_test, y_test) = mnist.load_data()

if K.image_data_format() == 'channels_first':
    x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)
    x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)
    input_shape = (1, img_rows, img_cols)
else:
    x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)
    x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)
    input_shape = (img_rows, img_cols, 1)

x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255
print('x_train shape:', x_train.shape)
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')

# 將類別向量轉換成二分類矩陣
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)

model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3),
                 activation='relu',
                 input_shape=input_shape))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(num_classes, activation='softmax'))

model.compile(loss=keras.losses.categorical_crossentropy,
              optimizer=keras.optimizers.Adadelta(),
              metrics=['accuracy'])


tbCallBack = TensorBoard(log_dir=LOG_DIR, 
                         histogram_freq=1,
                         write_graph=True,
                         write_grads=True,
                         batch_size=batch_size,
                         write_images=True)

model.fit(x_train, y_train,
          batch_size=batch_size,
          epochs=epochs,
          verbose=1,
          validation_data=(x_test, y_test),
          callbacks=[tbCallBack])
score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
複製程式碼

Tensorboard :)

[譯] Google Colab 免費 GPU 使用教程

總結

我認為 Colab 會給全世界的深度學習和 AI 研究帶來新的氣息。

如果你發現了這篇文章很有幫助,那麼請給它一些掌聲 ?,並與他人分享,這將會非常有意義。歡迎在下面留言。

你可以在 Twitter 上找到我。

最後請注意

英文原文會持續跟進更新,如有需要請移步英文原文

如果發現譯文存在錯誤或其他需要改進的地方,歡迎到 掘金翻譯計劃 對譯文進行修改並 PR,也可獲得相應獎勵積分。文章開頭的 本文永久連結 即為本文在 GitHub 上的 MarkDown 連結。


掘金翻譯計劃 是一個翻譯優質網際網路技術文章的社群,文章來源為 掘金 上的英文分享文章。內容覆蓋 AndroidiOS前端後端區塊鏈產品設計人工智慧等領域,想要檢視更多優質譯文請持續關注 掘金翻譯計劃官方微博知乎專欄

相關文章