Skip to content

MLDay 38 of 50Deep Learning

Transfer Learning

8 min read

You have 500 labelled photos of clothes, which is too few to train a good image model from scratch. Someone else has already trained a network on a huge photo collection, and its layers know how to find edges, textures and shapes. Borrow those layers and train only a small new part.

The idea

A pretrained network has weights that were already learned on another task. MobileNetV3-Small, a small CNN that ships with torchvision, was trained on ImageNet: labelled photos in 1,000 categories, from goldfish to garbage trucks. It has two parts:

  • the backbone: the conv layers that turn an image into 576 numbers, its features;
  • the head: the last layers, which turn those features into one score per class.

Transfer learning keeps the backbone and swaps the head. You freeze the backbone, which means training can't change its weights. Then you add a new head with 10 outputs, one per clothing class, and train only that. The head has few weights to learn, and the features it reads are already good.

The backbone expects images like the ones it learned from: 3 colour channels, 224 × 224 pixels, and each channel shifted and scaled by ImageNet's average and spread. So a gray 28 × 28 image is copied into 3 channels and enlarged first.

Frozen layers never change, so an image's features never change either. Compute them once, store them, and train the head on the stored features.

A tiny example

Take a small pretrained network whose backbone has two layers and outputs 4 features. Each class score in a head is a weighted sum of the 4 features plus a bias, so it needs 4 + 1 = 5 parameters.

Part Parameters During training
backbone layer 1 300 frozen
backbone layer 2 600 frozen
old head, 1,000 classes 1,000 × 5 = 5,000 removed
new head, 3 classes 3 × 5 = 15 trained

Before the swap, training would adjust all 5,900 parameters. After it, training adjusts 15 of 915, about 1.6%.

The formula

A new linear head has one weight per feature, plus a bias, for each class:

Phead=(d+1) kP_{\text{head}} = (d + 1)\,k
Symbol Meaning
PheadP_{\text{head}} the head's parameters, the only trainable ones after freezing
dd features per image, from the backbone
kk classes to predict

Worked, for MobileNetV3-Small on 10 clothing classes: (576+1)×10=5,770(576 + 1) \times 10 = 5{,}770. That's 5,770 trainable of 932,778, or 0.62%. Before freezing, all 2,542,856 were trainable. The old ImageNet head alone held 1,615,848 of them, more than the whole backbone.

Try it

Freeze MobileNetV3-Small, train a new head

A frozen layer keeps its pretrained weights: training doesn't change them. Freeze the feature layers and leave only the last layer (the head) trainable, then compare the counts.

  • 464
  • 10,024
  • 128,264
  • 51,768
  • 680,040
  • 56,448
  • 5,770

trainable 932,778 (100%)frozen 0total 932,778

These are the real counts: a block is a small group of conv layers in the backbone. Everything starts trainable, 932,778 parameters. Click Freeze all but the last layer, and only the head's 5,770 stay trainable: 0.62%, which the widget rounds to 1%. Then untick Freeze blocks 9–11: the share jumps to 74%, because those three blocks hold most of the backbone's parameters.

In code

torchvision downloads the pretrained weights (about 10 MB) the first time and caches them. Freezing is one flag per parameter, requires_grad = False, and the new head replaces net.classifier:

# script_id: day_038_transfer_learning/transfer
import torch
from torch import nn
import torchvision.models as models

weights = models.MobileNet_V3_Small_Weights.DEFAULT      # ImageNet weights: a one-time download
net = models.mobilenet_v3_small(weights=weights).eval()  # eval mode: BatchNorm and Dropout act as at prediction time


def count(model, trainable_only=False):
    return sum(p.numel() for p in model.parameters() if p.requires_grad or not trainable_only)


print(f"pretrained:        {count(net, trainable_only=True):,} trainable of {count(net):,}")
for p in net.parameters():
    p.requires_grad = False                              # freeze: training can't change these
torch.manual_seed(42)
net.classifier = nn.Linear(576, 10)                      # new head: 576 features -> 10 clothing classes
print(f"frozen + new head: {count(net, trainable_only=True):,} trainable of {count(net):,}")
pretrained:        2,542,856 trainable of 2,542,856
frozen + new head: 5,770 trainable of 932,778

Next, 500 training images (50 per class) from the Phase 4 split, and the 1,000 validation images. The weights come with their own preprocessing, weights.transforms(): resize, crop to 224 × 224 and normalize. T.RGB() copies the gray channel into 3 first.

# script_id: day_038_transfer_learning/transfer
import os
from pathlib import Path

import numpy as np
import torchvision.transforms.v2 as T
from sklearn.model_selection import train_test_split

DATA_DIR = Path(os.environ.get("ML_DATA", "datasets"))
d = np.load(DATA_DIR / "fashion_mnist" / "fashion_mnist_slice.npz")
X_tr, X_va, y_tr, y_va = train_test_split(d["X_train"], d["y_train"], test_size=1000,
                                          stratify=d["y_train"], random_state=42)
X_tr, _, y_tr, _ = train_test_split(X_tr, y_tr, train_size=500, stratify=y_tr, random_state=42)
X_tr, y_tr = torch.from_numpy(X_tr).unsqueeze(1), torch.from_numpy(y_tr).long()  # 500 images, 50 per class
X_va, y_va = torch.from_numpy(X_va).unsqueeze(1), torch.from_numpy(y_va).long()  # 1,000 images
prep = T.Compose([T.RGB(), weights.transforms()])  # 3 channels, 224 x 224, ImageNet normalization


@torch.no_grad()
def features(X):                                   # the frozen layers, run once per image
    return torch.cat([net.avgpool(net.features(prep(b))).flatten(1) for b in X.split(100)])


f_tr, f_va = features(X_tr), features(X_va)
print("one 28 x 28 image in:", tuple(prep(X_tr[:1]).shape), " features out:", tuple(f_tr[:1].shape))
one 28 x 28 image in: (1, 3, 224, 224)  features out: (1, 576)

avgpool averages each of the backbone's last 576 feature maps into one number. Now train the head on the stored features with the loop from D32. For comparison, train D37's small CNN from scratch on the same 500 images (50 epochs for both: 500 images make each epoch only 8 batches):

# script_id: day_038_transfer_learning/transfer
def fit(model, X, y, X_val, y_val, epochs=50):           # D32's loop; returns validation accuracy
    loader = torch.utils.data.DataLoader(torch.utils.data.TensorDataset(X, y), batch_size=64,
                                         shuffle=True, generator=torch.Generator().manual_seed(42))
    opt, loss_fn = torch.optim.Adam(model.parameters(), lr=1e-3), nn.CrossEntropyLoss()
    for _ in range(epochs):
        for xb, yb in loader:
            opt.zero_grad()
            loss_fn(model(xb), yb).backward()
            opt.step()
    with torch.no_grad():
        return (model(X_val).argmax(dim=1) == y_val).float().mean().item()


head_acc = fit(net.classifier, f_tr, y_tr, f_va, y_va)   # trains only the new head, on the stored features
torch.manual_seed(42)
cnn = nn.Sequential(nn.Conv2d(1, 16, 3), nn.ReLU(), nn.MaxPool2d(2),  # D37's small CNN, from scratch
                    nn.Conv2d(16, 32, 3), nn.ReLU(), nn.MaxPool2d(2), nn.Flatten(), nn.Linear(800, 10))
cnn_acc = fit(cnn, X_tr.float() / 255, y_tr, X_va.float() / 255, y_va)
print(f"frozen MobileNet + new head: val acc {head_acc:.3f}  ({count(net.classifier):,} params trained)")
print(f"D37's CNN from scratch:      val acc {cnn_acc:.3f}  ({count(cnn):,} params trained)")
frozen MobileNet + new head: val acc 0.857  (5,770 params trained)
D37's CNN from scratch:      val acc 0.791  (12,810 params trained)

With 500 images, the borrowed features win by 6.6 points. They even beat D37's CNN trained on all 5,000 images, which reached 0.830. The whole script takes about a minute on a laptop CPU, mostly in the backbone.

Quick check

Quick check

1. A frozen backbone gives 576 features per image, and the new head predicts 5 classes. How many parameters does the head train?

2. Why are the gray 28 × 28 images turned into 3 × 224 × 224 before the backbone?

3. Why compute the features once instead of running the backbone every epoch?

Next

D39: Project 4: a Clothing-Image Classifier tunes a CNN on the full slice and digs into which clothes it confuses.

Data: Fashion-MNIST (Zalando Research), MIT licence; cite Xiao, H., Rasul, K. and Vollgraf, R. (2017), "Fashion-MNIST: a Novel Image Dataset for Benchmarking Machine Learning Algorithms", arXiv:1708.07747.

Next · Day 39 · 9 minProject 4: a Clothing-Image Classifier← Previous: Day 37 · Convolutional Networks and an Image Classifier
Not tapped yet