smartyfy.mrindigi.com

Python Master Course V2 — 149. Transfer Learning and Frozen Feature Extractors

Purpose and learning outcomes

Transfer learning reuses a representation learned on one task to help another. We will train a tiny source network locally, reuse its hidden feature extractor for a related target task, and compare a frozen linear probe, limited fine-tuning, and training from scratch. This controlled toy exercise requires no downloaded pretrained weights and makes the limits of transfer evidence explicit.

  • Separate source-task training from target-task adaptation
  • Freeze and unfreeze layers deliberately
  • Compare linear probing and limited fine-tuning without leakage

Prerequisites: 145: checkpoints; 146: CNNs; 148: model components.

Environment and run order

Use the isolated Python 3.11 or 3.12 environment from lesson 142. All tensors and models below run on the CPU. No pretrained weights or external datasets are downloaded. For first-time setup install the numerical packages, then use the official PyTorch installer selector for your operating system. The CPU wheel command below is for Linux or Windows; macOS uses python -m pip install torch. Run Python blocks sequentially in a single file.

Shell

python -m pip install numpy pandas scikit-learn matplotlib
# Linux/Windows CPU installation:
python -m pip install torch --index-url https://download.pytorch.org/whl/cpu
python -m pip freeze > requirements-observed.txt

Understand the model and the evidence

Source and target need independent evidence

The source task predicts a thresholded combination of the first two features. The target adds a contribution from the third feature. Separate random draws create independent source and target observations. Target test rows must not appear in source pretraining, even without target labels, if the claim concerns transfer to unseen target cases. In real datasets, deduplication and subject overlap need explicit checks across both domains.

A feature extractor is a reusable function

The source network’s hidden layers map four input measurements into a twelve-dimensional representation. A source classification head converts that representation into two logits. For target adaptation we discard the source head and create a new head with the target meaning. A linear probe keeps the feature extractor fixed and trains only that new linear layer. It tests whether the source representation already exposes useful target information.

Freezing parameters is not the same as evaluation mode

requires_grad_(False) prevents gradients being accumulated for frozen parameters, while excluding them from the optimizer makes the update boundary explicit. eval controls behaviors such as dropout and batch normalization. Our extractor has only Linear and ReLU modules, but real frozen backbones often also need eval mode to avoid changing running statistics. A frozen extractor may still produce outputs that a trainable head differentiates through, so understand where no_grad is appropriate.

Fine-tuning can help or erase useful structure

Limited fine-tuning unfreezes the extractor and uses a small learning rate to adapt it. This can improve the target representation or overfit scarce target data. It may also reduce source-task performance, sometimes called forgetting. We compare target validation results before selecting a final system, record the additional fine-tuning budget, and avoid claiming that a toy benefit predicts results for large pretrained language or vision models.

Incremental worked example

1. Create separate source and target tasks

The same known input coordinate system is used for both tasks, so no learned scaling step is needed. Source validation is separate from source training; target training, validation, and test are independent partitions. The source model is trained for a fixed budget before target adaptation begins.

Python

import copy
import numpy as np
import torch
from torch import nn
from sklearn.model_selection import train_test_split

torch.set_num_threads(1)
torch.manual_seed(49)
rng = np.random.default_rng(49)
source_X = rng.normal(size=(600, 4)).astype(np.float32)
source_y = (source_X[:, 0] + 0.5 * source_X[:, 1] > 0).astype(int)
target_X = rng.normal(size=(240, 4)).astype(np.float32)
target_y = (target_X[:, 0] + 0.5 * target_X[:, 1] + 0.5 * target_X[:, 2] > 0).astype(int)
sr, sv = train_test_split(np.arange(600), test_size=0.2, stratify=source_y, random_state=49)
td, tt = train_test_split(np.arange(240), test_size=0.2, stratify=target_y, random_state=49)
tr, tv = train_test_split(td, test_size=0.25, stratify=target_y[td], random_state=50)
SX, SY = torch.tensor(source_X), torch.tensor(source_y, dtype=torch.long)
TX, TY = torch.tensor(target_X), torch.tensor(target_y, dtype=torch.long)
class TransferNet(nn.Module):
    def __init__(self):
        super().__init__()
        self.features = nn.Sequential(nn.Linear(4, 12), nn.ReLU(), nn.Linear(12, 12), nn.ReLU())
        self.head = nn.Linear(12, 2)
    def forward(self, x):
        return self.head(self.features(x))
loss_fn = nn.CrossEntropyLoss()
def train_steps(net, optimizer, inputs, labels, epochs):
    net.train()
    for _ in range(epochs):
        optimizer.zero_grad(set_to_none=True)
        loss = loss_fn(net(inputs), labels)
        loss.backward()
        optimizer.step()
def accuracy(net, inputs, labels):
    net.eval()
    with torch.no_grad():
        return (net(inputs).argmax(1) == labels).float().mean().item()
source = TransferNet()
train_steps(source, torch.optim.Adam(source.parameters(), lr=0.01), SX[sr], SY[sr], 70)
print("source validation", accuracy(source, SX[sv], SY[sv]))

2. Probe, fine-tune, and train from scratch

The fine-tuned candidate begins from the completed probe, so it receives 20 additional target epochs. We report this unequal budget instead of pretending the comparison isolates initialization alone. A saved copy confirms that probe training does not alter frozen feature weights.

Python

torch.manual_seed(50)
probe = TransferNet()
probe.features.load_state_dict(copy.deepcopy(source.features.state_dict()))
for parameter in probe.features.parameters():
    parameter.requires_grad_(False)
frozen_before = {k: v.clone() for k, v in probe.features.state_dict().items()}
train_steps(probe, torch.optim.Adam(probe.head.parameters(), lr=0.01), TX[tr], TY[tr], 60)
assert all(torch.equal(frozen_before[k], v) for k, v in probe.features.state_dict().items())
fine = copy.deepcopy(probe)
for parameter in fine.features.parameters():
    parameter.requires_grad_(True)
fine_optimizer = torch.optim.Adam([
    {"params": fine.features.parameters(), "lr": 0.001},
    {"params": fine.head.parameters(), "lr": 0.003}])
train_steps(fine, fine_optimizer, TX[tr], TY[tr], 20)
torch.manual_seed(50)
scratch = TransferNet()
train_steps(scratch, torch.optim.Adam(scratch.parameters(), lr=0.01), TX[tr], TY[tr], 60)
models = {"probe_60_epochs": probe, "fine_80_total_epochs": fine, "scratch_60_epochs": scratch}
validation = {name: accuracy(net, TX[tv], TY[tv]) for name, net in models.items()}
print("target validation", validation)
chosen = max(validation, key=validation.get)
print("selected", chosen, "target test", accuracy(models[chosen], TX[tt], TY[tt]))

Expected output / interpretation

The frozen-weight assertion should pass exactly because only the head optimizer receives updates.
Source validation and three target validation scores are printed, then one selected target test score.
Transfer may help, do nothing, or hurt; no performance improvement is guaranteed.

Guided lab and acceptance criteria

  1. Document the exact source and target label rules and explain why they are related but different. Draw the boundary between shared extractor and replaced head, including feature and output dimensions.
  2. Compare the probe’s trainable parameter count with scratch training. Verify both requires_grad flags and optimizer membership. For an extractor containing batch normalization, explain why frozen weights alone would not prevent running-statistic changes.
  3. Repeat with a target label based mainly on feature three or four to investigate negative transfer. Treat this as a new prespecified experiment with its own split and report all outcomes rather than presenting only a favorable related task.
  4. Deliver source provenance, source/target overlap checks, adaptation settings, compute budgets, validation comparison, and the locked final result. A passing conclusion is limited to this toy representation and does not imply that downloaded large models will behave similarly.

Common mistakes and repairs

  • Reusing source examples that include target test subjects: source pretraining can contaminate evaluation even when target labels are absent.
  • Freezing the extractor but leaving it in training mode when it has mutable running statistics: manage parameter updates and module behavior separately.
  • Claiming a fair equal-budget comparison when fine-tuning receives additional epochs: disclose or equalize the target-training and pretraining costs.

Questions that test understanding

What does a successful linear probe show?

It suggests the fixed source representation exposes information that a linear target head can use. It does not prove all useful target information is present or that the representation is optimal. A strong hand-engineered or scratch baseline may still be simpler or more accurate.

Why replace the source head?

Its output semantics belong to the source task. Even if both tasks have two classes, the meaning of those classes and the useful boundary differ. A new head makes target adaptation explicit rather than pretending the old classification rule already solves the new problem.

Can frozen features still cause leakage?

Yes. If their source training included target test inputs or repeated subjects, the evaluation may no longer represent entirely unseen cases. Freezing controls later updates, not what information the representation has already absorbed. Audit provenance and overlap before trusting transfer results.

Why use a smaller feature learning rate in fine-tuning?

The extractor already contains a useful representation, so smaller updates can reduce abrupt disruption while the head adapts more freely. This is a reasonable hypothesis, not a universal optimum. Validate the learning-rate schedule within the available target development data.

What is negative transfer?

Reusing a source representation can harm target performance when the learned features emphasize irrelevant patterns or make useful target information harder to access. Compare against scratch and simple baselines under clearly stated budgets. A failed transfer experiment is informative evidence, not something to hide.

Does eval freeze a model?

No. eval changes the behavior of certain modules but does not disable gradients or optimizer updates. Conversely, requires_grad=False does not automatically switch dropout or batch normalization into evaluation behavior. Use the controls that match the intended training boundary.

Exercises with worked solutions

Exercise 1: Count trainable parameters

Reveal the worked solution and reasoning

Only the probe head should be trainable: 12*2 weights plus two biases, totaling 26. The complete model has additional extractor parameters. This check makes the word frozen a testable statement.

Python

probe_trainable = sum(p.numel() for p in probe.parameters() if p.requires_grad)
assert probe_trainable == 26
print("probe trainable parameters", probe_trainable)
print("scratch trainable parameters", sum(p.numel() for p in scratch.parameters() if p.requires_grad))

Exercise 2: Design an equal-budget extension

Reveal the worked solution and reasoning

Train a scratch candidate for 80 target epochs and compare it with the 60-plus-20 fine-tuning procedure on validation. Report source pretraining cost separately. If the scientific question is data efficiency, vary target training size using fixed planned subsets and preserve an independent evaluation boundary for each complete protocol.

Recap and next step

Transfer learning is a controlled reuse of information, not a free guarantee of accuracy. Separate source and target evidence, test freezing, document mode behavior, and compare honest budgets. The deep-learning capstone now combines architecture, diagnostics, checkpoint recovery, and baseline comparison into one compact reproducible CPU project.

Official references

Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.