AI State of the Art
Fundamentals/Deep Learning: Fundamental Architectures/23 min
Section 19

Transfer Learning in Vision: Fine-tuning Pre-trained Models

Listen as a podcast →

The genius of transfer learning

Imagine: you learn to play the piano for 10 years. Then you're asked to learn the accordion. You don't start from scratch. You don't relearn how to read sheet music, keep time, or coordinate your hands. You reuse all of that, and you only learn what's specific to the accordion: the bellows, the button layout.

Transfer learning in AI follows exactly the same principle. A model trained on ImageNet spent days of GPU (Graphics Processing Unit) computation learning universal visual representations: what an edge is, a texture, a shape, a spatial composition. Rather than throwing away all that knowledge and starting over for each new problem, you reuse that knowledge and only specialize the final part of the model. Even if you only have 100 photos for your task, you inherit the work done on a million images.

Why ImageNet is the magical starting point

ImageNet is the dataset that launched the deep learning revolution in vision. Two figures not to be confused, both published by the ImageNet team:

  • the full dataset holds roughly 14 million images across more than 20,000 categories;
  • the subset used for the annual competition, ILSVRC (ImageNet Large Scale Visual Recognition Challenge), holds 1.2 million training images across 1,000 categories.

It is almost always this second, smaller subset that pre-trains the models you will download. Dogs, cars, plants, tools, food, a very broad sample of the visual world.

A CNN (convolutional network, see CNN: seeing with convolutions) trained on ImageNet develops a hierarchy of representations:

  • Low layers (close to the image): edge detectors, contrast detectors, simple textures. These filters are nearly universal, they work just as well on cat photos as on medical X-rays or satellite images.
  • Middle layers: combinations of textures, repeating patterns, basic geometric shapes.
  • High layers (close to the output): specific object shapes, face parts, fine textures specific to natural images. These representations are more domain-specific to ImageNet.

When you want to solve a problem like "recognizing flower species", the CNN already knows what petals, colors, and organic shapes are. All that's left is to teach it "this combination of petals + this color = tulip, this other one = rose".

Why it works so well

Low-level visual features (edges, textures, contrasts) are identical regardless of the domain. Whether you're looking at handwritten digits, tree leaves, or Martian rocks, edges are still edges. Only the high layers (which combine these primitives into specific concepts) change from one domain to another. Transfer learning exploits this natural hierarchy of vision.

Diagram of transfer learning in computer vision
The image illustrates how the convolution layers of a network pre-trained on ImageNet (object recognition) can be reused for a medical task (lesion classification). Only the final layers are adapted to the new task.Source : toloka.ai

Strategy 1: Feature Extraction

This is the simplest and fastest approach. You use the pre-trained model as a frozen feature extractor, without modifying its weights: they stay exactly as ImageNet training left them.

Concrete procedure:

  1. Load a model like ResNet-50 pre-trained on ImageNet
  2. Freeze all weights: no gradient flows through the pre-trained model
  3. Remove the last classification layer (the one that classified into 1,000 ImageNet categories)
  4. Add a new dense layer adapted to your problem: for example, 2048 inputs -> 5 outputs if you have 5 classes
  5. Train only this new layer

Concretely, the pre-trained model turns each image into a vector of 2048 numbers (for ResNet-50). This vector summarizes everything the model "sees" in the image. You then train a simple logistic regression on these vectors. It's very fast (only one layer to train), requires very little data (few parameters = low risk of overfitting), and gives excellent results when your task is reasonably close to ImageNet.

Speed trick: pre-computing features

Instead of passing each image through the CNN at every training epoch (an "epoch" = one full pass over your data), you can pre-compute the features of all your images once and save them. Then you train your final layer on those already-computed vectors. The gain is easy to reason about: if you train for 50 epochs, the images go through the big network once instead of 50 times, and what remains is one tiny matrix multiplication. The exact factor depends on the model and the hardware, the order of magnitude is the number of epochs.

Strategy 2: Fine-tuning

Instead of locking the model, you progressively "unfreeze" its weights so it adapts to your specific data. The model is no longer a passive extractor, it actively specializes on your domain.

Procedure:

  1. Load ResNet-50 pre-trained, replace the classification layer
  2. Unfreeze the weights: reactivate gradients on all layers (or a subset)
  3. Train the complete model, but with a very low learning rate (the size of the correction step applied to the weights at each update)

Why such a low learning rate? Because the pre-trained weights are already close to a good solution. Too large a step would eject them from this favorable zone, destroying the acquired knowledge. A very small step delicately adjusts them toward your task. As an order of magnitude: training from scratch runs around 10⁻² or 10⁻³, fine-tuning around 10⁻⁵ to 10⁻⁴, a hundred to a thousand times less.

Progressive fine-tuning in two phases

The best approach is often a gradual unfreezing:

Phase 1: low layers stay frozen, you train only the high layers and the new classification layer. Standard learning rate. You let the model learn the new categories.

Phase 2: you unfreeze all layers and train the complete model with a very low learning rate. The low layers subtly adjust to your domain.

Even better: discriminative learning rates. The idea is to apply a different learning rate depending on the layer depth. Layers close to the output (to be strongly adapted) receive a higher LR. Base layers (to be preserved) receive a much lower LR. You can typically divide the LR by 10 at each "group" of layers going back toward the input.

Choosing your strategy: the decision matrix

The choice between feature extraction and fine-tuning depends on two factors: the size of your dataset and the similarity to ImageNet.

Small dataset + task similar to ImageNet

Example: 200 photos of dog breeds. The model already knows dogs; it has learned perfectly adapted features. Feature extraction is the optimal choice. With so little data, fine-tuning would risk overfitting.

Large dataset + similar task

Example: 50,000 photos of bird species. You have enough data to specialize the model without risk of overfitting. Full fine-tuning: the model will learn the fine nuances between species (beak shape, feather patterns, etc.).

Small dataset + different task

Example: 500 chest X-rays. The images are visually very different from ImageNet. But the low layers (edges, contrasts, textures) remain useful. Feature extraction on low layers only: you keep the universal filters and replace everything specific to natural images.

Large dataset + very different task

Example: thousands of satellite images or microscope images. The domain is radically different from ImageNet. Consider aggressive fine-tuning (less conservative learning rate) or even training from scratch if you have enough data. ImageNet representations can introduce more noise than useful signal in these extreme cases.

Rule of thumb: always try transfer learning first

Starting from a pre-trained model costs a few minutes, and it works even when the domain looks far from ImageNet: low-level representations (edges, contrasts, local textures) apply to almost all images. So always try transfer learning before diving into training from scratch. Worst case, you lose half an hour.

Best practices for success

Input normalization

A crucial point often overlooked: your images must be normalized exactly like ImageNet. The model learned its filters on a certain distribution of pixel values. If you feed it differently normalized images, its filters react to patterns that don't exist. The reference values used for torchvision's pre-trained models are a mean of [0.485, 0.456, 0.406] and a standard deviation of [0.229, 0.224, 0.225] for the red, green and blue channels: subtract the mean and divide by the standard deviation, channel by channel.

Input size

Each model expects the image size it was trained on: 224x224 for ResNet and for most Vision Transformers, 299x299 for Inception, and 384x384 for the Vision Transformer variants fine-tuned at high resolution. Resize or center-crop without squashing the proportions.

Data augmentation

Essential when you have little data. Light rotations (5-10 degrees), horizontal flips, random crops, color variations (brightness, contrast, saturation). Each transformation artificially creates a new training example, which reduces overfitting.

Choice of base model

  • ResNet-50: the solid default choice. Good everywhere, well understood, fast.
  • EfficientNet: designed in 2019 precisely to optimize the accuracy-to-compute ratio; useful when the compute budget is tight.
  • ViT (Vision Transformer): excellent performance when pre-training was done on a lot of data, but not robust on a small dataset if the pre-training isn't a good match.

Key settings

  • Learning rate: on the order of 10⁻⁵ to 10⁻⁴ for fine-tuning, a hundred to a thousand times less than training from scratch
  • Batch size (the number of images processed before each weight update): as large as your GPU memory allows, since a gradient averaged over more examples is less noisy
  • Early stopping: monitor the loss on validation data and stop as soon as it rises, a sign the model is starting to overfit
Transfer learning is everywhere today

What we're doing here in vision has become the normal way to proceed across all of AI. In NLP (Natural Language Processing), BERT and GPT are pre-trained on huge text corpora, then specialized on precise tasks. In audio, Whisper was pre-trained on 680,000 hours of speech, the figure its paper reports. The principle is always the same: pre-train on a massive corpus to learn universal representations, then specialize with little data. Vision showed the way.

One development worth knowing: on large language models nobody retrains all the weights any more, even at a low learning rate, it is too expensive. Instead you insert small trainable matrices alongside the frozen weights, see LoRA.

Practical tools

PyTorch provides torchvision.models with all the classics pre-trained. Hugging Face transformers offers the same for Vision Transformers. In practice a few lines are enough to get started. The order of operations matters: freeze the whole network first, then replace the classification head, otherwise you would freeze the very layer you want to train.

from torchvision import models
import torch.nn as nn

# weights pre-trained on ImageNet
model = models.resnet50(weights="IMAGENET1K_V2")

# 1. freeze the whole network
for p in model.parameters():
    p.requires_grad = False

# 2. replace the head: its weights are new, hence trainable by default
model.fc = nn.Linear(2048, num_classes)

# only the parameters of model.fc will be updated

Transfer learning is exactly that: a giant pre-training done by others, a surgical fine-tuning done by you. You benefit from someone else's million images and days of GPU computation without paying the cost.

Check your understanding0 / 5

1. You often read that ImageNet holds 14 million images. What were the pre-trained models you download almost always trained on?

2. Why can a model trained on cats and cars help analyze chest X-rays?

3. Why is fine-tuning done with a learning rate a hundred to a thousand times lower than training from scratch?

4. You have 200 photos of dog breeds to classify. Which strategy should you pick?

5. In the code, why must you freeze the whole network BEFORE replacing the classification head, and not the other way around?