Deep Learning Foundations / Module 7 of 8
15-min lesson

Transfer Learning

Personalized Doggy Door · Data Augmentation · The Training Loop · Fine-Tuning the Model

Personalized Doggy Door

Module 6's door opens for any dog. Say you want it to open only for your dog, Bo — and keep out every other dog. You don't have millions of photos of Bo. You have maybe twenty. Training a CNN from scratch on twenty photos would badly overfit (Module 3). But VGG16 already knows how to see — edges, fur, shapes, general "dog-ness" — from 1.2 million photos. Transfer learning reuses that seeing, and only teaches the small, final part: telling Bo apart from everything else.

Freezing the Base

requires_grad_(False) tells PyTorch: never compute gradients for these parameters, never update them. Every layer VGG16 already learned stays exactly as it is — only a new head gets added and trained:

import torchvision.models as models
import torch.nn as nn

base_model = models.vgg16(weights=models.VGG16_Weights.IMAGENET1K_V1)
base_model.requires_grad_(False)   # freeze everything that's already learned

num_features = base_model.classifier[0].in_features
base_model.classifier = nn.Sequential(
    nn.Linear(num_features, 256),
    nn.ReLU(),
    nn.Dropout(0.3),
    nn.Linear(256, 2)   # 2 classes: bo / not_bo
)

The new classifier layers are trainable by default — only they get to learn anything new. The optimizer is told to only bother with those:

optimizer = torch.optim.Adam(
    filter(lambda p: p.requires_grad, model.parameters()),
    lr=0.001
)

Data Augmentation

With only twenty photos of Bo, augmentation matters even more than in Module 4. And here, unlike the ASL letters, a flip is safe — a mirrored photo of Bo is still recognizably Bo:

import torchvision.transforms.v2 as transforms

random_transforms = transforms.Compose([
    transforms.RandomRotation(10),
    transforms.RandomHorizontalFlip(),   # fine here — flipping doesn't change what's being shown
])

The Training Loop

Same loop as every module before it. What's different is invisible in the code: because the base is frozen, only the new head's weights actually move. Everything VGG16 already knew stays untouched.

for epoch in range(10):
    model.train()
    for x, y in train_loader:
        x = random_transforms(x)
        optimizer.zero_grad()
        output = model(x)
        loss = loss_fn(output, y)
        loss.backward()
        optimizer.step()

Fine-Tuning the Model

Once the new head is trained and doing reasonably well, you can optionally unfreeze the base too, and keep training the whole network — letting VGG16's early layers adjust slightly toward your specific task. This needs a much smaller learning rate: the base already holds well-tuned knowledge, and a large update would clumsily overwrite it instead of gently nudging it.

base_model.requires_grad_(True)   # unfreeze everything

fine_tune_optimizer = torch.optim.Adam(model.parameters(), lr=0.00001)  # 100x smaller

for epoch in range(5):
    model.train()
    for x, y in train_loader:
        x = random_transforms(x)
        fine_tune_optimizer.zero_grad()
        output = model(x)
        loss = loss_fn(output, y)
        loss.backward()
        fine_tune_optimizer.step()
You're not teaching the model to see. You're teaching it to look for one more thing.

Vocabulary

Transfer learning
Reusing a pretrained model's learned features, and only training a small new part for your task.
Freezing (requires_grad_(False))
Telling PyTorch never to compute or apply gradients for certain parameters.
Fine-tuning
Unfreezing some or all of a frozen base and continuing training, usually at a much smaller learning rate.
Learning rate
How large a step the optimizer takes when adjusting a weight after a mistake.
Classifier head
The final layers of a model that make its actual decision, as opposed to earlier layers that extract general features.

15-min quiz