Summative assessment
- The summative assignment is now released.
- Part A deadline: 8 December.
- Part B deadline: 9 December.
Recap: the familiar linear score
The fitting method still combines features with weights. Changing the features changes the boundaries we can represent.
What did we change?
| Input table | Columns |
|---|---|
| Original measurements | x₁, x₂ |
| Quadratic features | 1, x₁, x₂, x₁², x₂², x₁x₂ |
\[ z=w_0+w_1x_1+w_2x_2+w_3x_1^2+w_4x_2^2+w_5x_1x_2 \]
Each added column has a weight. We choose the feature map; fitting learns the coefficients.
Feature values determine the score
\[ z=2-4(x_1^2+x_2^2) \]
| Point | x₁² + x₂² | Score z |
|---|---|---|
| A: (0.4, 0.3) | 0.25 | +1 |
| B: (0.8, 0.6) | 1 | −2 |
| C: (0.5, 0.5) | 0.5 | 0 |
We can score locations between the examples
Evaluate the same score on a grid. Each location supplies its own feature values.
Filling the grid reveals the regions
The boundary joins locations with score zero. A curved boundary appears in the original coordinates.
The same idea with more polynomial terms
Terms up to degree 3 let a weighted score follow this more complicated gap.
The part reaches the clear leaf
Temperature 8 sends this part right. Vibration 4 then sends it to the clear leaf.
The rule on the measured parts
The questions divide the measurement plane into regions. This small rule classifies all 16 displayed parts correctly.
Trees learnt their own questions
Training tries candidate questions and favours splits that separate the labels. The thresholds can come from data.
A forest combined several trees
On the alignment example, different training samples gave different trees. The forest combined their predictions.
Neural networks
Feedforward models and learned features
Today we will cover
- Combine sigmoid units into a network.
- Follow the loss backwards to every layer.
- Build more flexible functions with hidden layers.
- Understand scaling and practical architecture choices.
One line through the Iris measurements
Petal length and width overlap for these two species. Logistic regression makes one straight decision boundary.
Logistic regression is one unit
\[ z=w_lx_l+w_wx_w+b,\qquad p=\sigma(z) \]
A weighted sum followed by a sigmoid gives the probability of virginica.
What if we use three sigmoid units?
Each unit has its own weights and bias, so each has its own straight half-activation line.
Three units become a hidden layer
\[ h_j=\sigma(W_{jl}x_l+W_{jw}x_w+b_j) \]
The next layer combines three learned feature values. We scale the two inputs, as before.
The first hidden feature
Colour shows h₁ from low to high. The straight line marks h₁ = 0.5.
The second hidden feature
Its weights point in a different direction. The same flower supplies a different feature value.
The third hidden feature
The model now has three smooth responses to combine, rather than only the two original measurements.
The three responses combined
Together, the three units can make a curved boundary.
Combine the three hidden outputs
\[ z=v_1h_1+v_2h_2+v_3h_3+c \]
\[ p=\sigma(z)=\sigma(v_1h_1+v_2h_2+v_3h_3+c) \]
This is another weighted sum and sigmoid. Its inputs are the hidden features.
A forest combined tree predictions. Here the combination itself has weights that training can learn.
The same loss trains both sets of weights
\[ \ell=-y\ln p-(1-y)\ln(1-p) \]
The loss depends on the output weights and on the weights inside each hidden feature.
Follow one flower forwards
For a virginica flower: length 5 cm, width 1.5 cm, so y = 1.
| Calculation | Value |
|---|---|
| Scaled inputs | xₗ = 0.146, x_w = -0.373 |
| Three hidden activations | h1 = 0.367, h2 = 0.439, h3 = 0.006 |
| Output probability | p = 0.379 |
| Cross-entropy loss | −ln(p) = 0.969 |
Start at the output
\[ \frac{\partial\ell}{\partial z}=p-y \]
For this flower, p − y = -0.621. The model should raise its final score.
Back to the hidden features
\[ \frac{\partial\ell}{\partial a_j}=(p-y)v_jh_j(1-h_j) \]
Each hidden unit receives a signal through its output weight, multiplied by its own sigmoid slope.
Reach the input weights
\[ \frac{\partial\ell}{\partial W_{jl}}=\frac{\partial\ell}{\partial a_j}x_l,\qquad \frac{\partial\ell}{\partial W_{jw}}=\frac{\partial\ell}{\partial a_j}x_w \]
The gradient reaches both sets of weights. The measured petal length and width stay fixed.
Change the parameters using those gradients
\[ \theta_{\mathrm{new}}=\theta-\eta\frac{\partial\ell}{\partial\theta} \]
| One parameter | Before | Gradient | After |
|---|---|---|---|
| Output weight v₁ | -6.107 | -0.228 | -6.061 |
| Hidden length weight W₁ₗ | -7.350 | 0.128 | -7.375 |
| Hidden width weight W₁w | 0.870 | -0.329 | 0.936 |
Learning rate η = 0.2. The same step updates all weights and biases.
Before the update
The ringed virginica flower receives p = 0.38. Its loss is 0.97.
Run the changed network forwards again
The same flower now receives p = 0.61. Its loss falls to 0.49.
The three features make one curved boundary
Dashed lines belong to the hidden units. The solid boundary is where their combined output gives p = 0.5.
One model, with features learned from data
The final boundary can curve even though each first-layer half-activation line is straight.
What if we add many more units and layers?
More learned intermediate features give the model more ways to vary its response.
A much more flexible Iris boundary
This 2 → 16 → 16 → 8 → 1 sigmoid network makes intricate regions. Check whether those details help new flowers using held-out data.
Return to XOR
A single straight line cannot separate these labels. Can two hidden sigmoid units help?
One hidden unit responds after the first corner
\[ h_1=\sigma(10(x_1+x_2-0.5)) \]
Another responds near the far corner
\[ h_2=\sigma(10(x_1+x_2-1.5)) \]
Their difference picks out the middle band
\[ p=\sigma(10h_1-10h_2-5) \]
Work through the input (1, 0)
\[ x_1+x_2=1 \]
\[ h_1=\sigma(5)\approx0.993,\qquad h_2=\sigma(-5)\approx0.007 \]
The first hidden unit is strongly active; the second is barely active.
The output recognises the positive corner
\[ z=10(0.993)-10(0.007)-5\approx4.87 \]
\[ p=\sigma(4.87)\approx0.992 \]
The two original inputs have become useful intermediate features.
All four XOR predictions
| Input | Hidden h₁ | Hidden h₂ | Output p | Label |
|---|---|---|---|---|
| (0, 0) | 0.007 | 0.000 | 0.007 | 0 |
| (1, 0) | 0.993 | 0.007 | 0.992 | 1 |
| (0, 1) | 0.993 | 0.007 | 0.992 | 1 |
| (1, 1) | 1.000 | 0.993 | 0.007 | 0 |
Thresholding the final probability at 0.5 gives all four labels correctly.
Learn a tolerance region
Recall the laser-alignment scenario. The blue parts are within tolerance. Start a 2 → 8 → 1 sigmoid network with random weights.
After 100 updates
The same loss updates the output combination and the hidden responses.
After 1,200 updates
The learned features now combine to enclose the central region.
Look inside one learned hidden unit
One unit alone still has a straight half-activation line.
Several learned features shape the output
The output combines all eight feature values. These are four of the learned responses.
Add another hidden layer
The new units receive the first layer’s feature values. Their inputs are already learned transformations.
Repeat the same weighted-sum-and-sigmoid calculation
\[ h_j=\sigma(W_{jl}x_l+W_{jw}x_w+b_j) \]
\[ r_k=\sigma(U_{k1}h_1+U_{k2}h_2+U_{k3}h_3+d_k) \]
\[ p=\sigma(v_1r_1+v_2r_2+v_3r_3+c) \]
Each layer uses the outputs of the layer before it.
The same loss trains all three sets of weights
\[ \ell=-y\ln p-(1-y)\ln(1-p) \]
We have extended the chain of dependencies.
Run a forward pass
Measurements → first hidden features → second hidden features → probability → loss.
Start at the output
\[ \frac{\partial\ell}{\partial z}=p-y \]
The calculation at the far right is exactly the same as before.
Back to the second hidden layer
\[ \frac{\partial\ell}{\partial a_k^{(2)}}=(p-y)v_kr_k(1-r_k) \]
Use the output weight and this unit’s sigmoid slope.
Back to the first hidden layer
\[ \frac{\partial\ell}{\partial a_j^{(1)}}=h_j(1-h_j)\sum_k U_{kj}\frac{\partial\ell}{\partial a_k^{(2)}} \]
Add the gradient contributions from every later unit.
Reach the input weights
\[ \frac{\partial\ell}{\partial W_{jl}}=\frac{\partial\ell}{\partial a_j^{(1)}}x_l \]
The petal measurements still stay fixed. The longer chain gives gradients for the earlier weights.
The optimiser updates every layer
| Parameters | What changes? |
|---|---|
| First hidden weights and biases | Features of the measurements |
| Second hidden weights and biases | Features of the first features |
| Output weights and bias | How the final features combine |
\[ \boldsymbol{\theta}_{\mathrm{new}}=\boldsymbol{\theta}-\eta\nabla_{\boldsymbol{\theta}}J \]
The gradient of a batch cost averages the example contributions before the update.
The sigmoid can pass back a very small slope
\[ \sigma\prime(a)=\sigma(a)(1-\sigma(a)) \]
At large positive or negative scores, changing the score barely changes the hidden output.
Small hidden slopes can multiply through the network
Repeated small factors can make early-layer gradients tiny. Those layers can then learn slowly.
A ReLU supplies a different response
\[ \mathrm{ReLU}(a)=\max(0,a) \]
What does it output at −2 and at 3?
Reading the ReLU
| Input score | Output | Local slope |
|---|---|---|
| −2 | 0 | 0 |
| 3 | 3 | 1 |
On its positive side, ReLU passes the slope through without a sigmoid factor.
The bias moves the bend
Learning the bias learns where this hidden feature starts responding.
The weight changes the slope
Learning input weights changes the strength and direction of the response.
Can extra layers create a curve on their own?
Suppose we remove the activations. Can these two weighted sums produce a curved response?
Two weighted sums still give a straight line
\[ h=2x-3,\qquad z=4h+1 \]
\[ z=4(2x-3)+1=8x-11 \]
Without a nonlinear activation, these two layers collapse into a single straight-line calculation.
A nonlinear activation changes what we can represent
The bend remains after combining the layers. Stacking linear calculations alone cannot create it.
Choose a hidden activation
Sigmoid, tanh and ReLU change both the functions we can represent and the gradients used in training.
The output activation still follows the prediction task.
Several units can supply different bends
These ReLU units start responding at different input values.
Combine the bends into a more complex function
\[ \hat y=0.5+2.8h_1-4.8h_2+4.8h_3 \]
A network for this numerical response
One input, three hidden units and a linear output. We predict a number, so the final layer need not be a sigmoid.
More units follow more of the curve
Extra changes of slope let the response follow finer detail.
A finer approximation
Simple units can combine to represent a complicated function.
Fitting the observed interval is only part of the task
A flexible network may fit the observed range well and still behave poorly beyond it.
Width supplies parallel features; depth composes them
| Change | What it offers |
|---|---|
| More units in a layer | More feature responses at the same stage |
| More hidden layers | Further transformations of learned features |
The useful choice depends on the pattern and the data.
A first layer can measure departures from a target
\[ |x_1|=\mathrm{ReLU}(x_1)+\mathrm{ReLU}(-x_1) \]
For the alignment example, combine positive and negative departures in each coordinate.
A later layer can combine them into a local response
\[ h=\mathrm{ReLU}(1-|x_1|-|x_2|) \]
The second stage makes a local feature from the first stage’s features.
Why did neural networks become so successful?
Learned features can be scaled to much larger problems.
From Iris to a large recommendation dataset
Iris is a small teaching dataset. Real recommendation tasks can draw on enormous collections of interactions.
Spotify Million Playlist Dataset, released for research in 2018.
An order-of-magnitude estimate
Imagine a music service with 100 million active listeners, each producing 10 recorded interactions a day.
\[ 10^8\ \mathrm{listeners}\times10\ \mathrm{events/day}=10^9\ \mathrm{events/day} \]
\[ 365\times10^9\approx3.7\times10^{11}\ \mathrm{events/year} \]
Illustrative assumptions. This estimates a hypothetical service, rather than Spotify’s internal dataset.
The inputs can contain much richer information
| For a candidate track | Possible input information |
|---|---|
| Listener | Recent listening and longer-term preferences |
| Track | Audio properties and learned track features |
| Context | Time, device and the surrounding playlist |
For example, predict the chance that this listener skips this track.
The same learned weights process a whole batch
\[ \mathbf{H}=\sigma(\mathbf{X}\mathbf{W}+\mathbf{b}) \]
| Object | Meaning |
|---|---|
| Rows of X | Different examples in one batch |
| W | One shared set of layer weights |
| Rows of H | Their hidden feature values |
These large matrix calculations can use parallel hardware efficiently.
Data, capacity and computation can grow together
A useful network can learn more features from more examples when we can afford to train it.
Hestness and colleagues, empirical scaling across several deep-learning tasks.
More rows need useful new information
More recordings of the same narrow situation may add little. Broader users, contexts and examples can teach the model more.
Check on genuinely held-out cases. For listening data, a time-based or user-based split may answer a more useful question than randomly splitting related events.
Choosing a neural network architecture
What do the familiar defaults and templates actually buy us?
A template you may encounter
MLPClassifier(
hidden_layer_sizes=(256, 128),
activation="relu",
solver="adam"
)
Two hidden layers, with 256 and 128 units. ReLU transforms their outputs; Adam updates the parameters.
scikit-learn’s actual default is one hidden layer of 100 units, with ReLU and Adam.
Why 256 then 128?
| Choice | What it means |
|---|---|
| 256 units | Many parallel feature responses |
| 128 units next | A further combination of those responses |
| Powers of two | A common convention, rather than a statistical requirement |
These numbers are starting choices. The validation results must justify the capacity.
Count the parameters before choosing the width
\[ P_{\mathrm{layer}}=(n_{\mathrm{in}}+1)n_{\mathrm{out}} \]
| Architecture for two inputs | Trainable parameters |
|---|---|
| 2 → 3 → 1 | 13 |
| 2 → 16 → 1 | 65 |
| 2 → 256 → 128 → 1 | 33,793 |
The +1 counts the bias for each output unit. A wider template can be a large jump for a tiny dataset.
Does doubling the width double the size?
Both hidden widths double. Do we get twice as many trainable parameters, or more?
The biggest weight matrix becomes four times larger
\[ (2\times256)(2\times128)=4(256\times128) \]
| Parameters | 256 → 128 | 512 → 256 |
|---|---|---|
| Weights between hidden layers | 32,768 | 131,072 |
| All weights and biases | 33,793 | 133,121 |
The whole model is almost four times larger. Most parameters connect the two hidden layers.
Does every layer need to shrink?
A narrower layer can encourage compression. Making it too narrow can discard useful distinctions.
Some networks expand before compressing. Choose the shape for the information the task needs.
Why start with ReLU?
It is cheap to compute, supplies a nonlinearity, and has slope 1 on its positive side.
Units that stay negative can become inactive. ReLU still needs sensible scaling, initialisation and learning rates.
Why is Adam a common starting choice?
| Adam uses | Why it can help |
|---|---|
| A moving average of gradients | A less erratic update direction |
| A moving average of squared gradients | Different adjustment scales for different parameters |
It is a practical starting optimiser. We still choose a learning rate and check the training curves.
Initialisation must let hidden units differ
Identical incoming and outgoing parameters can give identical gradients. Extra units then repeat the same feature.
Different starting weights let features develop differently
Random initial weights break that symmetry. Different units can learn different useful responses.
Keep the forward and backward signals on a useful scale
| Part of the model | A practical starting point |
|---|---|
| Input measurements | Scale using the training data |
| Sigmoid or tanh layers | Xavier/Glorot-style initialisation |
| ReLU layers | He/Kaiming-style initialisation |
The layer width and activation affect how signals grow or shrink. Libraries provide standard initialisers.
Compare a few small architectures first
| Candidate hidden layers | What we are testing |
|---|---|
| (16,) | One modest layer |
| (32,) | More parallel features |
| (32, 16) | A second stage of composition |
Use the same data split, a comparable tuning effort and more than one random seed. Let validation performance guide the choice.
Match the output to the prediction task
| Task | Final output | Loss |
|---|---|---|
| Virginica or versicolor | One sigmoid probability | Binary cross-entropy |
| A numerical response | A linear value | For example, mean squared error |
The hidden architecture and the output calculation solve different parts of the problem.
Match the architecture to the structure of the data
| Input structure | Architecture to consider |
|---|---|
| A fixed vector of measurements | A feedforward dense network |
| Neighbouring pixels in images | Convolutional networks |
| Sequences and relationships between elements | Attention-based architectures |
Next lecture: how those specialised architectures build on learned features and backpropagation.
Today we covered
- Hidden units learn features of their inputs.
- Their outputs combine to make curved boundaries and complex functions.
- Backpropagation supplies gradients throughout the network.
- Architecture, useful data and computation shape what we can learn.