Skip to content
Visual explainer 4h 30m to learn 5 steps

Convolutional networks and transfer learning in PyTorch

Compare a dense and a convolutional model on an image task, then fine-tune a pretrained model with augmentation and evaluate on distinct data.

By Invicly Tech, , in AI and Machine Learning with Python. About 11 minutes to read.

Topic 21 of 34

In short

Convolutional networks slide small learned filters across an image, so they reuse weights and keep spatial structure that a dense network throws away. Transfer learning starts from a network already trained on millions of images and retrains only its last layers, which gives strong results with little data and CPU-sized compute. The result only counts if you test on images that are genuinely different from the training ones.

Think of it like this: Transfer learning is like hiring an experienced photographer for a new magazine: they already know light and shape, so you only teach them your house style.

Explained simply

Images are big grids of numbers. A small colour photo of 224 by 224 pixels holds about 150,000 values. A dense network connects every value to every unit, which needs huge numbers of weights and ignores the fact that nearby pixels belong together.

A convolutional network, or CNN, uses small filters that slide across the image looking for local patterns such as edges, corners and textures. Deeper layers combine those into bigger shapes such as eyes or wheels. The same filter is reused everywhere, so the model is smaller and learns faster.

Training a CNN from scratch needs lots of images and compute. Transfer learning skips most of that. You take a model already trained on a large dataset such as ImageNet, keep its feature-detecting layers, and train only a new final layer for your own classes.

The catch is evaluation. If your test photos come from the same camera, room or day as the training photos, a high score can be misleading. Testing on images from a genuinely different source tells you whether the model will work in the real world.

Press Play on a diagram to walk through it one step at a time.

FlowFine-tuning a pretrained backbone
  1. 1
    Load pretrained model

    For example resnet18 with ImageNet weights

  2. 2
    Freeze the backbone

    Set requires_grad = False on its parameters

  3. 3
    Replace the head

    New nn.Linear sized to your classes

  4. 4
    Train the head

    With augmented training images

  5. 5
    Optionally unfreeze

    Fine-tune deeper layers with a small learning rate

LayersWhat a CNN learns at each depth
  1. 1
    Classifier head

    Maps features to your classes

  2. 2
    Deep layers

    Object parts and whole shapes

  3. 3
    Middle layers

    Textures and simple motifs

  4. 4
    Early layers

    Edges, colour blobs and gradients

  5. 5
    Input image

    Channels by height by width

In depth

Dense versus convolutional layers

A dense layer from a 28 by 28 greyscale image to 128 units needs 784 times 128 weights, about 100,000, and it would need to relearn the same edge detector at every position. A conv layer with 32 filters of size 3 by 3 on that image needs only 32 times 9 weights plus 32 biases, 320 parameters, because each filter is shared across all positions.

That sharing gives translation equivariance: a pattern is detected wherever it appears. Pooling layers then shrink the feature maps, so later layers see larger areas of the image. On Fashion-MNIST a small CNN usually beats a dense network of similar size by a few accuracy points while using fewer parameters, and the gap grows on larger, more varied images.

CompareDense and convolutional layers on images
Dense (nn.Linear)
  • Flattens the image to a long vector
  • One weight per pixel per unit
  • Ignores which pixels are neighbours
  • Parameter count grows with image size
Convolutional (nn.Conv2d)
  • Keeps the 2D grid
  • Small filter shared across positions
  • Detects local patterns anywhere
  • Parameter count independent of image size

Augmentation that preserves the label

Augmentation creates new training examples by applying random changes that should not change the answer. A cat flipped left to right is still a cat, so RandomHorizontalFlip is safe for most photos. RandomResizedCrop, small rotations and colour jitter add more variety. Use torchvision.transforms.v2 and compose the steps.

Choose changes that match the real world. Flipping digits or text can change their meaning, and vertical flips rarely make sense for street scenes. Apply augmentation only to the training split. Validation and test use a fixed resize, centre crop and normalisation, so their scores are comparable between runs. Augmentation makes each epoch slower on a CPU, so keep images small while you experiment.

  • Train: random crop, flip, light colour jitter, then normalise
  • Validation and test: resize, centre crop, normalise
  • Check a grid of augmented images by eye before training

Feature extraction versus fine-tuning

There are two common strategies. Feature extraction freezes the whole pretrained backbone and trains only a new head. It is fast, works on a CPU and suits small datasets of a few hundred images per class. Fine-tuning then unfreezes some or all backbone layers and trains them with a learning rate around ten times smaller than the head's, so the pretrained features adapt without being destroyed.

A good recipe is to train the head first until validation stops improving, then unfreeze the last block and continue briefly. Always use the preprocessing that comes with the weights: in torchvision, weights.transforms() returns the correct resize, crop and normalisation. Check model and weight licences before you ship; torchvision documents where each set of weights comes from.

Evaluating on genuinely distinct data

Image datasets often contain near-duplicates: bursts of photos, the same object from slightly different angles, or frames from one video. A random split puts siblings in both train and test, so the model can score highly by recognising the scene rather than the class. Split by group instead, such as by photographer, device, session or patient, using the grouped splitting ideas from the evaluation module.

It also helps to keep a small external test set collected differently, for example on another day or with another phone. Report accuracy per class and look at the confusion matrix and the worst misclassified images. If accuracy drops sharply on the external set, the model learned shortcuts such as background colour.

CPU first, GPU optional

Everything in this topic runs on a CPU if you keep it small: a few hundred images per class, 128 or 160 pixel inputs, a ResNet-18 or MobileNet backbone and a frozen backbone. Expect minutes per epoch rather than seconds. To go faster, precompute backbone features once and train the head on the saved tensors.

A GPU helps when you fine-tune the whole backbone or use large images. Options include a local NVIDIA card, Apple silicon via the mps device, free hosted notebooks with time limits, or paid cloud GPU instances. Paid hardware costs money by the hour, so stop instances when you finish. Your code should only change in the device line.

Learn it in 5 short steps

About 55m each. Track them with a timer in your plan.

  1. 1
    Compare dense and convolutional layers~55m
  2. 2
    Augment training images~55m
  3. 3
    Fine-tune a pretrained backbone~55m
  4. 4
    Evaluate on genuinely distinct data~55m
  5. 5
    Run on CPU or optional GPU~55m

Key points

  • A conv layer shares one small filter across the whole image, so it needs far fewer weights than a dense layer.
  • Augmentation such as flips and crops applies to training data only, never to validation or test.
  • Use the same resizing and normalisation the pretrained weights expect.
  • Freezing the backbone makes training fast enough for a CPU.
  • Test on images from a different source, session or person to check real generalisation.

Key terms

Tap a card to flip it. 0/6 known

Examples

python
from torch import nn
from torchvision.models import resnet18, ResNet18_Weights

weights = ResNet18_Weights.DEFAULT
model = resnet18(weights=weights)
for p in model.parameters():
    p.requires_grad = False
model.fc = nn.Linear(model.fc.in_features, 3)  # 3 classes
preprocess = weights.transforms()  # resize, crop, normalise
# pass only model.fc.parameters() to the optimiser

The weights download once (about 45 MB) and are cached locally.

Classifying three kinds of leaves with a frozen ResNet-18

Prerequisites: torch, torchvision and a folder per class under data/train and data/val, with about 150 of your own or openly licensed images per class. Step 1: load ResNet-18 with default weights and freeze it. Step 2: replace model.fc with a three-class linear layer. Step 3: build ImageFolder datasets, with augmentation for train only. Step 4: train the head with AdamW at lr 1e-3 for about 5 epochs. Expected evidence: validation accuracy climbs well above the 33 percent chance level within the first epoch or two. Cleanup: delete the cached weights in the torch hub cache folder if you need the space.

python
from torchvision import datasets, transforms as T

norm = T.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
train_tf = T.Compose([T.RandomResizedCrop(160), T.RandomHorizontalFlip(),
                      T.ToTensor(), norm])
val_tf = T.Compose([T.Resize(180), T.CenterCrop(160), T.ToTensor(), norm])
train_ds = datasets.ImageFolder("data/train", transform=train_tf)
val_ds = datasets.ImageFolder("data/val", transform=val_tf)
print(train_ds.classes)
opt = torch.optim.AdamW(model.fc.parameters(), lr=1e-3)

Catching a leak from near-duplicate photos

A defect classifier for factory parts scored 99 percent on a random split. Step 1: the team checked file names and saw each part was photographed five times in a row. Step 2: they re-split by part ID so all five photos of a part landed on the same side. Step 3: accuracy dropped to 91 percent. Step 4: they added 200 photos from a second production line as an external test, where accuracy was 87 percent. The 87 percent figure went into the model card, with a note that new lines need their own check.

Quick reference

  • Conv2d(in_channels, out_channels, kernel_size); 3 by 3 kernels are the usual default
  • Augment training data only; validation and test use fixed resize and crop
  • Use weights.transforms() so inputs match what the pretrained model expects
  • Freeze the backbone with requires_grad = False and train only the new head first
  • Fine-tune deeper layers with a learning rate about 10 times smaller
  • Split by group (device, session, person) to avoid near-duplicate leakage
  • On CPU: small inputs, small backbone, or precompute features once

Common mistakes

  • Letting near-duplicate photos land in both train and test, which inflates accuracy.
  • Forgetting the pretrained normalisation, so the backbone sees inputs it was not trained on.
  • Unfreezing everything with a large learning rate and wiping out the pretrained features.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1How many weights (excluding biases) does Conv2d(1, 16, kernel_size=3) have?

Question 2

2Which augmentation is risky for a handwritten digit classifier?

Question 3

3You have 200 images per class and only a CPU. Which approach fits best?

Question 4

4Test accuracy is 98 percent on a random split but 80 percent on photos from a new site. What is the most likely explanation?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Count the parameters of nn.Linear(784, 128) and nn.Conv2d(1, 32, 3) in code and compare them.

  2. Exercise 2medium

    Build a small CNN for 28 by 28 greyscale images: two conv and max-pool stages, then a linear layer to 10 classes. Pass a dummy batch through to confirm the output shape.

  3. Exercise 3hard

    Speed up CPU transfer learning by computing frozen ResNet-18 features once for all training and validation images, saving them, and training a logistic-regression-style head on the saved features.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

What is ImageNet?
A large labelled image dataset whose 1,000-class subset is the standard for pretraining vision models. Models trained on it learn general visual features that transfer well to other tasks.
How many images do I need for transfer learning?
Often a few hundred per class is enough for a frozen backbone to give a useful result, though more varied data always helps. Training from scratch typically needs far more.
Are CNNs outdated now that vision transformers exist?
No. CNNs remain efficient, strong and easy to run on CPUs and phones. Vision transformers shine with very large datasets, and many practical systems still use CNN backbones.

Go deeper

ShareXLinkedInWhatsApp