Learning path: Deep Learning for Production: Transformers, Fine-Tuning and Serving · Step 2 of 13
Transfer Learning on Images: A Frozen ResNet-18, a Small Head and an Honest Baseline
Freeze a pretrained ResNet-18 (11,176,512 parameters, 0 trainable) and train a 5,130-weight head on digit images, then compare it with from-scratch models. On this data the borrowed model loses twice, and the baseline is what tells you.
What you will learn
- Freeze a pretrained ResNet-18 from Hugging Face with requires_grad = False
- Turn images into 512 features and train only a small linear head
- Compare the frozen head with a from-scratch baseline, on plenty of images and on few
- Decide when transfer learning is worth trying
Before you start
- Convolutional Neural Networks (CNN) Basics
- Dropout, Early Stopping and Batch Norm
Say you're opening a restaurant. You could hire someone and train them from boiling water up. That takes years. Or you hire an experienced chef who already knows knives, heat and timing. You don't retrain any of that. You just teach them your menu, and that's a small job.
That's transfer learning. The chef's experience is a pretrained model someone else already trained. The menu is a new last layer that we call the head. We lock the model and teach only the head.
But here's the question people forget to ask: what if your menu is just boiled eggs? Then a simple cook might do just as well. Keep that in mind, because on our data it's exactly what happens.
The result first
The data is scikit-learn's load_digits: 1,797 handwritten digits, 8x8 pixels each. We split them 60/20/20 with seed 0, which gives 1,078 images to train, 359 for validation and 360 for the final test.
With 1,078 training images, a plain model on raw pixels gets 97.2%. The pretrained model with a small head gets 95.8%. Cut the training set to 150 images, where borrowing should shine, and the gap gets wider: 90.8% from scratch against 81.9% borrowed. On this data the borrowed model lost both times. Let's build it, then see why.
The idea: frozen encoder, one small head
Our digit image is tiny, 8x8. The model expects bigger colour images, so we stretch it to 128x128 and repeat it into three channels. It goes through ResNet-18, an image model trained on ImageNet photos, and 512 numbers come out: the model's description of the image.
Every weight in that encoder is locked. The only thing that learns is the head, one linear layer from 512 numbers to 10 digits. That's 512 x 10 + 10 = 5,130 weights on top of 11 million frozen ones. Small and cheap to train, and that's the whole appeal.
Preparing the images
data.py does the stretching and the split:
import numpy as np
import torch
import torch.nn.functional as F
from sklearn.datasets import load_digits
MEAN = [0.485, 0.456, 0.406]
STD = [0.229, 0.224, 0.225]
def load_images(size=128):
d = load_digits()
x = torch.tensor(d.images, dtype=torch.float32) / 16
x = F.interpolate(x.unsqueeze(1), size=size,
mode="bilinear")
x = x.repeat(1, 3, 1, 1)
m = torch.tensor(MEAN).view(1, 3, 1, 1)
s = torch.tensor(STD).view(1, 3, 1, 1)
return (x - m) / s, torch.tensor(d.target)
def split(n, seed=0):
idx = np.random.RandomState(seed).permutation(n)
a, b = int(n * 0.6), int(n * 0.8)
return idx[:a], idx[a:b], idx[b:]
Pixel values in load_digits run from 0 to 16, so dividing by 16 puts them between 0 and 1. F.interpolate stretches each image to 128x128, repeat copies the single channel into three, and the last line normalises with the mean and spread of each colour channel that ImageNet models expect.
The freeze in model.py
import torch
from torch import nn
from transformers import ResNetModel
NAME = "microsoft/resnet-18"
def load_encoder():
enc = ResNetModel.from_pretrained(NAME)
for p in enc.parameters():
p.requires_grad = False
return enc
def embed(enc, x, train_mode=False):
enc.train(train_mode)
with torch.no_grad():
out = enc(pixel_values=x).pooler_output
return out.flatten(1)
def make_head(dim=512, classes=10):
return nn.Linear(dim, classes)
load_encoderpulls the ResNet-18 weights from Hugging Face withfrom_pretrained.- The loop sets
requires_grad = Falseon every parameter. That's the freeze. embedturns images into the 512 numbers, with the encoder in evaluation mode so its batch norm layers stay put. Why that matters is the batch norm trap in Dropout, Early Stopping and Batch Norm.make_headis one line, a linear layer from 512 to 10. That's everything we train.
encoder params: 11176512 trainable: 0
11,176,512 parameters, and not one of them will change.
Baseline against the frozen head
In run_lecture.py we first train a baseline: flatten the pixels and fit logistic regression, starting from nothing. Then the head: embed every image once, standardise the features with the train rows' mean and spread, and fit only that one layer.
from sklearn.linear_model import LogisticRegression
from data import load_images, split, standardise
from model import load_encoder, embed, make_head
from train import fit, accuracy
x, y = load_images()
tr, va, te = split(len(y))
enc = load_encoder()
flat = x[:, 0].flatten(1).numpy()
base = LogisticRegression(max_iter=3000)
base.fit(flat[tr], y[tr])
b_acc = base.score(flat[te], y[te])
print("baseline test acc:", round(b_acc, 4))
f = standardise(embed(enc, x), tr)
head = make_head()
fit(head, (f[tr], y[tr]), (f[va], y[va]), lr=0.003)
h_acc = accuracy(head, f[te], y[te])
print("frozen head test acc:", round(h_acc, 4))
baseline test acc: 0.9722
frozen head test acc: 0.9583
Out of 360 test images, that's 350 right against 345. Only five images, so I wouldn't call the pixels far better. But the pretrained model is no better here, and without the baseline, 95.8% would have looked great on its own.
What about just a few images?
Borrowing is supposed to help when data is short. So both sides get the same 150 training images (tr[:150]), Adam with learning rate 0.01 and 200 epochs.
- From scratch: in
compare_curves.py, a tiny two-layer network learns from the 64 raw pixels. - Borrowed: in
run_lecture.py, the head learns from the 512 ResNet features of the same images.
small = tr[:150]
sub = (f[small], y[small])
h1 = make_head()
log1 = fit(h1, sub, (f[va], y[va]), lr=0.01)
plain: best val 0.340 at epoch 26, final val 0.486, test acc 0.9083
no stopping: epochs 200 best val epoch 5 test acc 0.8194
From scratch 0.9083, frozen head 0.8194: 327 against 295 out of 360. The gap got wider. A likely reason is that these digits are small, clean and centred, while this encoder learned from everyday photos. That wasn't measured, so treat it as a guess. Also note this is one seed and neither model got a learning-rate search.
When to borrow
Does that make transfer learning a bad idea? No. It's the usual starting point at work, because it costs so little to try. These are rules of thumb, not results from this run:
- Borrow when your images look like what the encoder learned from (photos of everyday things) and you have few labels.
- Start simple when your images are small and clean, like these digits.
- Either way, train a cheap baseline beside it. That's what told us the truth here.
Common mistakes
- No baseline. 95.8% sounds good until a logistic regression on pixels gets 97.2%.
- Trusting the model's name. A famous pretrained model is no guarantee on your data. The comparison decides.
- Feeding the wrong input shape. ImageNet models expect three channels and normalised colours; a raw 8x8 grey image needs stretching, repeating and normalising first.
- Freezing only half the way.
requires_grad = Falseplus evaluation mode, or batch norm statistics drift.
Quick recap
| Training images | From scratch | Pretrained + head |
|---|---|---|
| 1,078 | 0.9722 (logistic regression, pixels) | 0.9583 |
| 150 | 0.9083 (tiny network, pixels) | 0.8194 |
Freeze the encoder and train only a small head: 5,130 weights on top of 11,176,512 frozen ones. Keep a baseline beside it. Trust the comparison, not the name of the model.
Try it yourself
In both run_lecture.py and compare_curves.py, change 150 to 50 and run them again. Which one wins now?
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →Dropout, Early Stopping and Batch Norm: Judge Each One by the Validation Curve
Next →Attention Explained Without the Maths: Query, Key, Value and the Word "it"
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)Related articles
Why Neural Networks: Pixels, One Neuron and Layers
Why pictures need neural networks: a handwritten digit is 784 numbers, one neuron is a weighted sum plus a bias and one small rule, and neurons stack into layers. Worked out on MNIST with NumPy.
The Forward Pass and Activation Functions: ReLU, Sigmoid, Tanh and Softmax
Follow numbers through a tiny 3-2-3 network in NumPy: one matrix product per layer, ReLU inside, softmax at the end, and a count of every weight and bias.
Loss and Backpropagation: How Wrong, and Who Is to Blame
The loss says how wrong the network was; backpropagation says how much each weight is to blame. MSE and cross-entropy, the chain rule by hand on a two-weight chain, then the same gradients from PyTorch autograd.
The Training Loop: Epochs, Mini-Batches, Learning Rate and Optimisers
How training is organised: shuffle, cut into mini-batches, take one step per batch, repeat per epoch. Real MNIST runs compare three learning rates, SGD against Adam, and show the overfitting signal in the validation loss.