# Google Colab 基本教學 * **教學影片**: * ==[Google Colab Tutorial](https://youtu.be/5v41Scv_ZEM)== * **程式碼範例**: * colab:[Google Colab Tutorial](https://colab.research.google.com/github/ga642381/ML2021-Spring/blob/main/Colab/Google_Colab_Tutorial.ipynb) --- ## 簡介 (Introduction) Google Colaboratory,簡稱 Colab,是由 Google 提供的一項服務,允許使用者在瀏覽器中撰寫並執行 Python 程式碼。 Colab 的主要優點包括: * **無需設定 (Zero configuration required)**:許多常用的 Python 套件已經預先安裝好,使用者不需進行繁瑣的環境設定。 * **免費 GPU (Free access to GPUs)**:Colab 提供免費的圖形處理器 (Graphics Processing Unit, GPU) 資源,對於執行機器學習等計算密集型任務非常有幫助。 * **易於分享 (Easy sharing)**:Colab Notebook 可以輕鬆地與他人共享。 --- ## Code Block 與執行環境 在 Colab 中,輸入程式碼的區域稱為 Code Block (程式區塊/程式碼儲存格)。 * **Python 程式碼**:直接在 Code Block 中輸入的文字將被視為 Python 程式碼執行。 ```python import numpy import math print("Hello Colab") ``` * **Shell Script**:如果在指令前加上驚嘆號 `!`,則該 Code Block 中的內容會被視為 Shell Script (例如 Linux bash 指令) 來執行。 ```python !ls -l !pwd ``` 驚嘆號 `!` 的功能是開啟一個新的 Shell,執行其後的指令,然後終止該 Shell。 * **Magic Function**:以百分比符號 `%` 開頭的指令稱為 Magic Function。這類指令會直接影響與 Notebook 相關的程序。 * **例如**:要改變目前的工作目錄 (change directory),必須使用 `%cd`: ```python %cd /content/sample_data/ ``` * **重要**:由於 `!` 是開啟一個新的、短暫的 Shell 來執行命令,因此使用 `!cd` 無法永久改變目前 Notebook Session 的工作目錄。而 `%cd` (Magic Function) 則可以直接改變 Notebook Session 的工作目錄。`!` 和 `%` 後面能接的程式碼來源不同,兩者不可混用。 --- ## 變更執行階段 (Changing Runtime) 為了利用 Colab 提供的免費 GPU 資源,需要進行以下設定: 1. 點選頂部選單的「執行階段 (Runtime)」。 2. 選擇「變更執行階段類型 (Change Runtime Type)」。 3. 在「硬體加速器 (Hardware Accelerator)」下拉選單中選擇「GPU」。 4. 點擊「儲存 (Save)」。 **注意事項**: * 變更執行階段類型會重新啟動目前的 Colab Session,這意味著之前執行的變數和狀態將會遺失。因此,建議在**開始執行任何程式碼之前就設定好所需的執行階段類型**。 * 如果程式執行到一半才切換執行階段類型 (例如從 CPU 切換到 GPU),所有已執行的程式碼都需要重跑。 可以使用以下 Python 程式碼 (以 PyTorch 為例) 來確認 GPU 是否成功啟用: ```python= import torch if torch.cuda.is_available(): print("GPU is available.") print(f"GPU Name: {torch.cuda.get_device_name(0)}") else: print("GPU is not available.") # 輸出 True (或 GPU is available.) 即表示 GPU 模式已成功啟用。 ``` 在 Colab 中,右上角顯示 "connected" (已連線) 並成功執行上述確認程式碼,即代表 GPU 設定完成。 --- ## 執行 Code Block 要執行一個 Code Block,可以點擊該區塊左側的播放 (Play) 按鈕,或者使用快捷鍵 (如 Shift + Enter)。 **範例:從 Google Drive 下載檔案** 以下指令使用 `gdown` 工具從 Google Drive 下載一個具有特定檔案 ID 的檔案,並將其命名為 `Minori.jpg`。 ```python= # 下載檔案 ID 為 '1duQU7xqXRsOSPYeOR0zLiSA8g_LCFzoV' 的檔案,並命名為 Minori.jpg !gdown --id '1duQU7xqXRsOSPYeOR0zLiSA8g_LCFzoV' --output Minori.jpg # 列出目前工作目錄下的所有檔案 !ls ``` 執行後,可以看到 `Minori.jpg` 檔案出現在目前的工作目錄中。 --- ## 檔案結構 (File Structure) 與暫存檔案 * **查看檔案結構**:點擊 Colab 介面左側的「檔案 (Files)」圖示 (資料夾圖示),即可看到目前工作環境的檔案結構。 * **重新整理**:如果下載或操作檔案後未立即在檔案列表中看到變化,可以點擊檔案列表上方的「重新整理 (Refresh)」圖示。 * **檔案暫存特性**:直接下載到 Colab 執行環境中的檔案 (未掛載 Google Drive 的情況下) 是**暫時儲存**的。如果關閉瀏覽器分頁或終止 Colab Session,這些檔案將會消失。 * **下載檔案到本地電腦**:在檔案列表中對著想要下載的檔案點擊右鍵,選擇「下載 (Download)」,即可將檔案儲存到自己的電腦中。 --- ## 掛載 Google Drive (Mounting Google Drive) 為了永久儲存工作檔案,可以將自己的 Google Drive (雲端硬碟) 掛載到 Colab 環境中。 **掛載方法**: 1. **執行程式碼**:在一個 Code Block 中執行以下 Python 程式碼。 ```python= from google.colab import drive drive.mount('/content/drive') # force_remount=True 可用於強制重新掛載 # drive.mount('/content/drive', force_remount=True) ``` 2. **點擊圖示**:或者,點擊 Colab 介面左側「檔案 (Files)」窗格中的「掛載 Google Drive (Mount Drive)」圖示,系統會自動產生上述程式碼並提示執行。 **授權步驟**: 1. 執行掛載指令後,瀏覽器會開啟一個新的分頁要求你登入 Google 帳戶並授權 Colab 存取你的 Google Drive。 3. 登入並授權後,等待掛載 Google Drive 即可。 掛載成功後,通常會看到類似 "Mounted at /content/drive" 的訊息。此時,在左側的檔案結構中會出現一個名為 `drive` 的資料夾,其中包含 `MyDrive` 子資料夾,這就是你的 Google Drive 根目錄。之後儲存在 `MyDrive` 內的檔案都會同步到你的 Google Drive,不會因 Session 終止而消失。 > [!Important]注意:請確保你的 Google Drive 有足夠的儲存空間。 --- ## 在 Google Drive 中操作檔案 掛載 Google Drive 後,就可以像操作本地資料夾一樣對其進行讀寫。 1. **變更工作目錄到 Google Drive**: ```python # 切換到 Google Drive 的 MyDrive 資料夾 %cd /content/drive/MyDrive ``` 這樣,後續的檔案操作就會在你的 Google Drive 中進行。 2. **建立資料夾**: ```python # 在 MyDrive 中建立一個名為 ML_Practice 的資料夾 !mkdir ML_Practice ``` 3. **移動到新建立的資料夾**: ```python %cd ML_Practice/ ``` 4. **確認目前路徑**: ```python !pwd # 應輸出類似 /content/drive/MyDrive/ML_Practice 的路徑 ``` 5. **範例:在 Google Drive 中下載並儲存檔案**: ```python # 假設目前已 %cd 到 /content/drive/MyDrive/ML_Practice/ !gdown --id '1duQU7xqXRsOSPYeOR0zLiSA8g_LCFzoV' --output Minori_in_drive.jpg !ls ``` 執行後,`Minori_in_drive.jpg` 檔案就會被下載並永久儲存到你 Google Drive 的 `ML_Practice` 資料夾中。可以稍後在 Google Drive 網頁介面確認檔案是否存在。 --- ## Code Block 操作 Colab 提供了方便的 Code Block 管理功能: * **建立新的 Code Block**:點擊介面頂部工具欄的「+ Code (程式碼)」按鈕。 * **移動 Code Block**:將滑鼠懸停在 Code Block 上方,右側會出現上移 (Move cell up) 和下移 (Move cell down) 的箭頭按鈕。 * **刪除 Code Block**:同樣在 Code Block 右側,可以找到刪除 (Delete cell) 的垃圾桶圖示按鈕。 --- ## 儲存 Colab Notebook (Saving Colab) 儲存你的 Colab Notebook 非常重要,尤其是在提交作業時。 * **下載 `.ipynb` 檔案到本地**:點選頂部選單「檔案 (File)」->「下載 (Download)」->「下載 .ipynb (Download .ipynb)」。這會將整個 Notebook 以 `.ipynb` (IPython Notebook file) 格式儲存到你的電腦。 * **儲存副本到 Google Drive**:點選「檔案 (File)」->「在雲端硬碟中儲存副本 (Save a copy in Drive)」。這會在你的 Google Drive 中建立一個 Notebook 的副本。 --- ## 從 Google Drive 回復檔案 (Recovering Files in Google Drive) 由於 Colab 具有讀寫檔案的功能,如果不小心在 Colab 中操作覆蓋了 Google Drive 中的重要檔案,可以嘗試使用 Google Drive 的版本管理功能來回復。 1. 在 Google Drive 網頁介面中找到被覆蓋的檔案。 2. 對檔案點擊右鍵。 3. 選擇「管理版本 (Manage Versions)」。 4. 在彈出的視窗中,可以看到該檔案的歷史版本列表。 5. 找到需要的舊版本,可以選擇下載或還原。 --- ## 常用的 Linux 指令 (Useful Linux Commands in Colab) 以下是一些在 Colab 中搭配 `!` 或 `%` 常用的 Linux 指令: * `!ls`:列出目前資料夾內的檔案和子資料夾。 * `!ls -l`:以長格式列出內容,包含詳細資訊 (權限、擁有者、大小、修改日期等)。 * `!pwd`:顯示目前的工作目錄路徑 (print working directory)。 * `!mkdir <dirname>`:建立一個名為 `<dirname>` 的新資料夾 (make directory)。 * `%cd <dirname>`:移動到名為 `<dirname>` 的資料夾 (change directory)。**注意:在 Colab 中改變工作目錄推薦使用 `%cd` 而非 `!cd`**。 * `!gdown --id <file_id> --output <filename>`:從 Google Drive 下載指定 ID 的檔案並儲存為 `<filename>`。 * `!wget <url>`:從指定的網址 `<url>` 下載檔案。 * `!python <python_file.py>`:執行一個 Python 腳本檔案。 記得,除了 `%cd` 這類 Magic Function 外,大部分 Shell 指令在 Colab 中執行時,前面都需要加上驚嘆號 `!`。 --- 回[主目錄](https://hackmd.io/@Jaychao2099/aitothemoon)
×
Sign in
Email
Password
Forgot password
or
Sign in via Google
Sign in via Facebook
Sign in via X(Twitter)
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
Continue with a different method
New to HackMD?
Sign up
By signing in, you agree to our
terms of service
.