30 Mins

5. Transfer Learning for Computer Vision

Introduction to Transfer Learning Principles

Transfer learning is the cornerstone of modern computer vision, predicated on the observation that early layers in a deep convolutional neural network (CNN) act as generic feature extractors (Gabor filters, color blobs), while deeper layers represent task-specific semantic features. By leveraging models pre-trained on massive datasets like ImageNet, we initialize our networks with weights that have already learned to represent universal visual hierarchies.

This methodology significantly mitigates the risk of overfitting when working with small datasets, as the model starts from a sophisticated feature space rather than random initialization. The core philosophy is to treat the backbone as a frozen 'feature extractor' or a base for adaptation, which drastically reduces the computational cost and the required amount of labeled training data for specific downstream tasks.

Operator Note: Always ensure the normalization statistics (mean/std) used during inference match the values used when the base model was originally trained on ImageNet.
Python 3
import torch
import torchvision.models as models

# Load a ResNet18 model pre-trained on ImageNet
model = models.resnet18(pretrained=True)

# Freeze all parameters in the backbone to use as a feature extractor
for param in model.parameters():
    param.requires_grad = False

# Replace the final fully connected layer for a new 10-class problem
num_ftrs = model.fc.in_features
model.fc = torch.nn.Linear(num_ftrs, 10)

# Input tensor simulating a 224x224 RGB image
x = torch.randn(1, 3, 224, 224)
output = model(x)
print(output.shape) # Expected: torch.Size([1, 10])

Fine-Tuning Architectures

Unlike feature extraction, where the backbone remains static, fine-tuning involves unfreezing parts of the pre-trained architecture to allow backpropagation to update the weights based on the new, domain-specific data. This is typically done by unfreezing the last few residual blocks or the final convolutional layers. Because these layers contain high-level semantic features, small updates can adapt the model to specific textures, shapes, or lighting conditions present in your unique dataset.

When performing fine-tuning, the choice of learning rate is critical. A common heuristic is to use a learning rate 10 to 100 times smaller than the standard training rate. This prevents the large gradients from the new classification head from catastrophically destroying the carefully optimized weights already present in the frozen base layers. Proper scheduling, such as 'discriminative learning rates' (using lower rates for early layers and higher for later ones), is often employed.

Operator Note: If you observe the validation loss increasing while training loss decreases during fine-tuning, you are likely overfitting to the small dataset and should increase regularization or freeze more layers.
Python 3
model = models.resnet18(pretrained=True)

# Unfreeze only the last layer (layer4) for fine-tuning
for param in model.layer4.parameters():
    param.requires_grad = True

# Use a small learning rate for the fine-tuned parameters
optimizer = torch.optim.Adam([
    {'params': model.layer4.parameters(), 'lr': 1e-5},
    {'params': model.fc.parameters(), 'lr': 1e-4}
])

Knowledge Check

Ready to test your understanding of 5. Transfer Learning for Computer Vision?

Back