Skip to content
mentoor

Topic 5 of 5 · 5 min read

Transfer learning from pretrained models

Goal: Fine-tune a pretrained image or text model on a small dataset and decide which layers to freeze.

Transfer learning starts from a model already trained on a large dataset and adapts it to your task, so a few hundred labelled examples can be enough where training from scratch would need far more. The early layers already know edges, shapes or word patterns; you teach only what is specific to your problem.

Check yourself · 1 of 3

What is the main benefit of starting from a pretrained model?

Choose one answer

Why it matters

Labelled data is usually the scarce resource. A pretrained backbone, such as a ResNet or ViT for images or a BERT-style encoder for text, carries general features that transfer. You save data, compute and time, and you usually get a better result.

How to do it

  1. Pick a backbone pretrained on data close to yours, and load its weights.
  2. Replace the head. Swap the final layer for one with your number of classes.
  3. Freeze the backbone and train only the new head. This is fast and works with very little data.
  4. Optionally unfreeze the last blocks and continue with a much smaller learning rate, often a tenth or less of the head's. Early layers stay frozen longest because they hold the most general features.
  5. Match the preprocessing the backbone was trained with: input size, normalisation and tokenizer.
  6. Evaluate on held-out data you never trained on.

Before and after

Weak: new head and backbone trained together at the head's learning rate on 300 images.

import torch
import torchvision

model = torchvision.models.resnet18(weights="DEFAULT")
model.fc = torch.nn.Linear(model.fc.in_features, 4)
opt = torch.optim.Adam(model.parameters(), lr=1e-2)  # destroys pretrained weights

Better: freeze the backbone, train the head, and only then consider a gentle unfreeze.

model = torchvision.models.resnet18(weights="DEFAULT")
for p in model.parameters():
    p.requires_grad = False
model.fc = torch.nn.Linear(model.fc.in_features, 4)  # new layer is trainable
opt = torch.optim.Adam(model.fc.parameters(), lr=1e-3)

The PyTorch transfer learning tutorial shows both variants: a frozen feature extractor and full fine-tuning.

How much to unfreeze

The closer your data is to the pretraining data, the less you need to change. A small, similar dataset: train the head only. A larger or very different dataset, such as medical scans: unfreeze more layers.

What goes wrong

  • A high learning rate wipes out pretrained weights in the first epochs.
  • Skipping the model's own normalisation, so inputs look unlike what it saw in pretraining.
  • Evaluating on images that also appear in training, which hides overfitting.
  • Forgetting that batch-norm layers in a frozen backbone still update unless set to eval mode.

Examples

Four classes, 300 images

A team classifies four kinds of crop disease from 300 leaf photos. They load a pretrained ResNet, swap the final layer for four outputs, freeze everything else and train for a few epochs. Validation accuracy is checked on 60 photos kept aside before any training.

A text version

For support-ticket routing with 500 labelled tickets, load a pretrained encoder, add a classification head with one output per queue and fine-tune with a small learning rate such as 2e-5. Use the model's own tokenizer, not a custom one.

Key points

  • A pretrained backbone carries general features, so a small labelled dataset can be enough to adapt it.
  • Replace the final layer to match your classes, freeze the backbone, and train the new head first.
  • When unfreezing layers, use a learning rate far lower than the head's and unfreeze from the top down.
  • Use the same input size, normalisation or tokenizer the backbone was trained with.
  • Always evaluate on held-out data that was never used in training or tuning.

Common mistakes

  • Training the whole network at a high learning rate and wiping out the pretrained features.
  • Skipping the backbone's expected preprocessing, so inputs differ from what it learned on.
  • Leaving duplicates or near-duplicates across the train and validation sets, which inflates scores.
  • Unfreezing everything on a tiny dataset, where the head alone would have generalised better.

Check yourself · 2 of 3

You fine-tune a pretrained ResNet on 300 images and accuracy collapses in epoch one. What is the likeliest cause?

Choose one answer

Check yourself · 3 of 3

You have 200 labelled photos very similar to the pretraining data. Which plan is best to try first?

Choose one answer

Practice items, not counted towards your mastery.

Start here

More for this topic