Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 4 of 6 · Lab · 30 min · revision 2

Lab: Transfer Learning with a Pretrained Backbone

Generate a small six-class image dataset, then compare three ways to train torchvision's ResNet-18 on identical splits with ten training images per class: from scratch, as a frozen feature extractor with a new head, and with gradual unfreezing of layer4 at a lower learning rate than the head; report accuracy, per-class recall, the most confused pairs, trainable parameters and training time.

Contentsand lesson path

What you will learn

  • Fine-tune a pretrained backbone (for example a torchvision ResNet or ViT) by feature extraction and gradual unfreezing, and compare accuracy and compute cost with training from scratch.

Prerequisites: Deep Learning Fundamentals

01. Goal and setup

A network trained on ImageNet, 1.3 million photos in 1,000 classes, has learned filters for edges, textures, shapes and object parts. Transfer learning reuses those filters for a new task. This lab compares three ways to train the same architecture, torchvision's ResNet-18 (see why residual networks train deeper), on the same small dataset: from random weights; as a feature extractor, where the pretrained layers are frozen and only a new final layer is trained; and with gradual unfreezing, where the last stage is then fine-tuned too at a lower learning rate.

The dataset is drawn by a script: six shape classes on random colours with clutter and noise, and only ten training images per class. Nothing about these images is in ImageNet, so any benefit comes from general visual features, not from having seen the data.

You need: Python 3.12, PyTorch 2 and torchvision 0.29 (CPU builds), NumPy and Pillow. The first run downloads the ResNet-18 ImageNet weights, a 44.7 MB file, into the torch cache (~/.cache/torch unless TORCH_HOME is set). Seeds are fixed, so accuracies should match the expected outputs on PyTorch 2.x; the last digit can differ on other CPUs or library versions. Training times depend on your machine and are shown as illustrative output.

Project layout at the end of the lab
transfer-lab/
├── make_data.py      step 1: draws the six-class dataset into data/
├── common.py         step 2: data loaders, the pretrained model, helpers
├── inspect_model.py  step 2: what the pretrained weights come with
├── features.py       step 3: frozen backbone, new head
├── unfreeze.py       step 4: unfreeze layer4 with a lower learning rate
├── scratch.py        step 5: the same network from random weights
├── report.py         step 6: accuracy, recall, confusions
├── times.py          step 6: trainable parameters and time
├── data/             train/, val/, test/ with one folder per class
└── runs/             predictions and timings of each step
Terminal
mkdir transfer-lab && cd transfer-lab
python3.12 -m venv .venv
source .venv/bin/activate      # Windows: .venv\Scripts\activate
python -m pip install "torch==2.15.*" "torchvision==0.29.*" \
    --index-url https://download.pytorch.org/whl/cpu
python -m pip install "numpy==2.*" "pillow==13.*"

02. Step 1: Draw a small dataset

make_data.py draws 112 × 112 RGB images of six shapes: circle, cross, ring, square, star and triangle. Each image gets a random background colour, six random lines as clutter, a shape of random colour, size, position and rotation, and pixel noise. The files are written in the layout that torchvision.datasets.ImageFolder expects, one folder per class, so the same code works for your own photos. The split is fixed at 10 training, 10 validation and 30 test images per class.

Python · make_data.py
import math
from pathlib import Path

import numpy as np
from PIL import Image, ImageDraw

CLASSES = ["circle", "cross", "ring", "square", "star", "triangle"]
SPLITS = {"train": 10, "val": 10, "test": 30}      # images per class
SIZE = 112


def polygon(cx, cy, r, n, angle, inner=None):
    pts = []
    for i in range(n * (2 if inner else 1)):
        rad = r if not inner or i % 2 == 0 else r * inner
        a = angle + i * math.pi / (n if inner else n / 2)
        pts.append((cx + rad * math.cos(a), cy + rad * math.sin(a)))
    return pts


def draw(shape, rng):
    bg = tuple(int(v) for v in rng.integers(0, 256, 3))
    img = Image.new("RGB", (SIZE, SIZE), bg)
    d = ImageDraw.Draw(img)
    for _ in range(6):                        # clutter: random lines in random colours
        xy = [tuple(int(v) for v in rng.integers(0, SIZE, 2)) for _ in range(2)]
        d.line(xy, fill=tuple(int(v) for v in rng.integers(0, 256, 3)), width=2)
    fg = tuple(int(v) for v in rng.integers(0, 256, 3))
    r = rng.uniform(22, 38)
    cx, cy = rng.uniform(r + 8, SIZE - r - 8, 2)
    a = rng.uniform(0, 2 * math.pi)
    if shape == "circle":
        d.ellipse([cx - r, cy - r, cx + r, cy + r], fill=fg)
    elif shape == "ring":
        d.ellipse([cx - r, cy - r, cx + r, cy + r], outline=fg, width=int(r / 3))
    elif shape == "square":
        d.polygon(polygon(cx, cy, r, 4, a), fill=fg)
    elif shape == "triangle":
        d.polygon(polygon(cx, cy, r, 3, a), fill=fg)
    elif shape == "star":
        d.polygon(polygon(cx, cy, r, 5, a, inner=0.45), fill=fg)
    elif shape == "cross":
        w = r / 3
        for t in (a, a + math.pi / 2):
            dx, dy = math.cos(t), math.sin(t)
            d.line([(cx - r * dx, cy - r * dy), (cx + r * dx, cy + r * dy)],
                   fill=fg, width=int(2 * w))
    noise = rng.normal(0, 12, (SIZE, SIZE, 3))     # sensor-like noise
    arr = np.clip(np.asarray(img, dtype=np.float32) + noise, 0, 255).astype(np.uint8)
    return Image.fromarray(arr)


if __name__ == "__main__":
    rng = np.random.default_rng(0)
    for split, n in SPLITS.items():
        for c in CLASSES:
            out = Path("data") / split / c
            out.mkdir(parents=True, exist_ok=True)
            for i in range(n):
                draw(c, rng).save(out / f"{i:03d}.png")
        print(f"{split:5s}: {n} images x {len(CLASSES)} classes = {n * len(CLASSES)}")
Terminal
python make_data.py
Expected output
train: 10 images x 6 classes = 60
val  : 10 images x 6 classes = 60
test : 30 images x 6 classes = 180

03. Step 2: The pretrained model and its preprocessing

A pretrained network works best when its inputs are prepared as during its training. torchvision attaches that recipe to the weights: ResNet18_Weights.DEFAULT.transforms() resizes to 256 pixels, crops the centre 224 × 224, scales to 0..1 and normalises each channel with the ImageNet mean and std. common.py passes smaller sizes, 112 for both, to cut the CPU cost by about four; a network sees objects at a different scale than in training then, which can cost some accuracy, but the normalisation stays the same. The file also builds the model: resnet18(weights=WEIGHTS) loads the ImageNet weights, and the 1,000-class layer fc is replaced with a new, randomly initialised nn.Linear(512, 6).

Python · common.py
import json
import time
from pathlib import Path

import torch
from torch.utils.data import DataLoader
from torchvision.datasets import ImageFolder
from torchvision.models import ResNet18_Weights, resnet18

WEIGHTS = ResNet18_Weights.DEFAULT
# the preprocessing the weights were trained with, at a smaller size to save CPU time
TRANSFORM = WEIGHTS.transforms(resize_size=112, crop_size=112)


def loaders(batch_size=16, seed=0):
    sets = {s: ImageFolder(f"data/{s}", transform=TRANSFORM)
            for s in ("train", "val", "test")}
    g = torch.Generator().manual_seed(seed)
    return {s: DataLoader(d, batch_size=batch_size, shuffle=(s == "train"),
                          generator=g if s == "train" else None)
            for s, d in sets.items()}


def pretrained(n_classes):
    model = resnet18(weights=WEIGHTS)          # 44.7 MB file, cached after first use
    model.fc = torch.nn.Linear(model.fc.in_features, n_classes)   # new, random head
    return model


def trainable(model):
    return sum(p.numel() for p in model.parameters() if p.requires_grad)


def save_run(name, preds, labels, n_trainable, seconds):
    Path("runs").mkdir(exist_ok=True)
    torch.save({"preds": preds, "labels": labels}, f"runs/{name}.pt")
    times = json.loads(Path("runs/times.json").read_text()) if Path(
        "runs/times.json").exists() else {}
    times[name] = {"trainable": n_trainable, "seconds": round(seconds, 1)}
    Path("runs/times.json").write_text(json.dumps(times, indent=1))


class Timer:
    def __enter__(self):
        self.start = time.perf_counter()
        return self

    def __exit__(self, *exc):
        self.seconds = time.perf_counter() - self.start
Python · inspect_model.py
from common import TRANSFORM, WEIGHTS, pretrained, trainable

print("weights:", WEIGHTS.name, "| ImageNet top-1:", WEIGHTS.meta["_metrics"]
      ["ImageNet-1K"]["acc@1"])
print(TRANSFORM)
model = pretrained(n_classes=6)
print("children:", ", ".join(name for name, _ in model.named_children()))
print("new head:", model.fc)
print(f"parameters: {sum(p.numel() for p in model.parameters()):,}"
      f"  (layer4: {sum(p.numel() for p in model.layer4.parameters()):,})")
print(f"trainable before freezing: {trainable(model):,}")
Terminal
python inspect_model.py
Expected output
weights: IMAGENET1K_V1 | ImageNet top-1: 69.758
ImageClassification(
    crop_size=[112]
    resize_size=[112]
    mean=[0.485, 0.456, 0.406]
    std=[0.229, 0.224, 0.225]
    interpolation=InterpolationMode.BILINEAR
)
children: conv1, bn1, relu, maxpool, layer1, layer2, layer3, layer4, avgpool, fc
new head: Linear(in_features=512, out_features=6, bias=True)
parameters: 11,179,590  (layer4: 8,393,728)
trainable before freezing: 11,179,590

The first run also prints a Downloading: …resnet18-f37072fd.pth line and a progress bar.

With the new head the network has 11,179,590 parameters, and 8,393,728 of them, three quarters, sit in layer4, the last stage. Before you freeze anything, all of them are trainable.

04. Step 3: Feature extraction

Freezing a parameter means setting requires_grad = False, so autograd computes no gradient for it and the optimiser leaves it unchanged. features.py freezes the whole network and then unfreezes only fc: 3,078 trainable parameters (512 × 6 weights plus 6 biases). The frozen layers then act as a fixed function that turns each image into a 512-number feature vector, the output of global average pooling.

Because those layers never change and the images are not augmented, the script runs the backbone over every image once, in evaluation mode so that BatchNorm uses its stored ImageNet statistics, and trains the head on the cached vectors. That gives the same result as passing the images through the frozen network at every step, at a fraction of the cost.

Python · features.py
import copy

import torch
from torch import nn

from common import Timer, loaders, pretrained, save_run, trainable

torch.manual_seed(0)
dl = loaders()
model = pretrained(n_classes=len(dl["train"].dataset.classes))
for p in model.parameters():
    p.requires_grad = False                  # freeze everything...
for p in model.fc.parameters():
    p.requires_grad = True                   # ...except the new head
print(f"trainable parameters: {trainable(model):,}")

body = nn.Sequential(*list(model.children())[:-1]).eval()   # all layers before fc


@torch.no_grad()
def embed(loader):
    out = [(body(x).flatten(1), y) for x, y in loader]
    return torch.cat([f for f, _ in out]), torch.cat([y for _, y in out])


with Timer() as t:
    feats = {s: embed(dl[s]) for s in ("train", "val", "test")}   # backbone runs once
    print("feature matrix (train):", tuple(feats["train"][0].shape))
    opt = torch.optim.AdamW(model.fc.parameters(), lr=1e-2, weight_decay=0.01)
    X, y = feats["train"]
    best = (-1.0, None)
    for step in range(1, 201):               # full batch: all 60 training vectors
        loss = nn.functional.cross_entropy(model.fc(X), y)
        opt.zero_grad()
        loss.backward()
        opt.step()
        with torch.no_grad():
            val_acc = (model.fc(feats["val"][0]).argmax(1) == feats["val"][1]).float()
        if val_acc.mean() > best[0]:
            best = (val_acc.mean().item(), copy.deepcopy(model.fc.state_dict()))
        if step in (1, 50, 100, 200):
            print(f"step {step:3d}  train loss {loss.item():.3f}  "
                  f"val acc {val_acc.mean():.3f}")
model.fc.load_state_dict(best[1])
torch.save(best[1], "head.pt")
with torch.no_grad():
    preds = model.fc(feats["test"][0]).argmax(1)
acc = (preds == feats["test"][1]).float().mean().item()
print(f"best val acc {best[0]:.3f}  test acc {acc:.3f}  (head saved to head.pt)")
save_run("features", preds, feats["test"][1], trainable(model), t.seconds)
Terminal
python features.py
Expected output
trainable parameters: 3,078
feature matrix (train): (60, 512)
step   1  train loss 2.037  val acc 0.300
step  50  train loss 0.004  val acc 0.817
step 100  train loss 0.002  val acc 0.850
step 200  train loss 0.001  val acc 0.850
best val acc 0.850  test acc 0.850  (head saved to head.pt)

A linear layer on top of ImageNet features reaches 0.850 on the test images after seeing 60 training images. The training loss falls to almost zero within 50 steps: with 512 features and 60 examples the head can separate the training set easily, which is why the best step is chosen on validation accuracy.

05. Step 4: Gradual unfreezing of layer4

Gradual unfreezing fine-tunes the network from the top down: first the head alone (step 3), then the last stage together with the head, and optionally earlier stages after that. The order matters. A new head starts random, and its large early gradients would push the pretrained weights far from where they were; training the head first means the backbone is unfrozen when the gradients it receives are already sensible. The last stage goes first because its features are the most specific to ImageNet classes, while early layers detect edges and textures that suit almost any image.

unfreeze.py loads the head from step 3, unfreezes layer4 and fc, and gives them different learning rates through parameter groups: a list of dictionaries passed to the optimiser, each with its own lr. The pretrained layer4 gets 1e-4, ten times less than the head, so its useful filters change slowly. Two further details: layers up to layer3 are still frozen, so their output is cached once, as in step 3; and layer4 stays in evaluation mode, so its BatchNorm layers keep their ImageNet running statistics instead of estimating new ones from batches of 16 images, while their scale and shift are still trained.

Python · unfreeze.py
import copy

import torch
from torch import nn

from common import Timer, loaders, pretrained, save_run, trainable

torch.manual_seed(0)
dl = loaders()
model = pretrained(n_classes=len(dl["train"].dataset.classes))
model.fc.load_state_dict(torch.load("head.pt", weights_only=True))   # from step 3
for p in model.parameters():
    p.requires_grad = False
for module in (model.layer4, model.fc):      # unfreeze the last stage and the head
    for p in module.parameters():
        p.requires_grad = True
print(f"trainable parameters: {trainable(model):,}")

# layers up to layer3 stay frozen, so their outputs never change: compute them once
frozen = nn.Sequential(model.conv1, model.bn1, model.relu, model.maxpool,
                       model.layer1, model.layer2, model.layer3).eval()


@torch.no_grad()
def cache(loader):
    out = [(frozen(x), y) for x, y in loader]
    return torch.cat([h for h, _ in out]), torch.cat([y for _, y in out])


def top(h):                                  # the trainable part of the network
    return model.fc(torch.flatten(model.avgpool(model.layer4(h)), 1))


with Timer() as t:
    data = {s: cache(dl[s]) for s in ("train", "val", "test")}
    print("cached layer3 output (train):", tuple(data["train"][0].shape))
    opt = torch.optim.AdamW([
        {"params": model.layer4.parameters(), "lr": 1e-4},   # pretrained: small steps
        {"params": model.fc.parameters(), "lr": 1e-3},       # head: larger steps
    ], weight_decay=0.01)
    model.layer4.eval()                      # keep ImageNet BatchNorm statistics
    g = torch.Generator().manual_seed(0)
    H, y = data["train"]
    best = (-1.0, None)
    for epoch in range(1, 16):
        for idx in torch.randperm(len(H), generator=g).split(16):
            loss = nn.functional.cross_entropy(top(H[idx]), y[idx])
            opt.zero_grad()
            loss.backward()
            opt.step()
        with torch.no_grad():
            val_acc = (top(data["val"][0]).argmax(1) == data["val"][1]).float().mean()
        if val_acc > best[0]:
            best = (val_acc.item(), copy.deepcopy(model.state_dict()))
        if epoch % 5 == 0:
            print(f"epoch {epoch:2d}  last batch loss {loss.item():.3f}  "
                  f"val acc {val_acc:.3f}")
model.load_state_dict(best[1])
with torch.no_grad():
    preds = top(data["test"][0]).argmax(1)
acc = (preds == data["test"][1]).float().mean().item()
print(f"best val acc {best[0]:.3f}  test acc {acc:.3f}")
save_run("unfreeze", preds, data["test"][1], trainable(model), t.seconds)
Terminal
python unfreeze.py
Expected output
trainable parameters: 8,396,806
cached layer3 output (train): (60, 256, 7, 7)
epoch  5  last batch loss 0.032  val acc 0.817
epoch 10  last batch loss 0.000  val acc 0.867
epoch 15  last batch loss 0.000  val acc 0.867
best val acc 0.867  test acc 0.878

Fine-tuning layer4 adds about 8.4 million trainable parameters and lifts test accuracy from 0.850 to 0.878, five more correct images out of 180. That is a small gain on a small test set, so treat it as a hint, not proof: with 30 test images per class, one image moves a class recall by 0.03.

06. Step 5: The same network from scratch

scratch.py builds ResNet-18 with weights=None, so all 11.2 million parameters start random and all are trained, on the same images with the same preprocessing. Nothing can be cached, so every step runs the full network forward and backward; this is the slowest script of the lab, about a minute or more on a laptop CPU.

Python · scratch.py
import copy

import torch
from torch import nn
from torchvision.models import resnet18

from common import Timer, loaders, save_run, trainable

torch.manual_seed(0)
dl = loaders()
model = resnet18(weights=None, num_classes=len(dl["train"].dataset.classes))
print(f"trainable parameters: {trainable(model):,}")
opt = torch.optim.AdamW(model.parameters(), lr=1e-3, weight_decay=0.01)


@torch.no_grad()
def predict(loader):
    model.eval()
    out = [(model(x).argmax(1), y) for x, y in loader]
    return torch.cat([p for p, _ in out]), torch.cat([y for _, y in out])


with Timer() as t:
    best = (-1.0, None)
    for epoch in range(1, 13):
        model.train()
        for x, y in dl["train"]:
            loss = nn.functional.cross_entropy(model(x), y)
            opt.zero_grad()
            loss.backward()
            opt.step()
        p, yv = predict(dl["val"])
        val_acc = (p == yv).float().mean().item()
        if val_acc > best[0]:
            best = (val_acc, copy.deepcopy(model.state_dict()))
        if epoch % 4 == 0:
            print(f"epoch {epoch:2d}  last batch loss {loss.item():.3f}  "
                  f"val acc {val_acc:.3f}")
    model.load_state_dict(best[1])
    preds, labels = predict(dl["test"])
acc = (preds == labels).float().mean().item()
print(f"best val acc {best[0]:.3f}  test acc {acc:.3f}")
save_run("scratch", preds, labels, trainable(model), t.seconds)
Terminal
python scratch.py
Expected output
trainable parameters: 11,179,590
epoch  4  last batch loss 1.449  val acc 0.150
epoch  8  last batch loss 0.393  val acc 0.233
epoch 12  last batch loss 0.087  val acc 0.217
best val acc 0.233  test acc 0.222

The loss falls, so the network is fitting the 60 training images, but validation accuracy stays near 0.2, barely above the 0.167 of guessing among six classes. Eleven million parameters cannot learn general shape detectors from ten examples per class. To check that the budget is not the reason, rerun scratch.py with more epochs and watch whether validation accuracy moves.

07. Step 6: Compare accuracy, errors and cost

Accuracy alone hides which classes fail. report.py loads the saved test predictions of all three runs and prints accuracy, the recall of each class (the share of its 30 test images that were predicted as that class) and the three most frequent confusions. times.py prints the trainable parameters and the training time of each run.

Python · report.py
import json
from collections import Counter
from pathlib import Path

import torch

from make_data import CLASSES

times = json.loads(Path("runs/times.json").read_text())
for name in ("scratch", "features", "unfreeze"):
    run = torch.load(f"runs/{name}.pt", weights_only=True)
    preds, labels = run["preds"], run["labels"]
    acc = (preds == labels).float().mean().item()
    print(f"{name}: test accuracy {acc:.3f}, "
          f"trainable parameters {times[name]['trainable']:,}")
    recall = [(preds[labels == k] == k).float().mean().item()
              for k in range(len(CLASSES))]
    print("  recall: " + "  ".join(f"{c} {r:.2f}" for c, r in zip(CLASSES, recall)))
    pairs = Counter((CLASSES[t], CLASSES[p])
                    for t, p in zip(labels.tolist(), preds.tolist()) if t != p)
    top = ", ".join(f"{t}->{p} x{n}" for (t, p), n in pairs.most_common(3))
    print("  most confused (true->predicted):", top or "none")
Terminal
python report.py
Expected output
scratch: test accuracy 0.222, trainable parameters 11,179,590
  recall: circle 0.13  cross 0.03  ring 0.70  square 0.13  star 0.10  triangle 0.23
  most confused (true->predicted): square->ring x19, cross->ring x18, star->ring x14
features: test accuracy 0.850, trainable parameters 3,078
  recall: circle 0.97  cross 0.77  ring 0.97  square 0.83  star 0.77  triangle 0.80
  most confused (true->predicted): cross->star x4, star->cross x4, triangle->square x4
unfreeze: test accuracy 0.878, trainable parameters 8,396,806
  recall: circle 0.97  cross 0.87  ring 0.97  square 0.87  star 0.80  triangle 0.80
  most confused (true->predicted): cross->star x4, triangle->square x4, square->cross x3
Python · times.py
import json
from pathlib import Path

times = json.loads(Path("runs/times.json").read_text())
for name in ("scratch", "features", "unfreeze"):
    t = times[name]
    print(f"{name:9s} trainable {t['trainable']:>11,}  "
          f"training time {t['seconds']:6.1f} s")
Terminal
python times.py
Illustrative output
scratch   trainable  11,179,590  training time   68.1 s
features  trainable       3,078  training time    8.4 s
unfreeze  trainable   8,396,806  training time   32.6 s

The scratch model leans towards one class: it predicts "ring" for many images of other classes, so ring has a recall of 0.70 and cross 0.03. Both pretrained runs fail on the same pairs, cross against star and triangle against square, shapes made of straight edges and corners; fine-tuning layer4 reduced these errors but did not remove them. On cost, the times above come from one shared machine, so only their order matters: the feature extractor is cheapest because the backbone runs once, unfreezing costs more but still computes every layer before layer4 only once, and training from scratch is the most expensive and the least accurate. With a few hundred images per class the gap is usually smaller; the practice project measures it on real data.

08. Check your understanding

Practice check · 3 questions

Reading the transfer runs

Use the code and outputs of this lab.

Q1. `unfreeze.py` calls `model.layer4.eval()` and then trains `layer4`. What does that call change?
Q2. `times.py` shows `unfreeze.py` training much faster than `scratch.py`, although it updates 8.4 of the 11.2 million parameters. What explains most of the difference?
Q3. `report.py` gives the feature extractor a test accuracy of 0.850 and a recall of 0.77 for cross. What does the 0.77 mean?
Practice only: not graded, not saved, not evidence.

09. Apply it

This lab is a small version of the practice project. Repeat it on a real dataset of a few hundred images per class.

  1. Keep one fixed split and one evaluation script for all runs, and give the from-scratch CNN and the fine-tuned ResNet the same time budget on the same hardware.
  2. Report test accuracy, per-class recall, training time and the five most frequent confused pairs, as report.py does with three.
  3. Try unfreezing layer3 as a third stage with an even lower learning rate, and keep it only if validation accuracy improves.
  4. Add label-preserving augmentation for the from-scratch model, as in the CNN lab; note that it stops you from caching the features of frozen layers.

10. Review prompt

Without looking back, explain what weights.transforms() provides and why a pretrained model needs it; describe how you freeze a backbone and replace the head of a torchvision ResNet; explain why the head is trained before the backbone is unfrozen, and why the backbone gets a lower learning rate through parameter groups; say when caching frozen features is valid; and explain why ten images per class were enough for the pretrained model but not for the same network from scratch.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check