Reveal reasoning
512 × 3 + 3 = 1,539. The old 1,000-class head is replaced; the pretrained backbone can still be reused.
A powerful network already exists. Your dataset is small. Learn what to reuse, what to update, and when to rethink how a model sees.
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?
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.
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.
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.
A network recognises 1,000 ImageNet classes. Your three leaf classes are not on its menu. Is everything it learned now useless?
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.
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.
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.
Change the number of classes. Which part of the network grows?
512 × 3 + 3 = 1,539. The old 1,000-class head is replaced; the pretrained backbone can still be reused.
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.
Could you learn to sort leaves without changing a single convolutional weight?
| 0 | 0 | 7 | 0 |
| 0 | 7 | 9 | 7 |
| 7 | 9 | 7 | 0 |
| 0 | 7 | 0 | 0 |
| 0 | 0 | 0 | 7 |
| 0 | 0 | 7 | 9 |
| 0 | 7 | 9 | 7 |
| 0 | 0 | 7 | 0 |
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.
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.
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.
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.
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].
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.
“Freeze the backbone” sounds like switching it off. If it stops working, how can the head learn anything?
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.
ℓ 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.
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.
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.
Frozen: 2. Unfrozen: 2 − 0.1×0.4 = 1.96. A fixed weight still participates in the forward computation.
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.
A leaf is still a leaf in a different position. But is a left-turn arrow still “left” after a horizontal flip?
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.
𝒜 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.
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.
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.
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.
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.
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?
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.
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.
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.
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.
Four symbolic tokens shown for clarity; the readout counts all patches. Global reach does not guarantee learning the right relation.
r = 1 + 2×3 = 7. No: theoretical coverage describes possible paths, while learned weights, activations, and data determine actual influence.
(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.
You still have 120 leaf images and a pretrained ResNet-18. Now you have a sequence of testable choices.
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.
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.
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².
Write one precise sentence for each decision. These are saved with your other worksheet 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.