Skip to main content

Lesson 7 of 12

Transfer Learning

Transfer learning uses a pretrained CNN as a starting point for training on your own data. It dramatically reduces training time and data requirements.

8 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Transfer Learning with PyTorch

Transfer Learning with PyTorch
import torch
import torchvision.models as models
import torch.nn as nn

def create_transfer_learning_model(num_classes, freeze_backbone=True):
    """
    Create a model for transfer learning.
    Replaces the final layer of ResNet18 with a new classifier
    for your number of custom classes.
    """
    # Load pretrained ResNet18 (smaller than ResNet50, good for transfer learning)
    model = models.resnet18(weights=models.ResNet18_Weights.IMAGENET1K_V1)

    if freeze_backbone:
        # Freeze all layers — only train the new classifier
        for param in model.parameters():
            param.requires_grad = False

    # Replace the final fully-connected layer
    # ResNet18 final layer: in_features=512, out_features=1000 (ImageNet classes)
    in_features = model.fc.in_features
    model.fc = nn.Linear(in_features, num_classes)
    # The new fc layer has requires_grad=True by default

    # Count trainable parameters
    total = sum(p.numel() for p in model.parameters())
    trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)
    print(f"Total parameters:     {total:,}")
    print(f"Trainable parameters: {trainable:,}")
    print(f"Frozen parameters:    {total - trainable:,}")
    print(f"Reduction: training {trainable/total*100:.1f}% of model")

    return model

# Example: custom classifier for 5 categories (e.g., different plant species)
model = create_transfer_learning_model(num_classes=5, freeze_backbone=True)

print("\nTransfer learning strategy:")
print("1. Start with ResNet18 pretrained on 1M ImageNet images")
print("2. Freeze all convolutional layers (keep learned features)")
print("3. Replace final layer with classifier for YOUR classes")
print("4. Train only the final layer → fast, needs little data")
print("5. Optionally: unfreeze last few layers for fine-tuning")
Diagram
Loading diagram…

Educational visual guide for AiTransferLearning.

Finished this lesson?

0 of 12 in Module 11
Sign in to save progress

Topics in This Module

0/12 done