Transfer learning is the closest thing machine learning has to a cheat code. Somebody already spent a few million ImageNet photos teaching ResNet18 what edges, fur and wings look like. You keep all of that, cut off the last layer, and teach a new one your classes using a few hundred images. The recipe is four steps: load the weights, freeze them, swap the head, and train the head. Every one of those steps has a way to go quietly wrong. Quietly is the problem. None of the failures below raised an error. They just cost you accuracy and let you find out at demo time.

The idea came from the it-journey.dev Computer Vision quest. Its job is teaching you what a CNN is. Mine was to follow the shortcut and then break each step on purpose, five ways, with a table.

The rig: a 4-core CPU, no GPU, Python 3.14.4, torch 2.15.0+cpu, torchvision 0.29.2+cpu and Pillow 13.0.0. The data is the ants-vs-bees set from the PyTorch transfer-learning tutorial: two classes, 244 training images and 153 validation images. It’s small enough to be “your own images” and real enough that a wrong answer means something. Every output below is pasted from a run. In the console blocks I shortened /tmp/... paths and nothing else.

Get the parts

$ python3 -m venv /tmp/tv
$ /tmp/tv/bin/pip install -q torch torchvision --index-url https://download.pytorch.org/whl/cpu
$ curl -sSfL -o h.zip https://download.pytorch.org/tutorial/hymenoptera_data.zip && unzip -q h.zip

The --index-url .../whl/cpu is there on purpose. Without it, pip on Linux pulls the CUDA build, which is gigabytes of GPU libraries for a machine that has no GPU. ImageFolder wants one folder per class, so lay out your own images the same way the zip does: train/ants/*.jpg, train/bees/*.jpg, and the same under val/. The folder names become the labels.

The recipe

import sys, torch, torch.nn as nn
from torchvision import datasets, models, transforms

data = sys.argv[1]  # a folder with train/<class>/*.jpg and val/<class>/*.jpg
torch.manual_seed(0)

# 1. The preprocessing the pretrained weights were trained on. Not optional.
tf = transforms.Compose([
    transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(),
    transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
])
train = datasets.ImageFolder(f"{data}/train", tf)
val = datasets.ImageFolder(f"{data}/val", tf)
tl = torch.utils.data.DataLoader(train, batch_size=32, shuffle=True)
vl = torch.utils.data.DataLoader(val, batch_size=64)

# 2. Load the backbone and freeze every weight in it.
net = models.resnet18(weights=models.ResNet18_Weights.DEFAULT)
for p in net.parameters():
    p.requires_grad = False

# 3. Swap the 1000-class ImageNet head for yours. New layers are trainable by default.
net.fc = nn.Linear(net.fc.in_features, len(train.classes))

# 4. Hand the optimizer the head, and only the head.
opt = torch.optim.SGD(net.fc.parameters(), lr=0.01, momentum=0.9)

def frozen_train_mode():
    net.train()
    for m in net.modules():          # requires_grad=False does NOT stop BatchNorm
        if isinstance(m, nn.BatchNorm2d):  # from rewriting its running stats.
            m.eval()

print(f"{len(train)} train / {len(val)} val images, classes={train.classes}")
print(f"trainable params: {sum(p.numel() for p in net.parameters() if p.requires_grad):,}")
for epoch in range(5):
    frozen_train_mode()
    for x, y in tl:
        opt.zero_grad()
        nn.functional.cross_entropy(net(x), y).backward()
        opt.step()
    net.eval(); right = 0
    with torch.no_grad():
        for x, y in vl:
            right += (net(x).argmax(1) == y).sum().item()
    print(f"epoch {epoch + 1}: val accuracy {right / len(val):.1%}")
torch.save(net.state_dict(), "finetuned.pt")
$ time /tmp/tv/bin/python finetune_head.py hymenoptera_data
244 train / 153 val images, classes=['ants', 'bees']
trainable params: 1,026
epoch 1: val accuracy 94.8%
epoch 2: val accuracy 96.1%
epoch 3: val accuracy 96.1%
epoch 4: val accuracy 96.1%
epoch 5: val accuracy 96.1%

real	0m40.223s
user	1m4.275s
sys	0m13.968s

That’s 1,026 trainable numbers: a 512×2 weight matrix plus 2 biases. The other 11.2 million came pre-trained. It reached 96.1% on images it never saw, in 40 seconds, on a laptop-class CPU. I don’t hand out compliments, so record this one: it works.

The first run also downloads the weights (resnet18-f37072fd.pth, about 45 MB) into ~/.cache/torch/hub/checkpoints/. Every run after that is offline.

The gauntlet

Next I broke the recipe one step at a time. Each variant is the script above with one change. All runs used the same data and five epochs, and I scored the final epoch.

What I broke One-line change Trainable params Val accuracy (seed 0) Error raised
Nothing (the recipe) none 1,026 96.1% ✅ none
Dropped the normalization delete the Normalize(...) line 1,026 85.6% ❌ none
Optimizer gets everything SGD(net.parameters(), ...) 1,026 96.1% ✅ none
Plain net.train() skip the BatchNorm eval() loop 1,026 90.2% ❌ none
Forgot to freeze delete the requires_grad = False loop 11,177,538 93.5% ❌ none

The last column reads “none” five times, and that’s the column that matters.

Failure 1: no normalization. No error, 10 points gone

ResNet18’s weights learned from pixels shifted by the ImageNet mean and scaled by the ImageNet standard deviation, one pair per RGB channel. Drop Normalize and the network gets raw 0–1 tensors. They’re the right shape and the right dtype, so nothing complains. The pictures are just in a brightness range the backbone never trained on.

The brief I worked from said accuracy “craters”. It didn’t. It slid, and on four seeds it kept sliding:

Seed With Normalize Without Difference
0 96.1% (147/153) 85.6% (131/153) −16 images
1 95.4% (146/153) 87.6% (134/153) −12 images
2 96.1% (147/153) 91.5% (140/153) −7 images
3 96.7% (148/153) 91.5% (140/153) −8 images

A crater would be easier to catch. 85–91% looks like a model that’s working, so you ship it. The failure this prevents: you lose 7 to 16 correct answers out of 153, the loss curve looks normal, and you spend a week blaming your dataset. The fix is to copy the exact mean and std from the weights you loaded. If you’re unsure which numbers those are, models.ResNet18_Weights.DEFAULT.transforms() returns the preprocessing that matches those weights.

Failure 2 (that wasn’t): the optimizer got every parameter

The standard warning goes like this: hand the optimizer net.parameters() instead of net.fc.parameters() and you waste compute updating the backbone. So I tested it. It got the same 96.1%, to the image, and the backbone came out bit-for-bit identical (0 of 120 tensors changed). The run took 37.2 seconds versus 37.7 for the recipe.

It survived because the parameters were already frozen. Frozen parameters never get a .grad, and SGD skips any parameter whose grad is None. The freezing does the work. The optimizer argument is a second lock on the same door. I still recommend net.fc.parameters(), because the second lock is the one that saves you on the day someone deletes the first. It just isn’t the bug people say it is. Grudgingly noted.

Failure 3, the real one: requires_grad=False doesn’t freeze BatchNorm

This is the break that found a real bug. Every tutorial calls plain net.train() before each epoch. I compared the backbone’s state before and after training. With a plain net.train(), a backbone where every parameter had requires_grad=False came back with this:

backbone tensors changed: 60 of 120; e.g. ['bn1.running_mean', 'bn1.running_var']

ResNet18 has 20 BatchNorm layers. Each one keeps running_mean, running_var and num_batches_tracked as buffers, not parameters. requires_grad doesn’t apply to buffers, and in train mode every forward pass overwrites them with statistics from your current batch of 32 bees. 20 layers × 3 buffers = 60 tensors. The gradient never touched them. The forward pass did.

Across four seeds, the drifting statistics cost accuracy every time:

Seed BatchNorm held in eval() Plain net.train()
0 96.1% 90.2%
1 95.4% 91.5%
2 96.1% 94.1%
3 96.7% 93.5%

It was also jumpier along the way. Seed 0 went 95.4 → 90.8 → 98.0 → 90.2 → 90.2 across its five epochs. One of those epochs beat the recipe, which is exactly how this bug gets past code review. The failure this prevents: a backbone you “froze” adapts its statistics to a few hundred photos, and a checkpoint you think matches ImageNet ResNet18 doesn’t. That’s why frozen_train_mode() is in the recipe: train mode for the head, eval mode for every BatchNorm2d.

Failure 4: forgot to freeze

Delete the freeze loop and all 11,177,538 parameters train at a learning rate chosen for a fresh head. The brief promised the backbone would turn “into mush”. It didn’t. It overfit instead. Training loss hit 0.000 by epoch 4, which means the model memorized 244 photos. Validation landed at 93.5%, three points under the recipe, and every one of the 120 backbone tensors changed. It also took 67.8 seconds instead of 37.7, so you pay 1.8× the time for a worse model. On a set this small, full fine-tuning needs a much smaller learning rate and probably augmentation. That’s a different hack, not a default.

Failure 5: the folder full of surprises

Your own images are never as clean as a tutorial zip. Here’s what happened when I dropped some extra files into train/ants/:

File I added What ImageFolder did
gray.jpg (1-channel grayscale) ✅ loaded as 3×224×224 (the default loader converts to RGB)
alpha.png (RGBA, 4 channels) ✅ loaded as 3×224×224, alpha dropped
ant 🐜 + a real newline + newline'; DROP TABLE ants;--.jpg ✅ loaded fine. Grudging respect
notes.txt ✅ skipped (wrong extension)
fake.jpg (a text file named .jpg) ❌ listed and counted, then UnidentifiedImageError the first time anything indexed it

There was one more surprise, and it was already in the tutorial zip:

$ file hymenoptera_data/train/ants/imageNotFound.gif
hymenoptera_data/train/ants/imageNotFound.gif: GIF image data, version 89a, 300 x 300

ImageFolder only takes .jpg .jpeg .png .ppm .bmp .pgm .tif .tiff .webp, so a .gif is skipped without a word. That’s why the zip holds 245 training files and the script reports 244. In this case the skip is a favour, because the file is a “missing image” placeholder. The failure this prevents: your scraped dataset is 30% .gif and .avif, ImageFolder silently trains on the other 70%, and nobody notices because nobody compares len(train) with ls | wc -l. Print the count. The recipe does.

Verdict

On the survives-a-Tuesday scale, the recipe as written survives a bad Tuesday: 95.4–96.7% across four seeds, on a CPU, in about 40 seconds. The tutorial version, with a plain net.train() and a hand-typed normalization, survives a normal Tuesday, and only on the seeds you happened to try. Neither survives the intern with sudo who renames a text file to .jpg, but that one at least crashes loudly. Out of everything here, I trust the failure that raises an error.

Checklist, in the order the bugs bit:

  1. Use the weights’ own preprocessing (Weights.DEFAULT.transforms(), or the exact mean and std).
  2. Set requires_grad = False on the backbone and put its BatchNorm2d layers in eval() while you train the head.
  3. Replace net.fc and give the optimizer net.fc.parameters() (belt and braces).
  4. Print len(train) and compare it with what’s on disk.