DEEP LEARNINGPresentation & practice sheetsTRANSFER LEARNING
← All worksheets
LECTURE PRESENTATION / TRANSFER LEARNING

Borrow. Adapt.
See further.

A powerful network already exists. Your dataset is small. Learn what to reuse, what to update, and when to rethink how a model sees.

75–90 minutes5 guided visual lessonsPredict → explore → explain
01 / NOTICEA puzzle before a definition.
02 / EXPLOREChange one thing. Trace the numbers.
03 / EXPLAINMake a prediction, then reveal the reasoning.
00
TODAY'S MISSION

120 images.
Millions of decisions.

Your team needs to sort three kinds of leaves. You have 40 labelled images per class and a pretrained ResNet-18. Is starting from scratch the best use of what you know?

120labelled images
before the split
11.18Mparameters in ResNet-18
with a new 3-class head
THE TENSION

How much must we relearn
to recognise something new?

A motivating scenario, not a training benchmark. Parameter count includes BatchNorm's learned scale and bias; it excludes running-statistic buffers.

Borrow a visual vocabulary→Train a new reader→Decide what can change→Show useful variation
KEEP ONE QUESTION OPEN

Even after all four decisions, can a model miss a relationship between distant parts of an image? We will return to that puzzle at the end.

By the end, you will choose a transfer strategy, calculate a classifier's size, trace which weights change, reject an unsafe augmentation, and explain why patch attention is worth exploring.

Go deeperStarting point, notation & a fair experiment

Bring your knowledge of convolution, pooling, gradient descent, and train/validation/test splits. We write a network as a backbone fθ followed by a task head gφ. θ and φ are learned parameters.

Split the 120 original images first, preferably by plant or capture session if images are related. For illustration: 84 train, 18 validation, 18 test, stratified if feasible. Use validation to select a recipe and touch the test set only for the final evaluation. A tiny split has high uncertainty; repeated or cross-validation can help.

The labs below use exact small numerical examples, hand-designed features, or architecture counts. No accuracy curves or learned embeddings are claimed.

01
PRETRAINED

A head start, not a finished job.

01 / THE QUESTION

A network recognises 1,000 ImageNet classes. Your three leaf classes are not on its menu. Is everything it learned now useless?

02 / SEE THE PROBLEM
NEW INPUTLeaf image224 × 224 × 3
→
ALREADY LEARNEDVisual featuresedges · textures · parts
→
WRONG TASK1,000 scoresWhere are our three labels?
The output labels do not fit the task. That does not make the internal representation worthless.
03 / THE IDEA

A pretrained model has already learned parameters on another dataset or objective. Transfer learning reuses that experience for a new task. The backbone extracts a representation; the head turns it into task-specific predictions.

Think of hiring an experienced photographer: they already notice edges, textures, and shapes, but must learn your catalogue. Keep the useful visual vocabulary and replace the old label dictionary. Similarity between the old and new tasks matters; reuse is a hypothesis to validate.

04 / THE FORMULA
ŷ = gφ(fθ*(x))     φ = (W, b),   W ∈ ℝC×d, b ∈ ℝC

x is the input; θ* is the pretrained backbone; d is the feature width; C is the new class count. A linear head has Cd weights and C biases. The parameter notation denotes a weight matrix and bias vector.

Go deeperWhat transfers, what changes & preprocessing

Early CNN layers often detect simpler patterns and later ones are more task-specific, but this is a useful tendency, not a guarantee. Source bias and domain shift can make a pretrained representation unhelpful (negative transfer).

ImageNet ResNet-18 produces 512 features after global average pooling. Its original head has 512 × 1,000 + 1,000 = 513,000 parameters. A 3-class replacement has 512 × 3 + 3 = 1,539. Pretraining changes the initialization; whether the backbone later changes is a separate decision.

Use the checkpoint's expected channel order, input range, resizing, and normalization. The weights alone are not the complete input contract. Training augmentation may vary the crop, but normalization must remain compatible.

Decision: compare a frozen-backbone baseline against selective fine-tuning on validation data. Do not promise a fixed accuracy gain or claim that more pretraining always wins.

05 / WATCH, PREDICT, THEN EXPLORE
Explore the values yourself · open the interactive calculator

Replace the dictionary.

LIVE COUNTS

Change the number of classes. Which part of the network grows?

06 / CHECK YOUR UNDERSTANDING
Reveal reasoning

512 × 3 + 3 = 1,539. The old 1,000-class head is replaced; the pretrained backbone can still be reused.

Reveal reasoning

Verify the expected preprocessing, labels and splits, then compare frozen features and selective fine-tuning on validation data. A domain mismatch may require different pretraining or more adaptation; transfer is not guaranteed.

02
FEATURES

Keep the eyes. Teach a new reader.

01 / THE QUESTION

Could you learn to sort leaves without changing a single convolutional weight?

02 / SEE THE PROBLEM
View 1 · toy leaf pixels
0070
0797
7970
0700
View 2 · shifted pixels
0007
0079
0797
0070
THE MISSING STEPComparable featuresMany pixel coordinates change. Which evidence still helps recognise the species?
A classifier needs useful coordinates. A reusable representation can supply them.
03 / THE IDEA

In fixed feature extraction, each image passes through a frozen backbone. Train only a new head on the resulting feature vectors. The head learns how to combine the evidence that is already available.

Think of a trained observer handing a new curator a description card. The curator learns a new sorting rule without retraining the observer. If the description omits the crucial clue, a better sorting rule alone may not be enough.

04 / THE FORMULA
zc = (1/HW) Σi,jAijc   ;   p = softmax(Wz + b)

A is a feature tensor with H × W positions and channels c. Global average pooling creates one value per channel. W and b belong to the new classifier; p is its class-probability vector.

Go deeperAn exact example, loss & caching

For channel 1, [[1,3],[2,2]] averages to 2. Channel 2, [[0,2],[4,2]], also averages to 2. Thus z = [2,2]. Let W = [[1,−0.5],[−0.5,1]] and b = [1,1]. The scores are [2,2] and softmax gives [0.5,0.5].

For a labelled example y, cross-entropy is L = −log py. Optimize W and b while keeping θ fixed. With z = [3,1], the scores become [3.5,0.5], so pA ≈ 0.953. This confidence comes from a hand-selected toy classifier; it is not calibrated evidence about real leaves.

Feature maps are generally learned channel responses, not guaranteed human-interpretable properties. The channels here are deliberately simple.

Cached features can save repeated backbone computation when the backbone and preprocessing are fixed. Caching one view per image removes fresh online augmentation; cached augmented views or recomputation are needed for varied views.

05 / WATCH, PREDICT, THEN EXPLORE
Explore the values yourself · open the interactive calculator

From feature maps to a decision.

EXACT TOY MODEL

Predict the pooled values before changing the example. Watch how the same head reads new evidence.

Toy, hand-designed feature maps and fixed demonstration head; this lab traces inference, not head training.

06 / CHECK YOUR UNDERSTANDING
Reveal reasoning

The means are [2,2]. The first score is 1×2 − 0.5×2 + 1 = 2; the second is −0.5×2 + 1×2 + 1 = 2. Softmax yields [0.5,0.5].

Reveal reasoning

No. Identical representations give the same deterministic output. The missing distinction must enter through better input information or a changed representation, for example fine-tuning suitable backbone layers.

03
FREEZING

Freeze the weights. Keep the signal.

01 / THE QUESTION

“Freeze the backbone” sounds like switching it off. If it stops working, how can the head learn anything?

02 / SEE THE PROBLEM
INPUTx
→
FROZEN ≠ REMOVEDfθ(x)Forward computation still runs
→
TRAINABLENew headLoss determines the update
Freezing controls which parameters are updated. It does not remove layers from the forward path.
03 / THE IDEA

Layer freezing holds selected parameters fixed. Fine-tuning updates some or all pretrained parameters for the new task, often with a smaller learning rate than the new head.

Imagine editing a textbook: lock the trusted chapters and revise the chapter that needs new examples. You still read the locked chapters. Start with a head-only baseline, then consider unfreezing later blocks if validation evidence supports it.

04 / THE FORMULA
θℓ ← θℓ − ηℓ mℓ ∇θℓL   ;   mℓ ∈ {0,1}

ℓ is a layer, ηℓ its learning rate, and mℓ a teaching shorthand: 0 holds its parameters fixed, 1 applies a plain SGD update. Real freezing should exclude frozen parameters from optimizer updates, including weight decay.

Go deeperAutograd, BatchNorm & a practical training recipe

Forward pass: frozen layers still transform x. Backward pass: frozen parameters need no parameter gradients; gradients through their operations may still be needed if earlier trainable layers require them. Do not indiscriminately detach tensors in a partially trainable network.

In PyTorch, requires_grad_(False) controls parameter gradients; eval() controls module behaviour. They are different. BatchNorm running means and variances are buffers and can change in training mode even when affine weights are frozen. Dropout also behaves differently in train and eval modes.

For a fixed-feature baseline: freeze the backbone, put it in eval mode, train the head, and optimize only parameters that require gradients. If a parent train() call resets the backbone mode, restore its eval mode. When unfreezing, update the optimizer's parameter groups and choose the BatchNorm policy deliberately.

Counts below are for torchvision-style ResNet-18: stem + layer1 = 157,504; layer2–4 = 11,019,008; a new 3-class head = 1,539. The grouped blocks simplify the decision; they are not individual layers.

05 / WATCH, PREDICT, THEN EXPLORE
Explore the values yourself · open the interactive calculator

Choose who gets to learn.

ONE SGD STEP

Toggle a group, then take one step. Every group stays on the forward route; only unlocked weights move.

Representative scalar per group; fixed illustrative gradients [0.4, −0.2, 0.6], learning rates [0.01, 0.01, 0.1]. No momentum, weight decay, or BatchNorm updates are simulated. These gradients are not recomputed from a loss.

06 / CHECK YOUR UNDERSTANDING
Reveal reasoning

Frozen: 2. Unfrozen: 2 − 0.1×0.4 = 1.96. A fixed weight still participates in the forward computation.

Reveal reasoning

No. Running statistics are buffers, not gradient-trained parameters. BatchNorm can update them in train mode. Choose train/eval modes intentionally; eval mode itself does not freeze parameter gradients.

04
AUGMENTATION

More views. The same meaning.

01 / THE QUESTION

A leaf is still a leaf in a different position. But is a left-turn arrow still “left” after a horizontal flip?

02 / SEE THE PROBLEM
SPECIES LABEL
♧   ⇄   ♧
Often the same class
DIRECTION LABEL
←   ⇄   →
The class can change
The same transformation can be helpful for one task and wrong for another. Validate the semantics, not just the appearance.
03 / THE IDEA

Data augmentation samples plausible variations of training images so the model sees more than one exact rendering. Crops, flips, and brightness changes encode assumptions about what should not change the answer.

Think of rehearsing a talk in different rooms: useful variation prepares you for a new setting, but rewriting the subject would be a different talk. Augmented views are correlated observations of the same source; they do not create new independent labelled examples.

04 / THE FORMULA
minθ,φ (1/N) Σi 𝔼T∼𝒜[L(gφ(fθ(T(xi))), yi)]

𝒜 is a distribution of allowed transformations T. This standard classification form assumes T preserves the label yi. Frozen parameters are excluded from the minimization. Detection and segmentation require corresponding target transformations.

Go deeperTransform math, leakage & sensible evaluation

For width W, a horizontal flip is x′[r,c] = x[r,W−1−c]. In the toy grid, brightness adds δ and clips: x′ = min(9,max(0,x+δ)). A right shift inserts zeros on the left and discards the rightmost column. A clockwise rotation maps output [r,c] to input [H−1−c,r] for a square grid.

Split original examples before generating augmented views. Put related captures in the same split when necessary. Otherwise a transformed training image can leak into validation and make performance look better than it is.

Use random augmentation for training and a consistent evaluation preprocessing pipeline. Deliberate test-time augmentation is a separate technique, not the default validation recipe. A severe crop can remove the object; colour shifts can erase a disease cue. Stronger is not automatically better.

For leaf species, moderate position and illumination changes may preserve labels. For left/right arrow classes, a horizontal flip requires changing the label or excluding that transform. For colour-based diagnoses, brightness/colour changes need domain care.

05 / WATCH, PREDICT, THEN EXPLORE
Explore the values yourself · open the interactive calculator

Transform pixels. Audit the label.

NUMBERED PIXELS

Apply a flip, then switch the task to arrow direction. The pixel operation is identical. Is the training pair still valid?

Synthetic 4 × 4 images, values 0–9. Numbers stay visible. Geometry is applied before brightness; clipping can destroy evidence.

06 / CHECK YOUR UNDERSTANDING
Reveal reasoning

Flip: [9,7,2,0]. Add and clip: [9,9,4,2]. The transform changes the pixels; whether the label remains valid depends on the task.

Reveal reasoning

Views from one original can occur in both training and validation, causing leakage. Split original images or source groups first, and augment only the training portion. Five views are not five independent labelled images.

05
CONTEXT

When the answer lives far away.

01 / THE QUESTION

Two marks sit at opposite sides of an image. The label depends on whether they match. How many local steps let one location see both?

02 / SEE THE PROBLEM
A
A LOCAL VIEW
·   ·   ·
·   ?   ·
·   ·   ·
A
Local evidence can be insufficient for a relationship. A wider computational path is needed.
03 / THE IDEA

A standard convolution mixes nearby pixels using shared filters. Stacking layers grows the theoretical receptive field, so CNNs can learn global context. Pooling and fixed local filters impose useful biases, but may lose precise spatial detail or require multiple stages to connect distant evidence.

Think of neighbours passing a message down a street. A Vision Transformer (ViT) first represents image patches as tokens, adds position information, and uses attention to let tokens exchange content-dependent information across the image. It resembles a group discussion rather than only neighbour-to-neighbour messages.

04 / THE FORMULA
rℓ = rℓ−1 + (kℓ−1)jℓ−1   ;   jℓ = jℓ−1sℓ
N = (H/P)(W/P)   ;   Attention(Q,K,V) = softmax(QKᵀ/√dk)V

r is receptive-field width; j is input spacing between adjacent features; initialize r₀ = j₀ = 1. k is kernel size, s stride, dilation is 1. H,W are divisible by patch size P. Q,K,V are token projections; softmax is row-wise. Full attention compares all token pairs.

Go deeperWhat CNNs can do, what ViTs change & the cost

For L stride-1 3 × 3 convolutions without dilation, r = 1 + 2L. Three layers give 7 × 7 theoretical coverage. This is a geometric upper bound; the effective influence of individual pixels need not be uniform. Deeper layers, dilation, pooling, global pooling, large kernels, and hybrid attention can all widen context.

A conventional convolution uses the same learned spatial weights at different locations; attention weights depend on the current token content. Standard ViT splits an image into patches, flattens and projects each patch to an embedding, adds positional embeddings, then uses Transformer blocks. The original classification architecture also has a class token.

For 224 × 224 images and 16 × 16 patches, N = 196 patch tokens. There are 196² = 38,416 patch-to-patch attention scores per head. Including the class token gives 197² = 38,809. These counts are not total FLOPs or whole-model memory. Doubling patch width to 32 gives 49 tokens and 2,401 patch pairs, but coarser spatial detail.

Full attention has quadratic token-pair cost and weaker built-in locality than a CNN. Large-scale pretraining and the training recipe matter; ViTs are not automatically better on small datasets. The motivation is a different way to connect information, not a claim that CNNs are incapable of global reasoning.

05 / WATCH, PREDICT, THEN EXPLORE
Explore the values yourself · open the interactive calculator

Grow the field. Connect the patches.

GEOMETRY, NOT ACCURACY

Start with one convolution. How many layers cover both marked corners of this 7 × 7 input? Then compare patch sizes for a separate 224 × 224 image.

Patch 1Patch 2↘   ↓   ↙All-to-all attention↗   ↑   ↖Patch 3Patch 4

Four symbolic tokens shown for clarity; the readout counts all patches. Global reach does not guarantee learning the right relation.

06 / CHECK YOUR UNDERSTANDING
Reveal reasoning

r = 1 + 2×3 = 7. No: theoretical coverage describes possible paths, while learned weights, activations, and data determine actual influence.

Reveal reasoning

(224/16)² = 196 patch tokens, and 196² = 38,416 scores per head. These are score counts, not total compute. A global attention route is available immediately, but useful relationships must still be learned.

06
RETURN TO THE MISSION

Make the decisions.

You still have 120 leaf images and a pretrained ResNet-18. Now you have a sequence of testable choices.

1 / Split originals2 / Match preprocessing3 / Replace & train head4 / Validate adaptation5 / Audit augmentations
Reveal reasoning

Begin with source-aware splits, checkpoint-compatible preprocessing, a frozen backbone and a new 3-class head. Train on suitable augmented training views and compare validation results. If both training and validation are poor, first inspect labels and the pipeline, then test selective fine-tuning or a better-matched checkpoint. Keep augmented siblings in the same split. A ViT is a candidate if global relations or suitable pretraining justify it; the small dataset alone is not a reason to expect it to win.

NEXT TIME

We gave patches permission to talk. How do they decide whom to listen to? That is the question attention will answer.

Answers save locally when browser storage is available. Download a text copy to keep or share your work.

07
FINAL REVIEW

Eight questions,
then three sentences.

Multiple choice · type the letter or number
  1. A 512-feature backbone feeds a 3-class linear head with bias. How many head parameters are learned?
  2. Fixed feature extraction means (a) train every layer slowly (b) keep the backbone fixed and train the new head (c) discard the backbone (d) update only BatchNorm statistics.
  3. Two 2 × 2 feature maps are [1, 3; 2, 2] and [0, 2; 4, 2]. After global average pooling, type the vector as 2,2.
  4. A frozen weight starts at 2.000. Its gradient is 0.4 and the learning rate is 0.1. What is its value after the optimiser step?
  5. For a frozen BatchNorm backbone during fixed feature extraction, the safest default is (a) training mode with changing running statistics (b) evaluation mode with fixed running statistics (c) deleting BatchNorm (d) setting every activation to zero.
  6. To prevent augmented siblings from leaking across splits, (a) augment first, then split views randomly (b) split original examples first, then augment training examples (c) augment validation only (d) merge train and test.
  7. A horizontal flip for a left-versus-right arrow task is (a) always safe (b) unsafe unless the label is changed (c) safe only for validation (d) equivalent to brightness jitter.
  8. A 224 × 224 image split into 16 × 16 patches creates 196 tokens. Excluding a class token, how many patch-to-patch attention scores are formed per head?
Show answers

1: 1,539 = 512 × 3 + 3. 2: (b). 3: [2, 2] because each map sums to 8 over four positions. 4: 2.000 because freezing blocks the optimiser update; the forward pass still uses the weight. 5: (b). 6: (b). 7: (b). 8: 38,416 = 196².

Explain in three sentences

Write one precise sentence for each decision. These are saved with your other worksheet answers.

Show model answers

1. Split original images by source, apply the checkpoint's preprocessing, train a new 3-class head on a frozen backbone, and use suitable augmentation only on training data to establish a low-variance baseline. 2. If the pipeline and labels are sound but both training and validation remain weak, selectively unfreeze later layers with a smaller learning rate and compare on validation data. 3. A ViT becomes a useful candidate when distant relationships matter and a suitable pretrained checkpoint is available; the choice still needs a fair validation comparison.