Useful recipes for your general colab workflow (not restricted to fastai).

Open In Colab

Check you have a gpu

!nvidia-smi

Install required dependencies

For a stable version:

!pip install -q fastai2

For a bleeding edge install:

!pip install -q git+git://github.com/fastai/fastcore.git
!pip install -q git+git://github.com/fastai/fastai2.git

If you are often switching from local to colab:

try:
  import fastai2
except ImportError:
  !pip install -q git+git://github.com/fastai/fastcore.git
  !pip install -q git+git://github.com/fastai/fastai2.git

Required imports

We are just using Path from fastai here, if you don't want to install fastai you can instead do from pathlib import Path.

from fastai2.basics import *

Connect to drive

Connects to your google drive and mounts it as a local folder.
The mounted folder supports any operations that a local folder supports.

from google.colab import drive
drive.mount('/content/gdrive', force_remount=True)
root_dir = Path('/content/gdrive/My Drive/')

If you are constantly switching between colab and your local machine:

try:
  from google.colab import drive
  drive.mount('/content/gdrive', force_remount=True)
  root_dir = Path('/content/gdrive/My Drive/dl')
except ImportError:
  root_dir = Path.home()/'dl'
root_dir.mkdir(exist_ok=True)

Prevent colab from disconnecting

Keep colab connected by repeatedly clicking on connect button.
Copy and paste the snippet on your browser console (ctrl+shift+i for Windows/Linux, command+option+i for MacOS)

function ClickConnect(){
    console.log("Clicked on connect button"); 
    document.querySelector("colab-connect-button").click()
}
setInterval(ClickConnect,60000)

Upload files

Colab UI can be buggy, use this for uploading files.

from google.colab import files
files.upload()

Download stuff

If you have a direct link to the download, you can generally use wget to download it.

!wget http://images.cocodataset.org/zips/unlabeled2017.zip -P data