My personal notes for Google Colab notebooks

Basic Shortcuts

Executing:
ctrl+enter: execute current cell
shift+enter: execute current cell and go to cell below
alt+enter: execute current cell and create a new empty cell below

Editing:
ctrl+space: autocomplete
ctrl + /: comment current line
ctrl+m, y: convert to code cell
ctrl+m, m: convert to text cell
ctrl+m, l: toggle line numbers
ctrl+m, z: undo
ctrl+shift+y: redo
ctrl+s: save

Manipulating Cells:
ctrl+m, a: insert cell above
ctrl+m, b: insert cell below
ctrl+m, d: delete cell

Navigating:
ctrl+m, p: go to previous cell
ctrl+m, n: go to next cell

Navigating (Vim style):
esc: get out of editing mode
j (when not in editing mode): go to previous cell
k (when not in editing mode): go to next cell
enter: go into editing mode

Running with GPU

Colab notebooks do not use GPU by default. You have to turn it on manually if you need GPU computing power (e.g. for image processing)

Menu > Runtime > Change runtime type > set Hardware Accelerator dropdown to “GPU”

Running System Commands

You can run system commands in the cells by placing an exclamation mark (!) before the line:

Example 1: Install Python packages

!pip install tensorflow

Example 2: Download zip files from a URL

!wget --no-check-certificate http://the.download.url -O /tmp/myfile.zip

Working With Files

Unzipping files

import zipfile
with zipfile.ZipFile('/tmp/myfile.zip') as zf:
    zf.extractall('/tmp')

You can then find the unzipped files in the Files sidebar on the left

Selecting local files and uploading them

from google.colab import files
uploaded_files = files.upload()

A “Choose Files” button will appear. Clicking on it will bring up a file selection dialog. After selecting files, the upload process will begin. The uploaded files can be found in the Files sidebar on the left, under the “/content” directory.

You can then do what you need to do with those files by iterating through them:

for uploaded_file in uploaded_files:
    uploaded_file_path = '/content/' + uploaded_file
    # do some stuff with uploaded_file_path...

Downloading files

from google.colab import files
files.download('/path/to/file')

A lot more possibilities are demonstrated in this excellent colab notebook by Google: https://colab.research.google.com/notebooks/io.ipynb

Terminate Kernel

Run this to terminate the kernel to free up resources:

import os
import signal
os.kill(os.getpid(), signal.SIGKILL)