Summative assessment
- Part A: collected at 2 pm on 8 December. Part B is released at the same time.
- Part B: collected at 2 pm on 9 December.
- Validate and submit your assignment. Your latest submitted version is the one collected.
A boundary for two classes
Two input measurements and two labels. What sort of boundary would separate them?
One straight line cannot separate the rings
A single linear score puts examples from both classes on each side of the boundary.
Learned features can bend the boundary
Ten sigmoid hidden units transform the inputs. Their combined output can enclose the inner class.
Three Iris species
Now predict setosa, versicolor or virginica from sepal length and petal length. We need several output probabilities.
Softmax converts class scores into probabilities
\[ p_k=\frac{e^{z_k}}{\sum_j e^{z_j}} \]
| Class | Score z | e raised to z | Probability |
|---|---|---|---|
| Setosa | 1 | 2.718 | 0.090 |
| Versicolor | 2 | 7.389 | 0.245 |
| Virginica | 3 | 20.086 | 0.665 |
Scores can have any sign or size. The resulting probabilities are positive and sum to 1.
Reading softmax
| Change to the scores | Effect on the probabilities |
|---|---|
| Raise one score | Its probability rises and the others fall |
| Add the same value to every score | All probabilities stay the same |
\[ \mathrm{softmax}(1,2,3)=\mathrm{softmax}(101,102,103) \]
Subtracting the largest score before exponentiating gives the same result with smaller numbers.
Targets and cross-entropy
| Observed species | One-hot target |
|---|---|
| Setosa | (1, 0, 0) |
| Versicolor | (0, 1, 0) |
| Virginica | (0, 0, 1) |
\[ \ell=-\sum_k y_k\ln p_k \]
\[ \ell_{\mathrm{virginica}}=-\ln(0.665)\approx0.408 \]
The target selects the probability assigned to the observed class.
Forward pass
Evaluate the model from its inputs towards its outputs, using the current weights.
When targets are available, compare predictions with them to calculate a loss.
A batch through the network
Here a batch has 10 flowers, each with 2 inputs. Each flower produces 3 hidden values and 3 class probabilities.
Biases in the weighted sum
\[ z=b+w_1x_1+\cdots+w_nx_n=w_0(1)+w_1x_1+\cdots+w_nx_n \]
| Augmented weight matrix | Shape for this example |
|---|---|
| Input to hidden: V | 3 × (2 + 1) |
| Hidden to output: W | 3 × (3 + 1) |
A constant input of 1 lets the bias sit beside the other weights. Reusing the same parameters and inputs reproduces the same predictions.
Backward pass
Apply the chain rule backwards through the calculation to find loss gradients.
These gradients tell us how each parameter affects the loss at its current value.
The output supplies an error signal
\[ \frac{\partial\ell}{\partial z_k}=p_k-y_k \]
| Virginica example | Setosa | Versicolor | Virginica |
|---|---|---|---|
| Probability p | 0.090 | 0.245 | 0.665 |
| Target y | 0 | 0 | 1 |
| Score gradient | +0.090 | +0.245 | −0.335 |
The loss favours lower wrong-class scores and a higher observed-class score.
The signal reaches the hidden units
\[ \frac{\partial\ell}{\partial h_j}=\sum_k(p_k-y_k)W_{kj} \]
\[ \frac{\partial\ell}{\partial a_j}=\frac{\partial\ell}{\partial h_j}h_j(1-h_j) \]
The output weights and each hidden sigmoid slope carry the signal back.
Each weight gradient includes its input
\[ \frac{\partial\ell}{\partial W_{kj}}=(p_k-y_k)h_j,\qquad\frac{\partial\ell}{\partial V_{jr}}=\frac{\partial\ell}{\partial a_j}x_r \]
An output weight receives its hidden input. An incoming weight receives its original input. A bias uses the constant input 1.
The optimiser changes the parameters
\[ \theta_{\mathrm{new}}=\theta-\eta\frac{\partial J}{\partial\theta} \]
Gradients come from the backward pass. The optimiser uses them to update the weights.
Cost across a batch
\[ J_{\mathrm{sum}}=\sum_i\ell_i,\qquad J_{\mathrm{mean}}=\frac{1}{N}\sum_i\ell_i \]
Add or average the example losses. The gradients follow the same convention.
A sum and a mean differ by N, so the numerical scale of the learning rate matters.
Checking one gradient
\[ \frac{\partial J}{\partial c}\approx\frac{J(c+\epsilon)-J(c-\epsilon)}{2\epsilon} \]
| One output bias, ε = 0.001 | Value |
|---|---|
| J(c − ε) | 12.335392880 |
| J(c + ε) | 12.332134124 |
| Numerical slope | -1.62938 |
| Backpropagation slope | -1.62938 |
Different models fit the same readings
The dashed line is the true response. Each solid curve fits the same 12 noisy measurements.
What changes with a new training sample?
Each solid line is a fit to a fresh set of noisy measurements. Which model is consistently wrong? Which changes most?
Compare predictions at one fixed input
At x = 0, the true response is 1. What do the centre and width of each distribution tell us?
Bias and variance
Bias: the line’s average prediction misses the true value. Variance: the flexible model’s predictions vary most across training samples.
More data reduces variation
With 80 readings per fit, predictions vary less. The line still has the wrong shape.
\[ \mathrm{Expected\ squared\ error}=\mathrm{Bias}^2+\mathrm{Variance}+\mathrm{Noise} \]
Today we will cover
- Convolutional layers and learned image features.
- Learning to predict steering commands.
- A language model’s prediction and training loop.
- Reusing a pretrained model for a new task.
What could a network read from this image?
Nearby pixels form edges, markings and object parts. How can the architecture use that structure?
An image is a structured array
\[ 64\times64\times3=12,288\ \mathrm{input\ values} \]
Flattening keeps the pixel values while arranging them as a vector.
A dense first layer becomes large
\[ (12,288+1)\times256=3,145,984 \]
Every input value connects to every hidden unit. This first layer alone has over three million parameters.
CNN Kernels
This small grayscale example uses a 3 × 3 patch and nine weights.
CNN Kernels
What value should the first feature-map location receive?
CNN Kernels
\[ 0+0+1+0+0+1+0+0+1=3 \]
CNN Kernels
The next patch gives another response. The weights stay the same.
CNN Kernels
The filter responds where brightness changes across the patch. A uniform patch gives zero.
The feature moves with the edge
Sharing weights lets the same pattern trigger the same response at different positions.
Training learns the filter values
\[ \mathrm{pixels}\longrightarrow\mathrm{filter\ responses}\longrightarrow\mathrm{prediction}\longrightarrow\mathrm{loss} \]
Backpropagation gives gradients for each filter weight. Every location where that filter was used contributes to its update.
The examples teach which local responses help the final task.
One RGB filter spans three input channels
Add the red, green and blue contributions at the same location.
Several filters learn several responses
Each output channel has its own filter and bias. All positions within a channel share those parameters.
Stride controls where the filter is evaluated
With stride 1, move the window by one pixel.
A larger stride samples fewer positions
With stride 2, move by two pixels. The feature map has fewer locations.
Zero-padding at the image border
A one-pixel border of zeros lets a 3 × 3, stride-1 filter keep the original height and width.
How large is the output map?
\[ N_{\mathrm{out}}=\left\lfloor\frac{N+2P-K}{S}\right\rfloor+1 \]
| Input size N | Kernel K | Padding P | Stride S |
|---|---|---|---|
| 7 | 3 | 1 | 2 |
What are the output height and width? What if we use eight filters?
Eight filters give eight 4 × 4 maps
\[ \left\lfloor\frac{7+2-3}{2}\right\rfloor+1=4 \]
\[ \mathrm{Output\ shape}=4\times4\times8 \]
Spatial size and number of channels describe different parts of the tensor.
A nonlinear response still matters
\[ \mathrm{ReLU}(-3)=0,\qquad\mathrm{ReLU}(0)=0,\qquad\mathrm{ReLU}(3)=3 \]
A convolution is a shared weighted sum. Activations let several convolutional layers represent nonlinear responses.
Which values does max pooling keep?
Keep the largest response in each 2 × 2 window. What are the four outputs?
Four local maxima remain
Pooling reduces the spatial grid. The pooling operation itself has no learned weights.
Pooling trades detail for a coarser summary
A maximum records a strong response somewhere inside its window. It loses the exact location inside that window.
A small shift can leave the result unchanged if the response stays in the same window. Crossing a window boundary can change it.
Later units can see a wider region
The receptive field is the input region that can affect a particular unit.
A complete small CNN
Local features become larger-scale features, then a final head predicts the class.
Features can build on simpler features
Early local responses can combine into curves, parts and more complex shapes.
Zeiler and Fergus, Visualizing and Understanding Convolutional Networks.
Finding objects is a different output task
Detection predicts both object classes and their locations. One scene can contain several objects.
A class for each pixel
Semantic segmentation assigns classes to pixel locations, such as road, sky, car or pedestrian.
The target determines the head and loss
| Task | Training target | What the loss compares |
|---|---|---|
| Image classification | One class per crop | Class probabilities |
| Object detection | Classes and boxes | Labels and positions |
| Semantic segmentation | A class at each pixel | Pixel labels |
The backbone can supply image features for several kinds of head.
Same softmax, new labels
For one pixel in a simplified three-class example:
\[ p_{\mathrm{car}}=\frac{e^{z_{\mathrm{car}}}}{e^{z_{\mathrm{car}}}+e^{z_{\mathrm{sky}}}+e^{z_{\mathrm{pedestrian}}}} \]
| Class | Score | Probability |
|---|---|---|
| Car | 3 | 0.665 |
| Sky | 1 | 0.090 |
| Pedestrian | 2 | 0.245 |
The labels changed. The conversion from scores to probabilities stayed the same.
The observed pixel class supplies the loss
\[ \ell=-\ln p_{\mathrm{car}}\approx0.408 \]
A labelled car pixel supplies an error signal that travels back to the image network.
Residual connections
\[ y=x+F(x) \]
Why might carrying x along this shortcut make a deep network easier to train?
Residual connections
The learned branch can make a change to its input. The gradient also has a direct path through the addition.
He and colleagues, Deep Residual Learning for Image Recognition.
A camera-to-steering example
The training examples pair images with actions
We have camera views and the driver’s steering command at the same time.
How could we use these pairs to teach the network?
A target and a regression loss
\[ \ell=(\hat a-a)^2 \]
\[ \hat a=+2^\circ,\qquad a=-8^\circ\quad\Rightarrow\quad\ell=100\ \mathrm{degrees}^2 \]
Compare the predicted steering angle with the recorded angle. A large error gives a large penalty.
Forward pass: predict a steering command
The image passes through the CNN and produces an angle. The recorded command supplies the target.
Bojarski and colleagues, End to End Learning for Self-Driving Cars, 2016.
Backward pass: reach the image filters
\[ \frac{\partial\ell}{\partial\hat a}=2(\hat a-a)=20 \]
The pixels stay fixed. The loss gives gradients for the filters and the output head.
The same update rule trains the CNN
Change the trainable parameters, then make another prediction with the updated model.
What exactly do driver labels teach?
Does copying a recorded steering command tell the model which action is best in every possible situation?
Imitation learns from the demonstrations it receives
The model learns to reproduce the recorded behaviour. Missing situations and poor demonstrations affect what it can learn.
An image from a well-centred car may give little evidence about how to recover after drifting away from the demonstrated path.
Driving changes the next input
The model’s own actions change what it sees next. Errors can take it away from familiar training situations.
A new condition can change the inputs
A model that works on daylight recordings still needs evidence about night-time inputs.
A larger driving system has several tasks
An end-to-end model connects inputs directly to a target action. Other designs make intermediate tasks explicit.
Completing a route instruction
A navigation instruction begins: “Turn left at the next ____.”
What word would you put in the gap?
Which word might come next?
Turn left at the next ____
Use the earlier words as input and predict the next one.
A language model is another prediction function
We can keep the internal network abstract. Its output is a set of scores for possible next words.
Same softmax, different output labels
\[ p_{\mathrm{junction}}=\frac{e^{z_{\mathrm{junction}}}}{\sum_w e^{z_w}} \]
| Illustrative three-word vocabulary | Score | Probability |
|---|---|---|
| junction | 3 | 0.665 |
| roundabout | 2 | 0.245 |
| bridge | 1 | 0.090 |
The full output vocabulary of a language model is much larger. The calculation has the same form.
The observed next word gives the target
Training text: “Turn left at the next junction.”
\[ y=(1,0,0),\qquad\ell=-\ln p_{\mathrm{junction}}\approx0.408 \]
The label is the word that actually follows this prefix in the training text.
Backward pass: the same error signal
\[ \frac{\partial\ell}{\partial z_{\mathrm{junction}}}=p_{\mathrm{junction}}-1\approx-0.335 \]
The gradient reaches the parameters that produced this distribution.
Weight updates: the same learning rule
The optimiser adjusts the model using many such training examples.
One sentence supplies several training pairs
| Earlier words | Observed next word |
|---|---|
| Turn | left |
| Turn left | at |
| Turn left at | the |
| Turn left at the | next |
| Turn left at the next | junction |
\[ J=\frac{1}{N}\sum_i-\ln p(\mathrm{observed\ word}_i\mid\mathrm{earlier\ words}_i) \]
Apply the same loss at many positions and combine the contributions.
Which parts run when we use the trained model?
To produce the next word, do we need a forward pass, a backward pass, or a weight update?
Ordinary generation uses forward passes
| Changes as text grows | Stays fixed during ordinary generation |
|---|---|
| The input prefix and hidden activations | The learned weights |
Select a word, append it to the input, then run the model forwards again.
A completed instruction is still a prediction
“Turn left at the next junction.”
Each generated word extends the context used for the following prediction.
What has the loss actually rewarded?
The training loss compared the predicted words with observed text.
Does a fluent completion, or a high next-word probability, tell us that the direction reaches the library?
Fluent words can still give the wrong direction
The same sentence is fluent on both maps. Checking the route requires information about the actual destination.
The input, target and loss define what is learned
| Task | Observed target | Training penalty |
|---|---|---|
| Image labels | Car, sky or pedestrian | Cross-entropy |
| Steering | Recorded angle | Squared error |
| Text continuation | Observed next word | Cross-entropy |
The same training loop can serve different tasks. Choose the data and evaluation that match the outcome you need.
Adapting a pretrained model
A campus-card reader
The library asks for a camera-based card reader that can help check student membership.
How would you go about building it?
Define what the image model predicts
For the visual task, classify the card as student, staff or visitor. A separate ID read and register lookup check current status.
An ordinary lookup checks current student status
| Card ID | Printed card type | Current student record |
|---|---|---|
| A104 | Student | Current |
| A205 | Student | No longer current |
| S207 | Staff | Not a student record |
Read the identifier and look up its current record. The image model serves the visual part of the task.
What examples would you collect?
What should the input images look like, and where would their labels come from?
Labelled card images
Collect varied photos of different cards. Their known card types supply the labels.
| Known card | Visual class label |
|---|---|
| A104 | Student |
| S207 | Staff |
| V303 | Visitor |
How should the images be split?
Would a second photo of the same card give a strong test of performance on a new cardholder?
Hold out different cardholders
Keep related images together. Test whether the model works on cards and conditions it did not train on.
Must we learn every visual feature from scratch?
We have labelled card images. Do we also need to build and train the whole feature extractor ourselves?
Use pretrained ResNet weights
Download an existing architecture with its learned weights. It can provide a starting set of image features.
He and colleagues, Deep Residual Learning for Image Recognition.
Replace the classifier for the new labels
Keep the backbone fixed initially and train a new head for the three card categories.
Adapt more of the model if needed
Validation may justify fine-tuning selected backbone layers, often with a smaller learning rate.
Keep the input convention with the weights
| Part of the input | A practical starting point |
|---|---|
| Size and crop | Use the pretrained model’s supplied transform |
| Channels and numerical scale | Match its expected input convention |
| Card variations | Train with appropriate lighting and camera-angle variation |
Check that the card and relevant markings remain visible after preprocessing.
Loading the trained image features
from torch import nn
from torchvision.models import resnet18, ResNet18_Weights
weights = ResNet18_Weights.DEFAULT
model = resnet18(weights=weights)
preprocess = weights.transforms()
This loads the architecture and pretrained parameters. It also gives us their input preprocessing.
Adding the card-classification head
for parameter in model.parameters():
parameter.requires_grad = False
model.fc = nn.Linear(model.fc.in_features, 3)
model.eval()
The new head predicts student, staff or visitor. Train its parameters using the labelled card images.
Running the trained model
import torch
model.eval()
with torch.no_grad():
scores = model(batch)
probabilities = scores.softmax(dim=1)
Once the new head is trained, a preprocessed batch goes through the model in one call.
Most of the model already existed. Our task was to choose the target, supply examples and train the new output.
Today we covered
- CNNs learn shared local filters and combine image features.
- Images, steering and text use the same prediction, loss, backward pass and update loop.
- The target and loss determine which behaviour training rewards.
- Pretrained weights let us adapt an existing model to a new labelled task.