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

The example circle classification taskOne thousand examples from the example. The fitted boundary uses its ten-sigmoid-unit network configuration. −1.0 −0.5 0.0 0.5 1.0 Input x₁ −1.0 −0.5 0.0 0.5 1.0 Input x₂

Two input measurements and two labels. What sort of boundary would separate them?

One straight line cannot separate the rings

A straight boundary through two ringsA logistic-regression line cuts through both classes in the same one-thousand-example circle dataset. −1.0 −0.5 0.0 0.5 1.0 Input x₁ −1.0 −0.5 0.0 0.5 1.0 Input x₂

A single linear score puts examples from both classes on each side of the boundary.

Learned features can bend the boundary

The example circle classification taskOne thousand examples from the example. The fitted boundary uses its ten-sigmoid-unit network configuration. −1.0 −0.5 0.0 0.5 1.0 Input x₁ −1.0 −0.5 0.0 0.5 1.0 Input x₂

Ten sigmoid hidden units transform the inputs. Their combined output can enclose the inner class.

Same 1000-example circle data and fitted ten-unit model as the preceding version. The figure illustrates training fit, without making a held-out accuracy claim.

Three Iris species

All three Iris speciesThese are feature columns zero and two used by the training example: sepal length and petal length. 4.5 5.0 5.5 6.0 6.5 7.0 7.5 8.0 Sepal length (cm) 1 2 3 4 5 6 7 Petal length (cm) Setosa Versicolor Virginica

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}} \]

ClassScore ze raised to zProbability
Setosa12.7180.090
Versicolor27.3890.245
Virginica320.0860.665

Scores can have any sign or size. The resulting probabilities are positive and sum to 1.

Reading softmax

Change to the scoresEffect on the probabilities
Raise one scoreIts probability rises and the others fall
Add the same value to every scoreAll 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.

A common shift cancels because every exponential acquires the same multiplicative factor. Subtract-max is a numerical-stability device, not a change of model.

Targets and cross-entropy

Observed speciesOne-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

Forward and backward calculationsThe example model computes its outputs from left to right. The weights remain fixed during the forward calculation.InputsXHidden featuresH = σ(…)Class scoresZProbabilitiesP = softmax(Z)Training costJObserved labels YA forward pass evaluates the model using its current weights

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

Batch shapes in the exampleTen Iris flowers have two measurements, three hidden activations and three class probabilities each.Input batch10 × 2Hidden activations10 × 3Output probabilities10 × 3Each row remains one example as it passes through the layers.

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 matrixShape for this example
Input to hidden: V3 × (2 + 1)
Hidden to output: W3 × (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

Forward and backward calculationsThe example model computes its outputs from left to right. Blue arrows show derivatives travelling backwards; the optimiser changes parameters afterwards.InputsXHidden featuresH = σ(…)Class scoresZProbabilitiesP = softmax(Z)Training costJObserved labels YLoss gradients travel back through the dependencies

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 exampleSetosaVersicolorVirginica
Probability p0.0900.2450.665
Target y001
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.

a_j is the hidden pre-sigmoid score. W excludes its bias column in this expression. These are gradients of the loss for one example.

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

Three separate stages in trainingA forward pass calculates predictions and loss. A backward pass calculates gradients at the current parameters. The optimiser uses these gradients to update the parameters.Forward passCalculate outputsBackward passCalculate gradientsOptimiser stepChange 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.001Value
J(c − ε)12.335392880
J(c + ε)12.332134124
Numerical slope-1.62938
Backpropagation slope-1.62938
A numerical check in a 2→3→3 sigmoid/softmax model on ten selected, scaled Iris examples. The cost is summed cross-entropy, and c is the virginica output bias. Parameters use random seed 1211. Finite differences check the local gradient; they are not the training method.

Different models fit the same readings

Three models fitted to the same readingsA line, quadratic and degree-nine polynomial fit the same twelve noisy readings from one plus 0.2 x squared on minus two to two. The dashed curve is the noise-free response. −2 −1 0 1 2 Input x 0.5 1.0 1.5 2.0 2.5 Response Line −2 −1 0 1 2 Input x Quadratic −2 −1 0 1 2 Input x Flexible polynomial Readings True response Fitted response

The dashed line is the true response. Each solid curve fits the same 12 noisy measurements.

The true response is 1+0.2x². Inputs now span [−2,2] to make the curvature visible. Noise has standard deviation 0.15. The flexible model is a degree-nine polynomial, fitted by least squares.

What changes with a new training sample?

Repeated training sets reveal variationSix fitted responses per model from independent Gaussian noise at 12 fixed input settings. The noise standard deviation is 0.15, and axes are identical in the small and large sample figures. −2 −1 0 1 2 Input x 0.5 1.0 1.5 2.0 2.5 Predicted response Line −2 −1 0 1 2 Input x Quadratic −2 −1 0 1 2 Input x Flexible polynomial

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

Bias and variance at one fixed inputExact Gaussian prediction distributions from the linear least-squares fits under independent Gaussian observation noise. The line has a mean offset from the true response; the degree-nine fit has the largest variance. 0.6 0.8 1.0 1.2 1.4 1.6 Prediction at the same input: x = 0 0 2 4 6 8 10 Density across training sets Line Quadratic Flexible polynomial True response at x = 0

At x = 0, the true response is 1. What do the centre and width of each distribution tell us?

Prediction distributions are calculated from the exact linear least-squares sampling distributions under Gaussian noise, using the same 12 fixed input positions. This compares prediction bias and variance, not coefficient error.

Bias and variance

Bias and variance at one fixed inputExact Gaussian prediction distributions from the linear least-squares fits under independent Gaussian observation noise. The line has a mean offset from the true response; the degree-nine fit has the largest variance. 0.6 0.8 1.0 1.2 1.4 1.6 Prediction at the same input: x = 0 0 2 4 6 8 10 Density across training sets Line Quadratic Flexible polynomial True response at x = 0

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

Repeated training sets reveal variationSix fitted responses per model from independent Gaussian noise at 80 fixed input settings. The noise standard deviation is 0.15, and axes are identical in the small and large sample figures. −2 −1 0 1 2 Input x 0.5 1.0 1.5 2.0 2.5 Predicted response Line −2 −1 0 1 2 Input x Quadratic −2 −1 0 1 2 Input x Flexible polynomial

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} \]

The fitted model families and noise level are unchanged. The axes are identical to the 12-reading comparison. The squared-error decomposition is at a fixed input, averaging over training samples and independent outcome 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?

A road scene and possible model outputsA schematic scene contains a car and pedestrian. Detection adds bounding boxes; semantic segmentation assigns an object or scene class to each visible region. These are explanatory drawings, not outputs from a trained model.Schematic camera view

Nearby pixels form edges, markings and object parts. How can the architecture use that structure?

An image is a structured array

An image enters a dense networkThe pixel grids flatten to a vector of twelve thousand two hundred eighty-eight input values. A dense layer connects each value to all 256 units; the drawn cells and circles are schematic subsets.RGB pixel grids64 × 64 × 3FlattenInput vector12,288 valuesSame measurementsA different arrangementSchematic grids and units represent the full tensor sizes.

\[ 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

An image enters a dense networkThe pixel grids flatten to a vector of twelve thousand two hundred eighty-eight input values. A dense layer connects each value to all 256 units; the drawn cells and circles are schematic subsets.RGB pixel grids64 × 64 × 3FlattenInput vector12,288 valuesDense layer256 unitsSchematic grids and units represent the full tensor sizes.

\[ (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

A filter moves over an imageA five by five input is scanned with a three by three vertical-edge filter. Multiply corresponding numbers and add them. The valid feature map is three by three with rows 3, 3, 0.Input pixels0011100111001110011100111Filter weights-101-101-101Feature mapUse the same nine weights at every position.

This small grayscale example uses a 3 × 3 patch and nine weights.

Convolutional layers and parameter sharing.

CNN Kernels

A filter moves over an imageA five by five input is scanned with a three by three vertical-edge filter. Multiply corresponding numbers and add them. The valid feature map is three by three with rows 3, 3, 0.Input pixels0011100111001110011100111Products001001001Feature mapUse the same nine weights at every position.

What value should the first feature-map location receive?

CNN Kernels

A filter moves over an imageA five by five input is scanned with a three by three vertical-edge filter. Multiply corresponding numbers and add them. The valid feature map is three by three with rows 3, 3, 0.Input pixels0011100111001110011100111Filter weights-101-101-101Feature map330330330Use the same nine weights at every position.

\[ 0+0+1+0+0+1+0+0+1=3 \]

The example bias is zero. This operation follows the cross-correlation convention used by deep-learning convolution layers: the displayed kernel is not flipped.

CNN Kernels

A filter moves over an imageA five by five input is scanned with a three by three vertical-edge filter. Multiply corresponding numbers and add them. The valid feature map is three by three with rows 3, 3, 0.Input pixels0011100111001110011100111Filter weights-101-101-101Feature map330330330Use the same nine weights at every position.

The next patch gives another response. The weights stay the same.

CNN Kernels

A filter moves over an imageA five by five input is scanned with a three by three vertical-edge filter. Multiply corresponding numbers and add them. The valid feature map is three by three with rows 3, 3, 0.Input pixels0011100111001110011100111Filter weights-101-101-101Feature map330330330Use the same nine weights at every position.

The filter responds where brightness changes across the patch. A uniform patch gives zero.

These are hand-chosen explanatory filter weights. During CNN training, the filter values are learned from the task loss.

The feature moves with the edge

A translated edge gives a translated responseWith shared weights and stride one, shifting this edge by two pixels shifts its response by two positions inside the shared valid region.0011111001111100111110011111001111133000330003300000001110000111000011100001110000111003300033000330The edge shifts; its response shifts with it.

Sharing weights lets the same pattern trigger the same response at different positions.

This shows translation equivariance in the overlapping valid region with stride one. It is not a claim of complete translation invariance. Padding, boundaries and subsampling affect the exact property.

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

One filter spans all RGB channelsAn RGB filter has a three by three grid of learned weights for each of three input channels. It sums the contributions into one response at each location.RedGreenBlueOne responseA scalar3 × 3 × 3 weights, plus one bias = 28 parameters per filter

Add the red, green and blue contributions at the same location.

Several filters learn several responses

Several filters give several feature mapsEight filters applied to a three-channel input have 8 times 28, or 224, trainable parameters and give eight output channels.RGB input3 channels8 learned filters28 parameters each8 output maps224 trainable parameters

Each output channel has its own filter and bias. All positions within a channel share those parameters.

Stride controls where the filter is evaluated

Stride and paddingA three by three filter with stride 1 and padding 0 on the original five by five image gives an output of size 3 by 3. Dots show window centres.0011100111001110011100111Input 5 × 5Stride 1Output 3 × 3

With stride 1, move the window by one pixel.

A larger stride samples fewer positions

Stride and paddingA three by three filter with stride 2 and padding 0 on the original five by five image gives an output of size 2 by 2. Dots show window centres.0011100111001110011100111Input 5 × 5Stride 2Output 2 × 2

With stride 2, move by two pixels. The feature map has fewer locations.

Zero-padding at the image border

Stride and paddingA three by three filter with stride 1 and padding 1 on the original five by five image gives an output of size 5 by 5. Dots show window centres.0000000000111000011100001110000111000011100000000Input 7 × 7Stride 1Output 5 × 5

A one-pixel border of zeros lets a 3 × 3, stride-1 filter keep the original height and width.

This is symmetric zero-padding. Keeping dimensions with the usual same-padding convention depends on the stride; stride greater than one normally reduces spatial dimensions.

How large is the output map?

\[ N_{\mathrm{out}}=\left\lfloor\frac{N+2P-K}{S}\right\rfloor+1 \]

Input size NKernel KPadding PStride S
7312

What are the output height and width? What if we use eight filters?

Dilation is one, input is square and padding is symmetric. The same formula applies independently to height and width.

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?

Max pooling over a feature mapEach two by two window keeps its largest value. The pooled feature map is 3, 4 in the first row and 5, 3 in the second.1320021451232001Input feature mapPooled feature map2 × 2 windows, stride 2

Keep the largest response in each 2 × 2 window. What are the four outputs?

Four local maxima remain

Max pooling over a feature mapEach two by two window keeps its largest value. The pooled feature map is 3, 4 in the first row and 5, 3 in the second.13200214512320013453Input feature mapPooled feature map2 × 2 windows, stride 2

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.

Pooling and spatial downsampling.

Later units can see a wider region

A deeper unit sees a larger regionWith stride one and no dilation, two consecutive three by three convolutional layers give an effective five by five receptive field.Original inputFirst 3 × 3 layerNext 3 × 3 layerOne unit after two such layers depends on a 5 × 5 input patch.

The receptive field is the input region that can affect a particular unit.

A complete small CNN

A complete small image classifierTwo convolution and pooling stages create sixteen feature maps. Spatial averaging gives sixteen values; a dense classification head produces three logits and softmax probabilities.RGB image64 × 64 × 3Conv + ReLU64 × 64 × 8Pool32 × 32 × 8Conv + ReLU32 × 32 × 16Pool16 × 16 × 16Average each feature map16 summary valuesLinear head + softmax3 class probabilities

Local features become larger-scale features, then a final head predicts the class.

This architecture has 224 parameters in the first convolution, 1168 in the second and 51 in the three-class dense head: 1443 total. Pooling and spatial averaging add no trainable parameters. Convolutions use 3×3 kernels, stride 1 and padding 1. The diagram writes height×width×channels; framework tensor-axis conventions can differ.

Features can build on simpler features

A schematic feature hierarchyIllustrative edge responses combine into curves and parts, and then object responses. These are explanatory drawings, not measured feature visualisations from a particular model.EdgesCurves and cornersPartsObjectsSchematic examples of features that successive layers can combine.

Early local responses can combine into curves, parts and more complex shapes.

Zeiler and Fergus, Visualizing and Understanding Convolutional Networks.

The drawing is a schematic interpretation of hierarchical feature composition, not a display of actual activations. A learned unit need not correspond to one easily named visual concept.

Finding objects is a different output task

A road scene and possible model outputsA schematic scene contains a car and pedestrian. Detection adds bounding boxes; semantic segmentation assigns an object or scene class to each visible region. These are explanatory drawings, not outputs from a trained model.CarPedestrianSchematic output labels

Detection predicts both object classes and their locations. One scene can contain several objects.

The labels and boxes are schematic examples, not predictions from a trained detector. Detection commonly combines classification and localisation losses.

A class for each pixel

A road scene and possible model outputsA schematic scene contains a car and pedestrian. Detection adds bounding boxes; semantic segmentation assigns an object or scene class to each visible region. These are explanatory drawings, not outputs from a trained model.Schematic output labels

Semantic segmentation assigns classes to pixel locations, such as road, sky, car or pedestrian.

Schematic class regions demonstrate the output format. The model learns from labelled masks, often with a per-pixel classification loss. This is not an instance-segmentation example.

The target determines the head and loss

TaskTraining targetWhat the loss compares
Image classificationOne class per cropClass probabilities
Object detectionClasses and boxesLabels and positions
Semantic segmentationA class at each pixelPixel 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}}}} \]

ClassScoreProbability
Car30.665
Sky10.090
Pedestrian20.245

The labels changed. The conversion from scores to probabilities stayed the same.

The observed pixel class supplies the loss

The same learning loop in different tasksThe image example uses an input, a parameterised network, a prediction and a target-dependent loss. The backward pass computes gradients, and the optimiser updates the trainable parameters.Pixel valuesInput imageImage networkParameters θClass probabilities3 pixel classesCross-entropyPixel label yTraining targetBackward pass: gradients of the loss

\[ \ell=-\ln p_{\mathrm{car}}\approx0.408 \]

A labelled car pixel supplies an error signal that travels back to the image network.

Illustrative probabilities. A segmentation cost usually combines contributions across labelled pixels; real label sets commonly include further classes such as road. This three-class example isolates the softmax-and-cross-entropy calculation.

Residual connections

A residual connectionA learned branch F(x) is added to a shortcut carrying x. Matching tensor shapes are required. A projection can adjust shapes when needed.InputxLearned branchF(x)Outputx + F(x)Shortcut

\[ y=x+F(x) \]

Why might carrying x along this shortcut make a deep network easier to train?

Residual learning and optimisation.

Residual connections

A residual connectionA learned branch F(x) is added to a shortcut carrying x. Matching tensor shapes are required. A projection can adjust shapes when needed.InputxLearned branchF(x)Outputx + F(x)ShortcutGradients also have a path through the shortcut.

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.

Matching shapes are required for addition. A projection can adapt a shortcut when shapes differ. The direct path helps optimisation but does not guarantee that every deep model trains successfully.

A camera-to-steering example

The training examples pair images with actions

Training views and conditionsThese synthetic road views illustrate steering labels or lighting changes. Steering angles are illustrative, with negative left and positive right.Driver: −8°Driver: 0°Driver: +8°

We have camera views and the driver’s steering command at the same time.

How could we use these pairs to teach the network?

Angles are illustrative. Negative is left and positive is right.

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 same learning loop in different tasksThe steering example uses an input, a parameterised network, a prediction and a target-dependent loss. The backward pass computes gradients, and the optimiser updates the trainable parameters.Pixel valuesCamera imageCNNParameters θPredicted angleâSquared errorObserved angle aTraining targetForward pass with the current weights

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

The same learning loop in different tasksThe steering example uses an input, a parameterised network, a prediction and a target-dependent loss. The backward pass computes gradients, and the optimiser updates the trainable parameters.Pixel valuesCamera imageCNNParameters θPredicted angleâSquared errorObserved angle aTraining targetBackward pass: gradients of the loss

\[ \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

The same learning loop in different tasksThe steering example uses an input, a parameterised network, a prediction and a target-dependent loss. The backward pass computes gradients, and the optimiser updates the trainable parameters.Pixel valuesCamera imageCNNParameters θPredicted angleâSquared errorObserved angle aTraining targetBackward pass: gradients of the lossOptimiser update: θnew = θ − η ∇θJThen run the model again using the updated parameters.

Change the trainable parameters, then make another prediction with the updated model.

What exactly do driver labels teach?

Training views and conditionsThese synthetic road views illustrate steering labels or lighting changes. Steering angles are illustrative, with negative left and positive right.Driver: −8°Driver: 0°Driver: +8°

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.

Ross and colleagues, imitation learning under changing observation distributions.

Driving changes the next input

Predictions change later inputsThe diagrams illustrate how steering changes the next camera view. Small errors can move the system into situations missing from the expert demonstrations. This is a schematic sequence, not a measured trajectory.A small errorA changed next viewAnother prediction

The model’s own actions change what it sees next. Errors can take it away from familiar training situations.

The frames illustrate a dependency, not a measured trajectory. The original camera-to-steering work includes recovery-oriented data and augmentations. Camera-to-steering research. Sequential imitation learning.

A new condition can change the inputs

Training views and conditionsThese synthetic road views illustrate steering labels or lighting changes. Steering angles are illustrative, with negative left and positive right.DaylightNight

A model that works on daylight recordings still needs evidence about night-time inputs.

A larger driving system has several tasks

A broader driving systemPerception, prediction, planning and control are distinct tasks in this illustrative system decomposition. A camera-to-steering research model covers a particular learning task, not every requirement of a driving system.PerceptionWhat is around us?PredictionWhat might move?PlanningWhich path?ControlHow to follow it?CNN features can contribute to a larger driving system.

An end-to-end model connects inputs directly to a target action. Other designs make intermediate tasks explicit.

This is an illustrative decomposition of perception, prediction, planning and control. The point is to identify the learned task and evaluate it in the context where its outputs will be used, without treating steering prediction as the whole driving problem.

Completing a route instruction

A simple route to the libraryThe next junction has the library on the left. This schematic map grounds an example navigation instruction.LibraryYouNext junction

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 ____

Words in a route instructionThe example treats the words Turn left at the next as tokens, and predicts the next word. Actual tokenisers can split words into smaller units.Word tokenTurnWord tokenleftWord tokenatWord tokentheWord tokennextWord token?One word per token in this simplified example.

Use the earlier words as input and predict the next one.

Words are treated as tokens to keep this example concrete. Actual tokenisation may split a word into smaller pieces. The map grounds the instruction for the audience; it is not silently supplied as a model input.

A language model is another prediction function

The same learning loop in different tasksThe words example uses an input, a parameterised network, a prediction and a target-dependent loss. The backward pass computes gradients, and the optimiser updates the trainable parameters.Earlier wordsText prefixLanguage networkParameters θNext-word probsp₁, p₂, p₃Cross-entropyObserved next wordTraining targetForward pass with the current weights

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 vocabularyScoreProbability
junction30.665
roundabout20.245
bridge10.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

The same learning loop in different tasksThe words example uses an input, a parameterised network, a prediction and a target-dependent loss. The backward pass computes gradients, and the optimiser updates the trainable parameters.Earlier wordsText prefixLanguage networkParameters θNext-word probsp₁, p₂, p₃Cross-entropyObserved next wordTraining targetBackward pass: gradients of the loss

\[ \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 same learning loop in different tasksThe words example uses an input, a parameterised network, a prediction and a target-dependent loss. The backward pass computes gradients, and the optimiser updates the trainable parameters.Earlier wordsText prefixLanguage networkParameters θNext-word probsp₁, p₂, p₃Cross-entropyObserved next wordTraining targetBackward pass: gradients of the lossOptimiser update: θnew = θ − η ∇θJThen run the model again using the updated parameters.

The optimiser adjusts the model using many such training examples.

Autoregressive language modelling.

One sentence supplies several training pairs

Earlier wordsObserved next word
Turnleft
Turn leftat
Turn left atthe
Turn left at thenext
Turn left at the nextjunction

\[ 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?

Words in a route instructionThe example treats the words Turn left at the next as tokens, and predicts the next word. Actual tokenisers can split words into smaller units.Word tokenTurnWord tokenleftWord tokenatWord tokentheWord tokennextWord token?One word per token in this simplified example.

To produce the next word, do we need a forward pass, a backward pass, or a weight update?

Ordinary generation uses forward passes

Words in a route instructionThe example treats the words Turn left at the next as tokens, and predicts the next word. Actual tokenisers can split words into smaller units.Word tokenTurnWord tokenleftWord tokenatWord tokentheWord tokennextWord tokenjunctionOne word per token in this simplified example.

Changes as text growsStays fixed during ordinary generation
The input prefix and hidden activationsThe learned weights

Select a word, append it to the input, then run the model forwards again.

This describes ordinary inference with fixed parameters. Additional adaptation is a separate procedure. Inference without gradient updates.

A completed instruction is still a prediction

“Turn left at the next junction.”

Words in a route instructionThe example treats the words Turn left at the next as tokens, and predicts the next word. Actual tokenisers can split words into smaller units.Word tokenTurnWord tokenleftWord tokenatWord tokentheWord tokennextWord tokenjunctionOne word per token in this simplified example.

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 on two different mapsTurn left at the next junction is fluent on either map, but it reaches the library only on the left map. Route correctness needs information about the actual route.LibraryYouLibraryYouLeft turn reaches the libraryThe same words give a wrong turn

The same sentence is fluent on both maps. Checking the route requires information about the actual destination.

A schematic distinction between next-word likelihood and route correctness. The text-only prefix example has not been given the map. Supplying reliable route information and an appropriate objective or evaluation is a different task requirement.

The input, target and loss define what is learned

TaskObserved targetTraining penalty
Image labelsCar, sky or pedestrianCross-entropy
SteeringRecorded angleSquared error
Text continuationObserved next wordCross-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

A campus-card reading taskThree fictional photo-card designs have student, staff and visitor types. The example separates visual card-type recognition from looking up current membership.CAMPUSStudentA104CAMPUSStaffS207CAMPUSVisitorV303Fictional cards for a camera-based library 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

A visual prediction and a register lookupThe image model classifies the type of card. A separate reading of the card ID and a lookup of its current record determine student membership. The model does not infer membership from facial appearance.Read the cardType and card IDLook up the IDCurrent registerUse the recordCurrent student?The image model predicts card type.A separate ID read and register lookup check current membership.

For the visual task, classify the card as student, staff or visitor. A separate ID read and register lookup check current status.

Fictional example, not Durham access rules. Card-type classification does not establish current membership or authenticate a person. The status lookup uses authoritative records. A readable card ID can support a conventional lookup without needing visual inference of student status.

An ordinary lookup checks current student status

Card IDPrinted card typeCurrent student record
A104StudentCurrent
A205StudentNo longer current
S207StaffNot a student record

Read the identifier and look up its current record. The image model serves the visual part of the task.

Fictional records illustrate the separation between image classification and current membership. This is not an access policy; a real library may admit several user categories.

What examples would you collect?

Examples of the intended inputSeveral fictional student cards vary in holder ID, angle and brightness. Collect examples of every output category under relevant camera conditions.CAMPUSStudentA104CAMPUSStudentA205CAMPUSStudentA318Different cards, camera angles and lighting conditions

What should the input images look like, and where would their labels come from?

Labelled card images

A campus-card reading taskThree fictional photo-card designs have student, staff and visitor types. The example separates visual card-type recognition from looking up current membership.CAMPUSStudentA104CAMPUSStaffS207CAMPUSVisitorV303Fictional cards for a camera-based library reader

Collect varied photos of different cards. Their known card types supply the labels.

Known cardVisual class label
A104Student
S207Staff
V303Visitor
These are fictional card IDs. Card-type labels come from known card records. The portrait on a card is not treated as evidence that somebody looks like a student.

How should the images be split?

A cardholder-based validation splitThe first view shows two photographs of the same fictional card in different splits. The answer holds out a different cardholder to test generalisation to new cards.CAMPUSStudentA104TrainCAMPUSStudentA104ValidationTwo photos, but the same cardholder.

Would a second photo of the same card give a strong test of performance on a new cardholder?

Hold out different cardholders

A cardholder-based validation splitThe first view shows two photographs of the same fictional card in different splits. The answer holds out a different cardholder to test generalisation to new cards.CAMPUSStudentA104TrainCAMPUSStudentA205ValidationA new cardholder stays out of training.

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?

A pretrained image backbone gets a new taskDownload pretrained weights for an existing architecture, replace its original classifier with a three-class card-type head and train that head. Selected backbone layers can later be fine-tuned if useful.Card imagePixelsPretrained ResNetImage feature vectorOutput head1,000 old classes

We have labelled card images. Do we also need to build and train the whole feature extractor ourselves?

Use pretrained ResNet weights

A pretrained image backbone gets a new taskDownload pretrained weights for an existing architecture, replace its original classifier with a three-class card-type head and train that head. Selected backbone layers can later be fine-tuned if useful.Card imagePixelsPretrained ResNetImage feature vectorOutput head1,000 old classes

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.

The paper describes the architecture. A pretrained checkpoint supplies learned parameter values. Useful transfer depends on the new domain and task. Transfer-learning tutorial.

Replace the classifier for the new labels

A pretrained image backbone gets a new taskDownload pretrained weights for an existing architecture, replace its original classifier with a three-class card-type head and train that head. Selected backbone layers can later be fine-tuned if useful.Card imagePixelsPretrained ResNetImage feature vectorOutput head3 card typesTrain the new headKeep these weights fixed first

Keep the backbone fixed initially and train a new head for the three card categories.

Adapt more of the model if needed

A pretrained image backbone gets a new taskDownload pretrained weights for an existing architecture, replace its original classifier with a three-class card-type head and train that head. Selected backbone layers can later be fine-tuned if useful.Card imagePixelsPretrained ResNetImage feature vectorOutput head3 card typesTrain the new headAdapt selected layers

Validation may justify fine-tuning selected backbone layers, often with a smaller learning rate.

Frozen feature extractors and fine-tuning.

Keep the input convention with the weights

Part of the inputA practical starting point
Size and cropUse the pretrained model’s supplied transform
Channels and numerical scaleMatch its expected input convention
Card variationsTrain with appropriate lighting and camera-angle variation

Check that the card and relevant markings remain visible after preprocessing.

Pretrained weights and transforms.

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.

Torchvision ResNet18 API.

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.

The new Linear head has trainable parameters by default; optimise model.fc.parameters(). Keeping the frozen ResNet backbone in eval mode fixes BatchNorm running statistics. The Linear head has the same behaviour in train and eval mode. This is setup, not the head-training loop.

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.

batch contains card images processed with the supplied transform and stacked in the expected batch/channel/height/width order. This is ordinary inference. Evaluate against held-out cardholders; the register lookup is a separate step from the image probabilities.

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.