Back to Tutorials
Deep Learning
Intermediate

Transfer Learning: Borrow What a Network Already Sees

Teach a computer eight cat and dog breeds from a handful of photos. Compare a model that sees pixels with one that borrows a pretrained network’s features, and train both in your browser.

10 minInteractive: drag, click and try things as you read


Teaching a computer to tell a Siamese cat from a Birman sounds like a job for thousands of labelled photos and a powerful computer. It isn’t, if you borrow. Transfer learning takes a network already trained on millions of photos, keeps everything it learned about fur, ears, eyes and shapes, and trains only a small final layer on your own photos. Here you’ll do exactly that, in your browser, for eight cat and dog breeds, and compare it with a model that learns from the pixels alone. Reuse a pretrained network’s features, and a few dozen photos per class can be enough.

What a pretrained network gives you#

ResNet18 is a convolutional network with 11.7 million parameters, trained on ImageNet: 1.28 million photos sorted into 1,000 categories, from goldfish to garbage trucks. Its last layer picks one of those 1,000 categories. The layer just before it turns any photo into 512 numbers, its features. To get there, its earlier layers learned to spot edges, then textures, then parts such as ears and noses, so those 512 numbers describe what’s in the picture. Remove the last layer and you have a describer for any photo, including ones it never saw.

The alternative is to give a model the photo itself. Here that’s each photo shrunk to 12×12 pixels: 432 numbers, the red, green and blue of every pixel. The photos are 8 breeds from the Oxford-IIIT Pet dataset, four cats that come in confusable pairs and four dogs: 24 photos of each to learn from and 16 of each to test on.

Predict first

For a test photo of a pug, find the 5 training photos whose pixels are closest to it. How many are pugs?

Try it

Pick a test photo

Pug

What the pixel model gets

Closest by pixels · 0 of 5 are Pugs

British ShorthairRussian BlueRussian BlueBritish ShorthairRussian Blue

Closest by ResNet18 features · 5 of 5 are Pugs

PugPugPugPugPug

Comparing every test photo with every training photo…

Photos from the Oxford-IIIT Pet dataset (Parkhi et al. 2012, CC BY-SA 4.0). Each photo’s 512 features were computed offline with ResNet18 pretrained on ImageNet. Your browser finds the closest training photos: by the angle between feature vectors (cosine similarity), or by the straight-line distance between the 12×12 pixel versions.

Across all 128 test photos, the single closest training photo by features is the same breed 112 times. By pixels it’s 24 times, barely better than the 16 you’d expect by picking at random. Pixels record which colour is where, so a photo is close to others with the same lighting and background. Features record what’s in the picture, so a pug is close to other pugs, facing any way, on any sofa. Pixels describe colours and places; pretrained features describe what’s in the picture.

The recipe: freeze the pretrained network, so its parameters never change, and train a new final layer that maps its 512 features to your classes. That layer is a small classifier, the same kind as for text: one weight per feature per breed, learned with a few hundred steps of gradient descent. In the figure your browser trains it twice, once on features and once on pixels, with as many photos per breed as you choose, and tests both on the same 128 photos.

Predict first

With one training photo per breed, eight photos in all, how does the classifier on features do?

Try it
Trained on pixels (12×12)training…
Trained on ResNet18 featurestraining…

Trained offline on all 24 photos per breed, for comparison:

A small network trained from scratch30.5%
ResNet18 trained from scratch18.8%
ResNet18 fine-tuned, learning rate 0.00185.2%
ResNet18 fine-tuned, learning rate 0.0164.8%

The dark tick marks a blind guess: 1 in 8, 12.5%.

Training…

Training two classifiers in your browser…

Both live classifiers are trained in your browser each time you change a setting. The grey bars were trained offline on the same 24 photos per breed and tested on the same photos: a small network with four convolutional layers and ResNet18 trained from random weights (60 and 8 passes over the photos), and the pretrained ResNet18 with every layer trained further (8 passes) at two learning rates.

With 24 photos per breed the features model gets 88.3% right; the same classifier on pixels, 34.4%. Its mistakes are the ones a person might make: Siamese taken for Birman, both pale cats with dark faces, and British Shorthairs and Russian Blues, both grey. Now look at the grey bars. A small network trained from scratch on the same photos managed 30%, and ResNet18 itself, trained from random weights, 19%: with 192 photos, a network can’t learn to see. The pretrained one learned to see from 1.28 million. With little data, borrowing a network’s features beats learning to see from scratch by a mile.

Fine-tuning: gently, or not at all#

The next step is fine-tuning: after the new layer, let the whole network keep learning from your photos, so its features adjust to your classes. Two of the grey bars do that. With a learning rate of 0.001, it reached 85.2% after 8 passes; training only its last block with the new layer also gave 85.2%. Neither beat the frozen network with a new last layer, which got 88.3%. With a learning rate of 0.01, it got 84% after one pass and then fell, to 64.8% after eight: big updates on 192 photos overwrite what it learned from 1.28 million.

  • Freeze first. A frozen network with a new last layer is quick, hard to break, and often enough.
  • Fine-tune with a small learning rate, and keep it only if it beats the frozen version on photos it hasn’t trained on. It tends to pay off with more photos, or photos unlike everyday ones, such as X-rays or satellite images.
  • Prepare photos the way the network was trained. Same size, same normalisation: torchvision gives you these as weights.transforms().
  • Try a stronger backbone before collecting more data. ResNet18 is small and old. Newer pretrained networks generally give better features for the same few photos.

In code#

The frozen recipe with PyTorch and scikit-learn, free and local (pip install torch torchvision scikit-learn pandas huggingface_hub). It downloads the dataset (about 800 MB) and picks its own 24 and 16 photos per breed, so the numbers differ a little from the figure’s:

import io
import numpy as np, pandas as pd, torch, torchvision
from PIL import Image
from sklearn.linear_model import LogisticRegression

breeds = {32: "Siamese", 6: "Birman", 27: "Russian Blue", 9: "British Shorthair", 4: "Beagle", 3: "Basset Hound", 29: "Samoyed", 25: "Pug"}
url = "hf://datasets/timm/oxford-iiit-pet/data/{}-00000-of-00001.parquet"

def load(split, n):
    df = pd.read_parquet(url.format(split))
    df = df[df.label.isin(breeds)].groupby("label").sample(n, random_state=0)
    return [Image.open(io.BytesIO(im["bytes"])).convert("RGB") for im in df.image], df.label.to_numpy()

train_imgs, y_train = load("train", 24)  # 24 photos per breed to learn from
test_imgs, y_test = load("test", 16)     # 16 per breed it has never seen

weights = torchvision.models.ResNet18_Weights.DEFAULT
net = torchvision.models.resnet18(weights=weights).eval()
net.fc = torch.nn.Identity()  # drop ImageNet's 1,000-way layer: out come 512 features
prep = weights.transforms()   # the resizing and normalising it was trained with

@torch.no_grad()
def features(imgs):
    return net(torch.stack([prep(im) for im in imgs])).numpy()

def pixels(imgs):
    return np.stack([np.asarray(im.resize((12, 12))).reshape(-1) / 255 for im in imgs])

for name, describe in (("pixels", pixels), ("ResNet18 features", features)):
    clf = LogisticRegression(max_iter=5000).fit(describe(train_imgs), y_train)
    print(f"{name:>17}: {clf.score(describe(test_imgs), y_test):.0%} of {len(y_test)} test photos right")
#            pixels: 24% of 128 test photos right
# ResNet18 features: 92% of 128 test photos right

The ResNet18 weights download the first time (45 MB) and the whole thing runs on a laptop CPU in a minute or two. To fine-tune instead, replace net.fc with torch.nn.Linear(512, 8), leave the parameters trainable, and train with a small learning rate.

What to remember

  • A pretrained network turns any photo into features that describe what’s in it; pixels only say which colour is where.
  • With 24 photos per breed, a new last layer on ResNet18’s features got 88% of test photos right; the same classifier on pixels 34%, and networks trained from scratch 19–30%.
  • Freeze the network and train a new last layer first; fine-tune only gently, and keep it only if it beats the frozen version on held-out photos.

Keep going

Sign in to save your place and keep a learning streak. Free, with Google.