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
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
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?
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?
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.
- 1Weight values = 512 × 10 = 5,120.
- 2Bias values = 10, one for each class.
- 3Total trainable head parameters = 5,120 + 10 = 5,130.
- 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.
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.
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.
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.
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
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?
12. Failure Analysis
Failure mode → diagnosis → response
13. Improve the Project
14. Production Considerations
What changes beyond the notebook
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.