Part A is a project-style assignment, available for around three weeks. Part B is a 24-hour assignment.
Part A uses simulated collider data to investigate a classification problem. The notebook provides the background and instructions.
Does this tell us that predictions on new examples have improved?
Training loss measures the fit to examples used to update the model. The held-out loss checks predictions on other examples.
In the sensor example, validation loss was lowest at epoch 17. Training loss continued to fall after that.
A low training loss and a higher validation loss can indicate overfitting. Check the data split and measurement settings before changing the model.
Bias is a systematic miss. Variance is the sensitivity of the fit to the training sample.
At a cutoff of 0.55, this model flags four of the six defects and also flags two clear parts.
\[ \mathrm{TPR}=\frac{\mathrm{TP}}{\mathrm{TP}+\mathrm{FN}}\qquad\mathrm{FPR}=\frac{\mathrm{FP}}{\mathrm{FP}+\mathrm{TN}} \]
Sweeping the cutoff across all the scores gives the full curve. Each point represents a different balance of true positives and false positives.
Each candidate setting uses the same folds. Compare its average performance across the held-out folds.
These simulated readings flatten at high drive voltages. Where is the response most sensitive?
The straight-line fit uses the same slope across the whole range.
The horizontal axis is now \(\phi(x)=1-\mathrm{e}^{-x/(3\,\mathrm{V})}\). The transformed readings sit close to a line.
\[ \hat y=b+w\phi(x) \]
The feature supplies the shape. Fitting sets the offset and amplitude.
In this toy example, compare an 80 m² house with a 90 m² house in each neighbourhood.
| Neighbourhood | At 80 m² | At 90 m² | Increase |
|---|---|---|---|
| A | £220,000 | £240,000 | £20,000 |
| B | £460,000 | £500,000 | £40,000 |
The effect of floor area depends on the neighbourhood. A location feature that only shifts the intercept gives both areas the same slope.
Imagine starting with neighbourhood A’s price guide. In neighbourhood B, the same extra space adds more to the price.
| For an extra 10 m² | Contribution to the price increase |
|---|---|
| Area effect in A | £20,000 |
| Additional effect of being in B | £20,000 |
| Total increase in B | £40,000 |
The model needs a way for neighbourhood B to change how much each extra square metre contributes.
| House | Floor area | Area × neighbourhood-B indicator |
|---|---|---|
| 80 m² in A | 80 | 0 |
| 90 m² in A | 90 | 0 |
| 80 m² in B | 80 | 80 |
| 90 m² in B | 90 | 90 |
The new feature is zero in A. In B, it grows with floor area. A weight on this feature adds B’s extra contribution for each square metre.
An alignment camera records where each shot lands. A shot passes if it is within 1.2 mm of the target centre.
The shots outside tolerance surround the acceptable region. Which feature would make this decision simpler?
\[ r^2=x_1^2+x_2^2 \]
| Offset (mm) | Squared distance (mm²) | Result |
|---|---|---|
| (1, 0) | 1 | Pass |
| (1, 1) | 2 | Outside tolerance |
The tolerance corresponds to squared distance 1.44 mm².
Each camera reading has become a single squared distance. The cutoff separates the passing and failing shots.
\[ x_1^2+x_2^2=1.44 \]
The new target position is at (0.65, −0.45) mm. How should the distance feature change?
\[ r^2=(x_1-0.65)^2+(x_2+0.45)^2 \]
\[ (x_1,x_2)\ \longmapsto\ (x_1,x_2,x_1^2,x_1x_2,x_2^2) \]
We retain the original coordinates and add their squares and product. Each term becomes another column in the input table.
| Original reading | \(x_1\) | \(x_2\) | \(x_1^2\) | \(x_1x_2\) | \(x_2^2\) |
|---|---|---|---|---|---|
| (2, 3) | 2 | 3 | 4 | 6 | 9 |
The model can assign a separate weight to each of the five columns.
\[ x_1^3,\quad x_1^2x_2,\quad x_1x_2^2,\quad x_2^3 \]
There were five columns up to degree 2. These four additional products bring the total to nine. The intercept is separate.
| Terms up to degree 2 | New columns |
|---|---|
| Original measurements | 10 |
| Squares of each measurement | 10 |
| Products of each distinct pair | 45 |
| Total | 65 |
Every pair supplies a potential interaction. Many measurements create many possible pairs.
| Original features | Degree 2 | Degree 3 | Degree 6 |
|---|---|---|---|
| 2 | 5 | 9 | 27 |
| 10 | 65 | 285 | 8,007 |
More columns mean more coefficients and more work per fit. With 100,000 rows, 8,007 columns occupy about 6.4 GB as a dense float64 array.
These are the 100 examples used in the practical. The inner group has label 1 and the outer group has label 0.
\[ z=b+w_1x_1+w_2x_2 \]
The points where this score is zero form a straight line. This fit crosses both groups.
This is logistic regression fitted to the same examples with extra input columns. Its boundary now bends around the inner group.
| Input table | Columns |
|---|---|
| Original measurements | x₁, x₂ |
| Augmented measurements | 1, x₁, x₂, x₁², x₂², x₁x₂ |
The notebook includes a constant column of ones, giving six columns. It supplies the intercept that we previously wrote separately as b.
\[ z=w_0+w_1x_1+w_2x_2+w_3x_1^2+w_4x_2^2+w_5x_1x_2 \]
Fitting changes the six coefficients. Each training point supplies its feature values, and the score combines them.
\[ z=2-4x_1^2-4x_2^2 \]
For the next few slides, use these hand-chosen weights to make the geometry easy to follow.
The score is high near the origin and falls as either coordinate moves away from zero.
Which score is positive, which is negative, and which is exactly zero?
| Point | (x₁, x₂) | x₁² + x₂² | z = 2 − 4(x₁² + x₂²) |
|---|---|---|---|
| A | (0.4, 0.3) | 0.25 | +1 |
| B | (0.8, 0.6) | 1 | −2 |
| C | (0.5, 0.5) | 0.5 | 0 |
A is on the label-1 side. B is on the label-0 side. C sits on the decision boundary.
\[ 0=2-4x_1^2-4x_2^2 \]
\[ x_1^2+x_2^2=\frac{1}{2} \]
All points with squared distance one-half have score zero. Those points form a circle.
Call the new coordinates \(u=x_1^2\) and \(v=x_2^2\). The straight line \(u+v=0.5\) corresponds to the circle in the original plot.
\[ p=\sigma(z)=\frac{1}{1+\mathrm{e}^{-z}} \]
| Point | Score | Probability of label 1 |
|---|---|---|
| A | +1 | 0.73 |
| B | −2 | 0.12 |
| C | 0 | 0.50 |
At a probability cutoff of 0.5, the score-zero circle is also the decision boundary.
Evaluate the same score on a grid of input coordinates. Colour each location using the predicted class.
The green line joins locations with score zero. The regions show what the model would predict throughout the input space.
A circle is one possible shape. These two groups need a boundary with a different bend.
Here the input table contains terms up to degree 3. Logistic regression learns a weighted score on those columns.
A different choice of feature measures how close an input is to a chosen reference point.
At the reference point the feature is 1. It becomes smaller as we move away.
\[ \phi_j(\mathbf{x})=\exp\!\left(-\gamma\|\mathbf{x}-\mathbf{c}_j\|^2\right) \]
Choose reference points \(\mathbf{c}_j\) from the training inputs. For each reference point, put the squared distance inside the exponential to obtain one feature value.
\[ \phi_j(\mathbf{x})=\mathrm{e}^{-\|\mathbf{x}-\mathbf{c}_j\|^2}\qquad(\gamma=1) \]
The graph now shows the actual feature formula. One input point gives one number from this curve.
For a one-measurement example, choose reference values −1, 0 and 1. Each curve is a feature before applying any model weights.
\[ w_2=-1\quad\Longrightarrow\quad w_2\phi_2(x)=-\phi_2(x) \]
At x=0 the middle feature is 1, so its contribution is −1. Further from the centre, that contribution moves toward zero.
The two outside features have weights +1. The middle feature has weight −1. The sign of a weight determines whether that feature raises or lowers the score.
| Feature | Value at x=0 | Weight | Contribution |
|---|---|---|---|
| Left reference point | 0.135 | +1 | +0.135 |
| Middle reference point | 1 | −1 | −1 |
| Right reference point | 0.135 | +1 | +0.135 |
\[ z(0)=0.135-1+0.135-0.1\approx-0.83 \]
The final −0.1 is the bias. The score at this location is negative.
\[ z(x)=w_1\phi_1(x)+w_2\phi_2(x)+w_3\phi_3(x)+b \]
Adding the same contributions at every x gives this curve. Near the middle, the negative contribution dominates. Near an outside centre, a positive contribution dominates.
\[ \phi_j(\mathbf{x})=\exp\!\left(-\gamma\|\mathbf{x}-\mathbf{c}_j\|^2\right) \]
Changing \(\gamma\) changes each feature’s width. The fitted score combines many such features, with a learned weight for each.
The score combines broad contributions. Several examples still fall on the wrong side of its curved boundary.
The model is still logistic regression. Changing the input features lets its boundary follow the gap.
This fit gets all 86 training labels right. On 600 fresh simulated examples it gets 569 right, compared with 596 for the previous fit.
A factory measures the temperature and vibration of each part during a test. Later inspection tells us which parts are clear and which are defective.
We want a rule that can flag a new part from those two measurements.
Each point is one of 16 inspected parts. Orange squares are clear. Blue circles are defective.
Suppose a test rig flags a part when both its temperature and vibration are high. We can draw that inspection rule as a tree.
The part has temperature 8 and vibration 4. Follow the questions to a leaf.
Temperature 8 sends it right. Vibration 4 then sends it to the clear leaf.
The questions divide the measurement plane into rectangular regions. In this small dataset, the rule classifies all 16 parts correctly.
We supplied the cutoffs by hand. A decision-tree algorithm can choose its features and thresholds from the labelled training data.
Cut A tests temperature. Cut B tests vibration. Which leaves the groups less mixed?
| Cut | At or below (clear, defect) | Above (clear, defect) |
|---|---|---|
| A Temperature 6 | (6, 0) | (4, 6) |
| B Vibration 5 | (5, 0) | (5, 6) |
Both cuts create a pure group on one side. We also need to account for the size and mixture of the other side.
\[ G=1-p_{\mathrm{clear}}^2-p_{\mathrm{defect}}^2 \]
| Group | Gini impurity |
|---|---|
| All one class | 0 |
| Half clear, half defect | 0.5 |
| 4 clear and 6 defects | 1 − 0.42 − 0.62 = 0.48 |
A smaller value means a purer group.
\[ G_A=\frac{6}{16}(0)+\frac{10}{16}(0.48)=0.300 \]
| First cut | Weighted Gini |
|---|---|
| A Temperature 6 | 0.300 |
| B Vibration 5 | 0.341 |
The algorithm prefers A. It can then repeat the search within the mixed branch.
The mixed branch splits at vibration 5. In this example, learning from the labels recovers the rule we first drew by hand.
On the laser alignment data, repeated coordinate cuts make a staircase around the acceptable region.
With a different training sample, a tree can choose different early questions. Each early split changes the examples that reach later questions.
A random forest fits many trees with deliberately different views of the training data.
| Sample | Rows selected for one tree |
|---|---|
| Original | 1 2 3 4 5 6 7 8 |
| Tree 1 | 1 2 2 4 5 7 7 8 |
| Tree 2 | 1 1 3 3 4 6 6 8 |
Each sample draws rows with replacement. Some rows appear several times and others are absent.
At each split, a random forest considers a random subset of the input features.
With many measurements, different trees can discover different useful questions. This reduces how closely their predictions track each other.
Each panel shows the training rows for one tree. How do the three trees classify the same ringed reading P?
| Tree | Probability of outside tolerance |
|---|---|
| 1 | 0 |
| 2 | 1 |
| 3 | 1 |
\[ \hat p=\frac{0+1+1}{3}=\frac{2}{3} \]
Averaging their probabilities gives a prediction of outside tolerance at a cutoff of 0.5.
Each tree supplies a probability for each new reading. The forest averages all 60. The individual staircases combine into a different boundary.
If one tree changes its prediction, it contributes only one part of the average. Errors that different trees make on different readings can partly cancel.
If all the trees make the same mistake, their average keeps it. We still evaluate the forest on fresh examples.
Each position gives a pair of model weights. Its height is the cost on the training data. We want to move toward lower cost.
At the blue point the slope is positive. Moving the weight to the left reduces the cost.
\[ w_{\mathrm{new}}=w_{\mathrm{old}}-\eta\frac{\partial J}{\partial w} \]
| Current weight | Current slope | Learning rate | New weight |
|---|---|---|---|
| 1.25 | 31.25 | 0.025 | 0.46875 |
The slope supplies a direction and magnitude. The learning rate scales the step.
All three runs start at the same weight. Small steps take time. Larger steps can cross the minimum and even move away from it.
The cost is steep across the valley and shallow along it. One rate gives repeated crossings and slower progress along the valley. On other surfaces, steepness can also change as the weights move.
This is our reference run. We will add each optimiser to this same plot, starting from the same weights. The cost axis is logarithmic.
Momentum keeps a running direction. Persistent gradients build up in the average, while alternating gradients partly cancel.
\[ m_t=\beta m_{t-1}+(1-\beta)g_t \]
\[ w_{t+1}=w_t-\eta m_t \]
With \(\beta=0.8\), the new direction keeps 80% of the previous average and adds 20% of the current gradient.
The blue curve adds momentum. Averaging the gradient changes the path and how the cost falls.
| Update | Gradient for weight A | Gradient for weight B |
|---|---|---|
| 1 | 100 | 0 |
| 2 | 100 | 0 |
| 3 | 100 | 0 |
| 4 | 1 | 1 |
At update 4, both current gradients are 1.
Can we do better and give each weight its own learning rate?
\[ s_t=s_{t-1}+g_t^2\qquad s_0=0 \]
\[ \Delta w_t=-\eta\frac{g_t}{\sqrt{s_t}+\epsilon} \]
Each weight keeps its own sum of squared gradients. A large accumulated sum reduces the multiplier for its next gradient.
\[ s_A=3(100)^2+1^2=30\,001\qquad s_B=1^2=1 \]
| Weight | Sum of squares | Square root | Update at rate 0.2 |
|---|---|---|---|
| A | 30,001 | ≈173.2 | ≈−0.0012 |
| B | 1 | 1 | −0.2 |
The current gradients are identical, but B receives a step about 170 times larger. The earlier large gradients strongly reduce A’s step.
If the same gradient appears repeatedly, the sum keeps growing. AdaGrad can eventually make very small updates.
The orange curve adds AdaGrad. Gradients from long ago still influence every update. Its running sum keeps their squared values, so an early large gradient can keep later steps small.
\[ r_t=\rho r_{t-1}+(1-\rho)g_t^2 \]
\[ \Delta w_t=-\eta\frac{g_t}{\sqrt{r_t}+\epsilon} \]
A moving average of squared gradients gives recent updates more influence. Earlier contributions gradually fade.
AdaGrad retains the original contribution. RMSProp discounts it, allowing a later gradient to receive a larger multiplier.
The green curve adds RMSProp. On this problem and at these rates, its recent-gradient scaling gives a different pattern of progress.
\[ m_t=\beta_1m_{t-1}+(1-\beta_1)g_t \]
\[ r_t=\beta_2r_{t-1}+(1-\beta_2)g_t^2 \]
Adam combines a running direction with a running estimate of gradient scale. Both start at zero.
\[ \hat m_t=\frac{m_t}{1-\beta_1^t}\qquad\hat r_t=\frac{r_t}{1-\beta_2^t} \]
\[ \Delta w_t=-\eta\frac{\hat m_t}{\sqrt{\hat r_t}+\epsilon} \]
The correction removes the early shrinkage caused by starting the averages at zero.
With \(g_1=2,\ \beta_1=0.9,\ \beta_2=0.999\), we store \(m_1=0.2\) and \(r_1=0.004\).
\[ \hat m_1=2,\qquad\hat r_1=4 \]
\[ \Delta w_1\approx-\eta\frac{2}{\sqrt{4}}=-\eta \]
The purple curve adds Adam. At the rates shown, it moves quickly at first and later overshoots. Changing the learning rate changes each run.
| Year | Method | Added idea |
|---|---|---|
| 1847 | Gradient descent | Follow the negative gradient |
| 1964 | Momentum | Use the previous direction |
| 2011 | AdaGrad | Track each weight’s squared gradients |
| 2012 | RMSProp | Discount older squared gradients |
| 2014 | Adam | Combine corrected moving averages |
Lion stands for EvoLved Sign Momentum. Researchers at Google and collaborators discovered it through a search over optimiser programs.
It keeps a moving average of gradients, then uses a sign operation to choose the update direction.
Optimiser design continues to develop. The useful choice can depend on the model, data and training budget.
| Combined direction | Sign | Update |
|---|---|---|
| Large positive | +1 | \(-\eta\) |
| Small positive | +1 | \(-\eta\) |
| Negative | −1 | \(+\eta\) |
The sign sets an equal step magnitude for each nonzero direction component. The moving gradient average helps choose that direction.
import torch
optimiser = torch.optim.Adam(model.parameters(), lr=0.001)
optimiser.zero_grad()
loss = loss_fn(model(x_batch), y_batch)
loss.backward()
optimiser.step()
Choose the optimiser once. For each batch, calculate the loss and gradients, then let it update the model and its own stored history.