Skip to main content
LearnMLAcademy
Advanced10 min read

Transfer Learning and Fine-Tuning

Adapt pretrained deep vision and language models to downstream tasks with LoRA, with sequence diagrams, attention calculations, and model-code exercises.

What you will master in this lesson
Intuitive core mechanisms & practical real-world intuition
Step-by-step mathematical breakdown & visual diagrams
Runnable Python implementation & practical trade-offs

Deep Learning · Transfer Learning

Learn how to reuse a pretrained model, replace its old task-specific head, freeze or unfreeze layers deliberately, and fine-tune with learning rates that protect useful representations.

Why Reuse a Model?

A factory may have only 800 labelled product images—far too few to teach a large vision model every useful edge, texture and shape from scratch. A model pretrained on a much larger image collection already contains weights that respond to many visual structures. Transfer learning asks whether those representations can help the factory task.

The pretrained model is the source model; your new labelled problem is the target task. The reusable part is usually called a backbone or encoder. Its old classifier head is removed because its labels do not match yours.

Transfer learning keeps useful representations and replaces the old decision

source pretraining

many general images

old labels: 1,000 classes

→

pretrained backbone

block 1

edges

block 2

textures

block 3

parts

block 4

shapes

reusable weights

→

new task head

normal / scratch / crack

target factory data

The old classifier is task-specific and is replaced. Earlier representations may transfer because visual edges and shapes remain useful, but usefulness depends on similarity between source and target data.

Feature Extraction and Fine-Tuning Are Different

Train from scratch

Initialize backbone and head randomly; update everything.

Useful comparison when target data is large or unlike pretraining.

Fixed feature extractor

Freeze the backbone; train only the new head.

Fast, memory-efficient baseline for small similar datasets.

Fine-tuning

Start from pretrained weights; update some or all backbone layers.

Adapts features, but increases overfitting and forgetting risk.

Freezing means a parameter is excluded from gradient updates. It does not delete the parameter, and it does not necessarily control every layer's train/evaluation behavior. Dropout and normalization state still require deliberate mode handling.

Use a Staged Training Plan

First train the new random head while the backbone stays stable. Once the head maps pretrained features to target labels reasonably, unfreeze later blocks and continue at a smaller rate. This avoids sending large, noisy gradients from an untrained head through useful pretrained layers on the first update.

Fine-tuning is a controlled sequence, not one switch

Stage 1 · establish baseline

backbone: frozen

head: train

Learn the new head without disturbing pretrained features

Stage 2 · partial fine-tuning

backbone: early blocks frozen; later blocks train

head: train

Adapt higher-level features with a smaller learning rate

Stage 3 · optional full fine-tuning

backbone: all train, often at very small rates

head: train

Attempt deeper domain adaptation only if validation supports it

Stop at whichever stage gives the best held-out result under your compute budget. Full fine-tuning is optional, not the definition of success.

Target size and domain similarity guide the first experiment

Similar data · few labels

Freeze most layers; train a small head

Similar data · many labels

Fine-tune later blocks, then compare full fine-tuning

Different data · few labels

Transfer may be weak; use augmentation/self-supervision and cautious fine-tuning

Different data · many labels

Compare pretrained initialization with training from scratch

This is a starting heuristic. Measure on the actual target split: negative transfer can occur when pretrained features or normalization assumptions do not fit the new domain.

Why the Backbone Usually Needs a Smaller Learning Rate

Every trainable weight still follows the optimizer's update rule. For plain SGD, wnew=w−ηg. The gradient g is calculated by backpropagation from the current batch; learning rate η is chosen by the developer. Multiplying them gives the update size, and subtracting moves the weight in the direction that locally reduces loss. Different parameter groups can use different η values.

Same gradient, different movement

For comparison, manually use the same illustrative gradient g=0.2 for one pretrained backbone weight and one new head weight. The two learning rates are example hyperparameters, not prescriptions.

Backbone η=0.00001
change = ηg
= 0.00001×0.2
= 0.000002

New head η=0.001
change = ηg
= 0.001×0.2
= 0.0002

Interpretation: the new head moves 100 times farther in this example. The backbone can adapt gradually instead of immediately overwriting its features.

Discriminative learning rates protect general features

early backbone

η = 0 or 10⁻⁵

general features

late backbone

η = 10⁻⁴

adaptable task features

new head

η = 10⁻³

randomly initialized

These rates are illustrative, not universal defaults. A newer random head often needs larger movement; pretrained layers usually need smaller updates.

Preprocessing Is Part of the Pretrained Model

Pretrained weights expect the channel order, resize/crop policy and normalization used during source training. A model may compile with incorrect preprocessing yet receive a distribution unlike anything it learned. Use the transform bundled with the weight object and save it with deployment code.

BatchNorm needs special attention

BatchNorm has learned affine parameters and running statistics. Freezing parameters does not make every framework's training/evaluation semantics identical. With small target batches, updating running statistics can damage predictions. Keep the intended mode explicit and verify running-stat behavior when unfreezing.

A Two-Stage PyTorch Workflow

This example adapts a pretrained ResNet-18 to three defect classes. The weight object supplies matching image transforms. Stage 1 trains only the replacement head. Stage 2 unfreezes the last residual block and rebuilds the optimizer with smaller backbone learning rate.

staged_transfer_learning.py
import torch
from torch import nn
from torchvision.models import resnet18, ResNet18_Weights

weights = ResNet18_Weights.DEFAULT
preprocess = weights.transforms()  # use for train/validation input baseline
model = resnet18(weights=weights)

# Replace the 1,000-class ImageNet head with three target classes.
in_features = model.fc.in_features
model.fc = nn.Linear(in_features, 3)

# Stage 1: freeze backbone, train the new head.
for parameter in model.parameters():
    parameter.requires_grad = False
for parameter in model.fc.parameters():
    parameter.requires_grad = True

optimizer = torch.optim.AdamW(model.fc.parameters(), lr=1e-3)
# ... run training/validation epochs here ...

# Stage 2: adapt the final backbone block carefully.
for parameter in model.layer4.parameters():
    parameter.requires_grad = True

# Rebuild optimizer so newly unfrozen parameters are included.
optimizer = torch.optim.AdamW([
    {"params": model.layer4.parameters(), "lr": 1e-5},
    {"params": model.fc.parameters(), "lr": 1e-4},
], weight_decay=1e-4)

# Confirm exactly what can update.
trainable = [name for name, p in model.named_parameters() if p.requires_grad]
print("trainable parameter tensors:", len(trainable))
print(trainable[:5])

What is reused and what is new?

DEFAULT selects a versioned pretrained-weight recipe; weights.transforms() returns its expected resizing and normalization. in_features is read from ResNet's existing head, while output size 3 comes from the target labels. PyTorch randomly initializes that replacement head.

Why rebuild the optimizer?

requires_grad=False prevents backbone gradients and updates in stage 1. After layer4 is unfrozen, the old optimizer still contains only head parameters; rebuilding it includes the newly trainable tensors and gives backbone and head separate, chosen learning rates.

Training augmentation can be added around the required normalization while validation remains deterministic. Evaluate the frozen-head baseline before stage 2; continue only if target validation improves.

How Much Should You Unfreeze?

SituationFirst experimentWhat to compare next
Very small target set, similar imagesFreeze backbone; regularized linear headUnfreeze only last block with early stopping
Moderate target set, noticeable domain shiftHead first, then later blocksGradual/full fine-tuning at smaller rates
Large target set, related domainPretrained full fine-tuningScratch baseline under equal compute
Medical/satellite/thermal data unlike sourceTest transfer, but expect mismatchDomain-specific/self-supervised pretraining
Latency-constrained deploymentPretrained compact backboneDistillation, pruning/quantization and device benchmarks
Text task with large language modelHead, adapters or low-rank updatesFull fine-tuning only with sufficient data/compute

Negative Transfer: When Reuse Hurts

Negative transfer means pretrained initialization performs worse than a reasonable alternative because source features or biases do not match the target. Natural-image pretraining may still help medical images, but it is not guaranteed; text pretraining in one language or domain may tokenize and represent another poorly.

Run a scratch baseline

Use the same split, augmentation, budget and selection rule.

Inspect the domain gap

Compare channels, resolution, vocabulary, label meaning and data collection.

Try closer pretraining

In-domain supervised or self-supervised pretraining may transfer better than a famous generic checkpoint.

Common Transfer-Learning Mistakes

SymptomLikely mistakeCorrection
Accuracy collapses when fine-tuning beginsLearning rate too high or random head destabilizes backboneTrain head first; reduce backbone rate; unfreeze gradually
Unfrozen layer never changesOptimizer was created before unfreezing and excludes itRebuild optimizer or add a parameter group; compare weights before/after
Validation changes when batch size changesNormalization statistics/mode are unstableControl train/eval mode; inspect BatchNorm running statistics
Model compiles but performs poorlyWrong resize, channel order or normalizationUse transforms paired with exact weight version
Great random-split score, poor production scoreDuplicate/user/time leakageSplit by deployment unit and remove near duplicates
Large model overfits within a few epochsToo much capacity for target labelsFreeze more, regularize head, augment and stop earlier
Checkpoint cannot be reproducedModel, weights, tokenizer/transform and labels not versionedSave exact identifiers, preprocessing, class map and configuration

A Transfer Experiment Must Answer More Than Accuracy

Compare validation quality, per-class errors, calibration, training time, memory and inference latency. Record the best checkpoint by a target metric rather than the last epoch. If labels are scarce, repeat across seeds or folds where appropriate because a single split can make one strategy look better by chance.

Also review the source model's licence, training-data documentation and intended use. Transfer carries source biases and limitations along with useful features.

A Reliable Transfer-Learning Checklist

  1. Check whether source data and the target domain are related enough to make reuse plausible.
  2. Use the exact preprocessing paired with the selected checkpoint.
  3. Measure a frozen-backbone baseline before gradually unfreezing later blocks.
  4. Use a smaller learning rate for pretrained weights than for the new head.
  5. Compare against a fair scratch baseline and inspect negative transfer.
  6. Save the class map, preprocessing, weight version and best validation checkpoint.
Next step: transfer learning starts from existing labelled pretraining. The next lesson asks what to do when your own domain contains abundant unlabelled data or a new class arrives with only a few labelled examples.

Continue Learning

Apply this concept in a real hands-on project

You have studied the idea. Now use it in working Python code, see the calculation and output, and explain what changed. Each project includes step-by-step instructions, full source and tests.

Practice challenge: predict an outcome first, run the code, and explain the difference.

Track Your Progress0% curriculum done

Finished "Transfer Learning and Fine-Tuning"?

Mark this lesson as completed to update your progress bar and track your milestones across the full curriculum.

Overall Progress0 / 167 lessons

Was this tutorial helpful?

Your feedback helps us continuously refine and improve our open-access tutorials.

Summary / Key Takeaways

  • Transfer learning reuses representations learned on a source task.
  • A new head matches the target labels.
  • Freezing protects the backbone while the head starts training.
  • Staged fine-tuning unfreezes layers with a smaller learning rate.
  • Inputs must follow the checkpoint's preprocessing contract.
  • Validate domain mismatch, forgetting, overfitting, latency, and licensing.

Knowledge Check

Progress: 0/5

Test your active recall. Choose one answer for each question, then check it to reveal the step-by-step reasoning.

Question 1 of 5conceptual
What is the pretrained backbone used for?
Question 2 of 5conceptual
Why replace the original classifier head?
Question 3 of 5practical selection
What is a sensible first stage with a small target dataset?
Question 4 of 5interpretation
Why use a smaller learning rate when unfreezing?
Question 5 of 5debugging/diagnostic
Validation worsens immediately after unfreezing. What should be checked?

Knowledge Check Review & Explanations

Review the questions, verified correct answers, and conceptual explanations for this lesson.

1What is the pretrained backbone used for?▼

Correct Answer: Reusable feature extraction

The backbone carries representations learned from a larger source dataset.

2Why replace the original classifier head?▼

Correct Answer: The target task has its own label set

The new output layer must produce the number and meaning of classes required by the target task.

3What is a sensible first stage with a small target dataset?▼

Correct Answer: Freeze the backbone and train the new head

Freezing protects useful source features while the randomly initialized head learns the new mapping.

4Why use a smaller learning rate when unfreezing?▼

Correct Answer: To avoid rapidly destroying pretrained features

Large updates can cause catastrophic forgetting of useful representations.

5Validation worsens immediately after unfreezing. What should be checked?▼

Correct Answer: Learning rate, number of unfrozen layers, and domain fit

Instability after unfreezing commonly comes from aggressive updates or a mismatched fine-tuning strategy.

Keep moving through the path

Continue Learning

Free Download: ML Interview Cheatsheet

100 essential Machine Learning interview questions and answers covering foundations, algorithms, evaluation, deep learning, Python, system design and interview strategy. Enter your email to download it instantly.

Optional Learning Resources

These resources may complement the lesson. They are optional and are not required to use ML Academy.

As an Amazon Associate I earn from qualifying purchases. Other links are identified separately when they are not affiliate links.

Next