liveBook · Manning

Transfer learning

As explained in Inside Deep Learning: Math, Algorithms, Models

A training approach that adapts a pretrained model to a new task, usually by reusing learned weights and matching the original preprocessing expectations.

Transfer learning adapts a model trained on a large source dataset to a related target task. Instead of learning every weight from random initialization, keep most of the pretrained architecture and weights, then change what the model must predict. This is especially useful when labeled target data or training time is scarce. It works best when the source and target share useful patterns; a large but irrelevant source dataset is not automatically helpful. section 13.0 section 13.2.1

Adapt ResNet-18 to cats versus dogs

An ImageNet-pretrained ResNet ends with a layer for 1,000 classes. For two classes, load its pretrained weights and replace only that layer: `model = torchvision.models.resnet18(pretrained=True)`; `model.fc = nn.Linear(model.fc.in_features, 2)`. The new `fc` starts with random weights; the preceding filters retain their learned weights. Loading ResNet without `pretrained=True` and replacing `fc` changes the task, but training that randomly initialized network is not transfer learning. section 13.2 section 13.2.1

Pretrained weights are useful only if inputs match the conditions under which they were learned. The ImageNet ResNet expects each color channel to be normalized with its ImageNet mean and standard deviation. A mismatch can make those weights ineffective. One implementation puts normalization in a wrapper around the model, with fixed values, rather than treating it as an inherent property of the dataset. section 13.2.2

class NormalizeInput(nn.Module): 
    def __init__(self, baseModel): 
        """
        baseModel: the original ResNet model that needs to have its inputs 
         pre-processed 
        """ 
        super(NormalizeInput, self).__init__() 
        self.baseModel = baseModel               #1 
        self.mean = nn.Parameter(torch.tensor( 
         [0.485, 0.456, 0.406]).view(1,3,1,1), #2 
         requires_grad=False)                  #3 
        self.std = nn.Parameter(torch.tensor(
         [0.229, 0.224, 0.225]).view(1,3,1,1), #2 
         requires_grad=False)                  #3

    def forward(self, input): 
        input = (input-self.mean)/self.std       #4
        return self.baseModel(input)             #4
#1 The model that we want to use. We need to normalize its input first.
#2 The mean and standard deviation used for ImageNet normalization. We just have to accept these “magic” numbers that everyone uses.
#3 requires_grad=False: we don’t want these values to change during training!
#4 Normalizes the input and then feeds it into the model we want to use

The `NormalizeInput` module subtracts the three ImageNet channel means, divides by their standard deviations, and passes the result to the pretrained model. Its normalization parameters do not train. section 13.2.2

After replacing the classifier, choose which weights may change:

  • Warm start: train the new layer and allow the pretrained weights to update. A warm start means initializing from weights believed better than random; it is not, by itself, synonymous with transfer learning. section 13.2.3
  • Frozen weights: set `requires_grad=False` on the pretrained parameters, then install a new `fc` whose parameters remain trainable. This leaves far fewer weights to estimate from the target data. section 13.2.4 section 13.3

Compare both choices against training from scratch rather than assuming one always wins. In the cats-versus-dogs comparison, frozen weights gave stable results slightly below the warm-started model, while both beat the scratch baseline. With extremely little training data, freezing can help because fewer adjustable parameters must be learned from those examples. section 13.2.4 section 13.3

Transfer a text model

For AG News classification with 256 labeled training items, a GRU trained from scratch provides a baseline. A frozen DistilBERT offers a pretrained transformer alternative through Hugging Face. Load both `DistilBertTokenizer.from_pretrained('distilbert-base-uncased')` and `DistilBertModel.from_pretrained('distilbert-base-uncased')`: the tokenizer must encode new text as the model's original training did. This route avoids training a large transformer from scratch, though transformer models remain computationally expensive. section 13.4 section 13.4.1

How Inside Deep Learning: Math, Algorithms, Models covers it

How deep it goes
Walks through classifier replacement, matched preprocessing, and warm-versus-frozen training; avoids training a large pretrained transformer from scratch.
Examples
Compares scratch, warm, and frozen ResNet classifiers for cats versus dogs, then contrasts a GRU with DistilBERT on AG News.
What it assumes
Assumes familiarity with training neural networks and CNNs, while teaching pretrained-model adaptation and its preprocessing requirements step by step.
What you can do after
Apply it via torchvision.models or Hugging Face transformers, matching preprocessing and choosing trainable weights for the available labels.
How it connects
Connects pretrained weights to convolutional filters, input normalization, warm starts, weight freezing, tokenization, and transformers.

Also explained in

Compare how 13 books explain transfer learning →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Inside Deep Learning: Math, Algorithms, Models. The section links point to the parts of the book it draws on.