Skip to main content
LearnMLAcademy
Intermediate10 min read

Image Classification with Transfer Learning

Train an image classifier from scratch using transfer learning with ResNet, with reproducible setup, model evaluation, and an end-to-end project task.

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

1. Project Goal

Adapt a pretrained image backbone to classify ten small image categories, then diagnose class-specific errors and overfitting rather than treating one accuracy number as the project result.

2. What You Will Build

CIFAR-10 train/validation/test loaders with train-only augmentation
A pretrained ResNet-18 feature extractor and new ten-class head
Frozen-head training followed by optional staged fine-tuning
Learning curves, confusion matrix, inference and saved model contract

3. Skills / Prerequisites

Review unfamiliar foundations before implementing the project. Each link points to an existing lesson used by the workflow.

4. Dataset or Inputs

CIFAR-10 contains 32×32 RGB images in ten classes. torchvision provides 50,000 training and 10,000 test images, small enough for a teaching project. Split validation from the official training set; do not tune on the official test labels.

Understand every project input

Understand every project input
Tensor / labelShape or valueOrigin
One image3 × 32 × 323 color channels, height 32, width 32
Training batch32 × 3 × 32 × 32Batch size 32 chosen by developer
Logits32 × 10Model output: one score per class for each image
Labelinteger 0–9Dataset class index
Augmentationcrop + horizontal flipRandomly applied only to training images

5. Architecture / Workflow

Create separate training, validation and test datasets.

Normalize all splits consistently but augment training only.

Load pretrained weights, freeze the backbone and replace the classification head.

Train the head, inspect curves, then optionally unfreeze a late block with a smaller learning rate.

Project figure

Transfer learning reuses visual features and replaces the task head

Which parameters begin pretrained, frozen and newly initialized?

32×32×3 image
CIFAR-10 tensor
Pretrained backbone
general edges → shapes
Frozen features
no update in stage 1
New head
10 output logits
Fine-tune
small learning rate
The backbone begins with pretrained weights. A new ten-class head starts randomly initialized; train it first, then optionally unfreeze only later backbone blocks with a smaller learning rate.

6. Environment / Dependencies

  • Python 3.10+
  • PyTorch and torchvision
  • scikit-learn for confusion matrix
  • CPU works for the small tutorial; GPU shortens training

7. Data or Input Understanding

A pixel tensor is numerical input, not a photograph to the model. Normalization uses fixed channel statistics, while augmentation creates plausible training variations.

Keep validation deterministic. Random validation crops would make the metric change because of evaluation noise rather than model quality.

8. Baseline / Simplest Working Approach

Before transfer learning, record chance accuracy (10%) and a small CNN or majority baseline. Transfer learning should justify its extra complexity by faster convergence or better validation results.

Stage 1 updates only the new head. Stage 2 unfreezes a small late portion of the backbone, uses a learning rate such as 1e−4, and stops if validation degrades.

Project figure

Training and validation curves diagnose learning

What does the widening gap after epoch 5 mean?

training lossvalidation lossepoch
Training loss continues down while validation loss turns upward. That gap is evidence of overfitting and a reason to stop, regularize or strengthen augmentation.

Worked Example: Count the new classification-head parameters

Given: ResNet-18 produces 512 features per image. CIFAR-10 needs 10 output logits. A linear head has a 512×10 weight matrix and 10 bias values.

  1. 1Weight values = 512 × 10 = 5,120.
  2. 2Bias values = 10, one for each class.
  3. 3Total trainable head parameters = 5,120 + 10 = 5,130.
  4. 4With the backbone frozen, these 5,130 values are the only parameters updated in stage 1.

Interpretation: The pretrained backbone supplies general visual features; the small new head learns how those features map to CIFAR-10 classes.

9. Step-by-Step Implementation

Step 1: Load images with split-specific transforms

Only training uses random crop and flip. Evaluation uses the same fixed normalization without randomness.

Load images with split-specific transformsRUNNABLE CODE
import torch
from torch import nn
from torch.utils.data import DataLoader, Subset
from torchvision import datasets, models, transforms

train_tfms = transforms.Compose([
    transforms.RandomCrop(32, padding=4),
    transforms.RandomHorizontalFlip(),
    transforms.ToTensor(),
    transforms.Normalize((0.491, 0.482, 0.447), (0.247, 0.243, 0.262)),
])
eval_tfms = transforms.Compose([
    transforms.ToTensor(),
    transforms.Normalize((0.491, 0.482, 0.447), (0.247, 0.243, 0.262)),
])
augmented = datasets.CIFAR10("data", train=True, download=True, transform=train_tfms)
evaluation_copy = datasets.CIFAR10("data", train=True, download=False, transform=eval_tfms)
test_set = datasets.CIFAR10("data", train=False, download=True, transform=eval_tfms)

generator = torch.Generator().manual_seed(42)
indices = torch.randperm(len(augmented), generator=generator).tolist()
train_set = Subset(augmented, indices[:45_000])
validation_set = Subset(evaluation_copy, indices[45_000:])
train_loader = DataLoader(train_set, batch_size=32, shuffle=True)
validation_loader = DataLoader(validation_set, batch_size=64)
test_loader = DataLoader(test_set, batch_size=64)

Step 2: Replace and train the head

Cross-entropy converts the 10 logits and true labels into one loss. backward computes gradients; step updates only parameters with requires_grad=True.

Replace and train the headRUNNABLE CODE
model = models.resnet18(weights=models.ResNet18_Weights.DEFAULT)
for parameter in model.parameters():
    parameter.requires_grad = False

# ResNet-18 supplies 512 input features; CIFAR-10 has 10 classes.
model.fc = nn.Linear(512, 10)
optimizer = torch.optim.AdamW(model.fc.parameters(), lr=1e-3)

for images, labels in train_loader:
    optimizer.zero_grad()
    logits = model(images)
    loss = nn.functional.cross_entropy(logits, labels)
    loss.backward()
    optimizer.step()

Step 3: Fine-tune conservatively

Unfreeze the last residual block only after the head has learned. A smaller learning rate protects reusable pretrained features.

Fine-tune conservativelyRUNNABLE CODE
for parameter in model.layer4.parameters():
    parameter.requires_grad = True
optimizer = torch.optim.AdamW(
    [p for p in model.parameters() if p.requires_grad], lr=1e-4
)

Step 4: Save an inference contract

Save class names and normalization alongside weights so inference reproduces training-time preparation.

Save an inference contractRUNNABLE CODE
torch.save({
  "state_dict": model.state_dict(),
  "classes": train_set.classes,
  "mean": (0.491, 0.482, 0.447),
  "std": (0.247, 0.243, 0.262),
}, "cifar10_resnet18.pt")

10. Expected Results / Outputs

Read the output as evidence, not decoration

Read the output as evidence, not decoration
StageTrain accuracyValidation accuracyInterpretation
Chance10%10%Ten equally likely classes
Frozen head78%74%Pretrained features transfer
Late-block fine-tune86%79%Useful gain with a growing generalization gap

11. Evaluation

Track training and validation loss/accuracy each epoch. Select the checkpoint with the best validation objective, then evaluate the untouched test set once.

A confusion matrix exposes class-specific errors. Inspect misclassified images: cat/dog confusion may reflect pose and background; truck/car errors may reflect scale. Confirm whether labels are correct before changing the model.

Project figure

A confusion matrix exposes class-specific image errors

Which classes does the model confuse even when overall accuracy looks reasonable?

Predicted Cat
Predicted Dog
True Cat
38
correct
12
error
True Dog
9
error
41
correct
Rows are true classes and columns are predicted classes. The off-diagonal cat→dog and truck→car cells show where more representative examples or targeted augmentation may help.

12. Failure Analysis

Failure mode → diagnosis → response

Failure mode → diagnosis → response
Observed failureLikely causeNext action
Validation loss risesOverfitting after several epochsEarly stop, augment, regularize or freeze more
Both curves flatBad learning rate or frozen headCheck trainable parameters and gradients
One class has poor recallImbalance or visual ambiguityInspect examples and class counts
Inference mismatchDifferent normalization/class orderLoad the saved preprocessing contract

13. Improve the Project

Use class-balanced sampling only if training counts justify it.
Tune augmentation to plausible CIFAR-10 changes; do not flip classes where orientation matters.
Compare a small native CNN against transfer learning on speed and accuracy.
Calibrate probabilities and add an abstention threshold for uncertain images.

14. Production Considerations

What changes beyond the notebook

What changes beyond the notebook
AreaProduction requirement
ArtifactWeights, architecture, class order, transforms and version
ServingValidate image type/size; batch when latency permits
MonitoringClass mix, confidence, drift, class recall and corrupt uploads
SafetyDo not extend toy performance claims to medical or high-stakes imagery

15. Summary / Key Takeaways

  • Image classification maps a numeric image tensor to class scores, not directly to a human-readable label.
  • Training, validation and test images serve different purposes and must remain separate.
  • Augmentation belongs only in training; normalization must be reproduced consistently everywhere.
  • Transfer learning freezes reusable pretrained features and begins with a newly initialized task head.
  • Staged fine-tuning uses a smaller learning rate and validation evidence to avoid damaging useful features.
  • Learning curves and confusion matrices expose overfitting and class-specific errors hidden by overall accuracy.
  • A deployable image model includes transforms, class order, weights, versioning and monitoring—not only a checkpoint file.

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 "Image Classification with Transfer Learning"?

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.

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
Why must random augmentation be excluded from the validation transform?
Question 2 of 5numerical/formula
A linear head maps 512 features to 10 classes. Including bias, how many parameters does it have?
Question 3 of 5interpretation
What is updated during the first frozen-backbone training stage?
Question 4 of 5debugging/diagnostic
Training loss keeps falling while validation loss rises after epoch 5. What is the best next action?
Question 5 of 5application/scenario
Which artifact is required for correct inference in addition to weights?

Knowledge Check Review & Explanations

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

1Why must random augmentation be excluded from the validation transform?▼

Correct Answer: It would make evaluation change with random crops/flips instead of only model behavior

Validation should be a stable measurement. Random transforms inject evaluation noise and can hide real changes.

2A linear head maps 512 features to 10 classes. Including bias, how many parameters does it have?▼

Correct Answer: 5,130

Weights = 512×10 = 5,120 and biases = 10, so total parameters are 5,130.

3What is updated during the first frozen-backbone training stage?▼

Correct Answer: Only the newly replaced classification head

requires_grad is false for backbone parameters, so gradients update only the new head.

4Training loss keeps falling while validation loss rises after epoch 5. What is the best next action?▼

Correct Answer: Treat it as overfitting and consider early stopping or regularization

The widening gap is a classic overfitting signal. Select the best validation checkpoint and change regularization or augmentation if needed.

5Which artifact is required for correct inference in addition to weights?▼

Correct Answer: Class order and image normalization contract

Inference must reproduce preprocessing and map output indices to the same class names used during training.

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.

Next