Summative assessment

Part A is a project-style assignment, available for around three weeks. Part B is a 24-hour assignment.

Assessment release and collection schedulePart A opens tomorrow and is collected at 2 pm on 7 December. Part B opens at that time and is collected at 2 pm on 8 December.Part A opensTomorrowPart A collected7 December2 pmPart B opens7 December2 pmPart B collected8 December2 pmPart B is available for 24 hours

The dates and times are supplied by the lecturer. Part B begins at 2 pm on 7 December and closes 24 hours later, at 2 pm on 8 December.

Working on the assignment

Part A uses simulated collider data to investigate a classification problem. The notebook provides the background and instructions.

  • Explain your choices and what you learn from the results.
  • Submit a notebook that runs from top to bottom.
  • Part A is individual work. AI use is not permitted.
General briefing based on the supplied assignment notebook.

Non-linear models

Last lecture

The training loss halves

Training loss halvesLoss on training examples falls from 0.40 to 0.20 over ten epochs. 0 2 4 6 8 10 Epoch 0.2 0.3 0.4 0.5 0.6 Loss Training

Does this tell us that predictions on new examples have improved?

Validation changes the conclusion

The same falling training loss can go with different hold-out lossesBoth example training paths run from 0.40 to 0.20. The hold-out loss falls in one case and rises in the other. 0 2 4 6 8 10 Epoch 0.2 0.3 0.4 0.5 0.6 Loss Hold-out loss falls Training Hold-out 0 2 4 6 8 10 Epoch Hold-out loss rises Training Hold-out

Training loss measures the fit to examples used to update the model. The held-out loss checks predictions on other examples.

The best checkpoint can come early

Sensor loss over 250 epochsThe training loss falls. The horizontal axis uses a logarithmic scale to show early epochs. The validation loss reaches its minimum at epoch 17 and rises afterwards. 1 2 5 10 17 50 100 250 Epoch (log scale) 0.00 0.04 0.08 0.12 0.16 Mean squared error (V²) Lowest validation loss Training Validation

In the sensor example, validation loss was lowest at epoch 17. Training loss continued to fall after that.

A persistent gap needs an explanation

Training loss is low and validation loss stays higherTraining loss is low and validation loss stays higher in this schematic example. 0 5 10 15 20 25 30 Epoch 0.0 0.2 0.4 0.6 0.8 Loss (illustrative) Training Validation

A low training loss and a higher validation loss can indicate overfitting. Check the data split and measurement settings before changing the model.

Bias and variance

Sensitivity of fitted curves to new training samplesSix degree-one fits all miss the curved simulated signal in similar ways. Six degree-twelve fits vary much more across draws, especially near the edges. −1.00 −0.75 −0.50 −0.25 0.00 0.25 0.50 0.75 1.00 Scaled setting 0.0 0.5 1.0 1.5 2.0 Sensor output (V) Degree 1 Simulated signal −1.00 −0.75 −0.50 −0.25 0.00 0.25 0.50 0.75 1.00 Scaled setting Degree 12

Bias is a systematic miss. Variance is the sensitivity of the fit to the training sample.

A score becomes an inspection decision

Defect scores for twelve example partsSix defective parts have scores 0.95, 0.82, 0.74, 0.59, 0.48 and 0.31. Six clear parts score 0.79, 0.61, 0.43, 0.28, 0.18 and 0.07. At cutoff 0.55, 4 defects and 2 clear parts are flagged. 0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0 Defect score Clear (6) Defect (6) Cutoff 0.55 Flag for review

At a cutoff of 0.55, this model flags four of the six defects and also flags two clear parts.

A new cutoff changes both rates

Receiver operating characteristicThe selected cutoffs 0.80, 0.55, and 0.40 lie at (0, 2/6), (2/6, 4/6), and (3/6, 5/6). 0 1/6 2/6 3/6 4/6 5/6 1 False positive rate (FPR) 0 1/6 2/6 3/6 4/6 5/6 1 True positive rate (TPR) Cutoff 0.80 Cutoff 0.55 Cutoff 0.40

\[ \mathrm{TPR}=\frac{\mathrm{TP}}{\mathrm{TP}+\mathrm{FN}}\qquad\mathrm{FPR}=\frac{\mathrm{FP}}{\mathrm{FP}+\mathrm{TN}} \]

Use the same defect-inspection example as Lecture 3. Each point on the ROC plot represents a cutoff.

The full ROC curve

Receiver operating characteristicThe curve moves from flagging none at the origin to flagging all in the top right. Each passing defect raises the curve, and each passing clear part moves it right. 0 1/6 2/6 3/6 4/6 5/6 1 False positive rate (FPR) 0 1/6 2/6 3/6 4/6 5/6 1 True positive rate (TPR) Flag none Flag all Chance ranking Inspection model

Sweeping the cutoff across all the scores gives the full curve. Each point represents a different balance of true positives and false positives.

Cross-validation rotates the held-out fold

Five-fold cross-validationA fresh model trains on four folds and scores the omitted fold. Each fold is used once as the scored fold. The test set is held aside for the whole process.Fold 1Fold 2Fold 3Fold 4Fold 5Fit 1ScoreTrainTrainTrainTrainFit 2TrainScoreTrainTrainTrainFit 3TrainTrainScoreTrainTrainFit 4TrainTrainTrainScoreTrainFit 5TrainTrainTrainTrainScoreTest held out

Each candidate setting uses the same folds. Compare its average performance across the held-out folds.

Today we will cover

  • Features for curved relationships and complex decision boundaries.
  • Decision trees and random forests.
  • How optimisers choose their updates.

A sensor can saturate

Simulated sensor readingsReadings rise quickly at first and flatten as drive voltage increases. 0 2 4 6 8 10 Drive voltage (V) 0.0 0.5 1.0 1.5 2.0 2.5 3.0 Sensor reading (V)

These simulated readings flatten at high drive voltages. Where is the response most sensitive?

A constant slope misses the bend

Straight-line fit to the sensorThe fitted line misses the bend across the same simulated measurements. 0 2 4 6 8 10 Drive voltage (V) 0.0 0.5 1.0 1.5 2.0 2.5 3.0 Sensor reading (V) Simulated readings Fitted response

The straight-line fit uses the same slope across the whole range.

A saturation feature

Fit in the transformed coordinateThe same readings lie close to a line when plotted against the saturation feature. 0.0 0.2 0.4 0.6 0.8 1.0 Saturation feature 1 − exp(−x/3 V) 0.0 0.5 1.0 1.5 2.0 2.5 3.0 Sensor reading (V) Simulated readings Fitted response

The horizontal axis is now \(\phi(x)=1-\mathrm{e}^{-x/(3\,\mathrm{V})}\). The transformed readings sit close to a line.

The 3 V scale is given in this worked example. Fit the slope and intercept using the training readings.

The fit bends in the original units

Sensor response in the original coordinatesThe fitted line in the transformed feature gives a saturating curve as a function of voltage. 0 2 4 6 8 10 Drive voltage (V) 0.0 0.5 1.0 1.5 2.0 2.5 3.0 Sensor reading (V) Simulated readings Fitted response

\[ \hat y=b+w\phi(x) \]

The feature supplies the shape. Fitting sets the offset and amplitude.

What is an extra 10 m² worth?

Illustrative house prices in two neighbourhoodsIncreasing floor area from 80 to 90 square metres adds twenty thousand pounds in neighbourhood A and forty thousand in B. These prices are a toy example. 60 80 100 120 140 Floor area (m²) 100 200 300 400 500 600 700 House price (£ thousands) Neighbourhood A Neighbourhood B

In this toy example, compare an 80 m² house with a 90 m² house in each neighbourhood.

Floor area interacts with location

NeighbourhoodAt 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.

Illustrative prices, chosen to show an interaction. They do not describe either a real neighbourhood or current house prices.

A neighbourhood changes the value of extra space

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.

A feature for space in neighbourhood B

HouseFloor areaArea × neighbourhood-B indicator
80 m² in A800
90 m² in A900
80 m² in B8080
90 m² in B9090

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.

The indicator is 0 in A and 1 in B. This explains the interaction term A×L without requiring the full model equation.

Is the laser beam within tolerance?

Laser beam alignment measurementsSimulated beam hits, labelled by whether the distance from the target centre exceeds the tolerance of 1.2 millimetres. −2 −1 0 1 2 Horizontal beam offset (mm) −2 −1 0 1 2 Vertical beam offset (mm) Within tolerance Outside tolerance Target centre

An alignment camera records where each shot lands. A shot passes if it is within 1.2 mm of the target centre.

These measurements are simulated. Orange squares pass the alignment check. Blue circles lie outside the specified tolerance.

A trial straight boundary

Laser beam alignment measurementsSimulated beam hits, labelled by whether the distance from the target centre exceeds the tolerance of 1.2 millimetres. −2 −1 0 1 2 Horizontal beam offset (mm) −2 −1 0 1 2 Vertical beam offset (mm) Within tolerance Outside tolerance Target centre Trial line

The shots outside tolerance surround the acceptable region. Which feature would make this decision simpler?

Distance from the target centre

\[ r^2=x_1^2+x_2^2 \]

Offset (mm)Squared distance (mm²)Result
(1, 0)1Pass
(1, 1)2Outside tolerance

The tolerance corresponds to squared distance 1.44 mm².

One feature gives one cutoff

Separation by distance from the targetA single threshold of 1.44 square millimetres separates the two alignment classes. 0.0 0.5 1.0 1.5 2.0 2.5 3.0 3.5 4.0 Squared distance from target (mm²) Within tolerance Outside tolerance Cut at 1.44 mm²

Each camera reading has become a single squared distance. The cutoff separates the passing and failing shots.

The cutoff becomes a circle

Laser beam alignment measurementsSimulated beam hits, labelled by whether the distance from the target centre exceeds the tolerance of 1.2 millimetres. −2 −1 0 1 2 Horizontal beam offset (mm) −2 −1 0 1 2 Vertical beam offset (mm) Within tolerance Outside tolerance Target centre Tolerance boundary

\[ x_1^2+x_2^2=1.44 \]

The coordinates are expressed in mm and the squared distance in mm². The radius is 1.2 mm.

What if the target position moves?

Laser beam alignment measurementsSimulated beam hits, labelled by whether the distance from the target centre exceeds the tolerance of 1.2 millimetres. −2 −1 0 1 2 Horizontal beam offset (mm) −2 −1 0 1 2 Vertical beam offset (mm) Within tolerance Outside tolerance Target centre Original circle

The new target position is at (0.65, −0.45) mm. How should the distance feature change?

Distance relative to the new target

Laser beam alignment measurementsSimulated beam hits, labelled by whether the distance from the target centre exceeds the tolerance of 1.2 millimetres. −2 −1 0 1 2 Horizontal beam offset (mm) −2 −1 0 1 2 Vertical beam offset (mm) Within tolerance Outside tolerance Target centre Tolerance boundary

\[ r^2=(x_1-0.65)^2+(x_2+0.45)^2 \]

A quadratic feature map

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

Polynomial feature expansion.

One reading becomes five feature values

Original reading\(x_1\)\(x_2\)\(x_1^2\)\(x_1x_2\)\(x_2^2\)
(2, 3)23469

The model can assign a separate weight to each of the five columns.

Degree 3 adds four more 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.

With ten original measurements

Terms up to degree 2New columns
Original measurements10
Squares of each measurement10
Products of each distinct pair45
Total65

Every pair supplies a potential interaction. Many measurements create many possible pairs.

The expanded input table can become large

Original featuresDegree 2Degree 3Degree 6
25927
10652858,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.

Counts exclude the intercept. The byte estimate is 100,000 × 8,007 × 8, divided by 10^9 for decimal GB. Feature-count formula.

Curved decision boundaries

The circular data in the notebook

The circular dataset from the practical notebookThe inner circle has label one and the outer ring has label zero. −1.0 −0.5 0.0 0.5 1.0 Original feature x₁ −1.0 −0.5 0.0 0.5 1.0 Original feature x₂ Class 0 Class 1

These are the 100 examples used in the practical. The inner group has label 1 and the outer group has label 0.

The familiar linear score

The circular dataset from the practical notebookThe same one hundred points, fitted with a linear score on the original features. −1.0 −0.5 0.0 0.5 1.0 Original feature x₁ −1.0 −0.5 0.0 0.5 1.0 Original feature x₂ Class 0 Class 1

\[ z=b+w_1x_1+w_2x_2 \]

The points where this score is zero form a straight line. This fit crosses both groups.

After adding quadratic features

The circular dataset from the practical notebookThe same one hundred points, fitted with logistic regression on quadratic features. −1.0 −0.5 0.0 0.5 1.0 Original feature x₁ −1.0 −0.5 0.0 0.5 1.0 Original feature x₂ Class 0 Class 1

This is logistic regression fitted to the same examples with extra input columns. Its boundary now bends around the inner group.

What did we change?

Input tableColumns
Original measurementsx₁, x₂
Augmented measurements1, 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.

The practical asks students to construct these columns. The fitted preview uses a separate intercept and the five nonconstant features, which gives the same class of quadratic scores.

Every added column has a weight

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

The probabilities still come from the sigmoid and the training objective is still cross-entropy. No new probability transformation is required.

A score we can work through

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

These rounded illustrative weights are distinct from the coefficients of the preceding fitted model.

Calculate the score at three locations

A worked circular decision ruleThe illustrative score is two minus four times the squared radius. The score is zero on the circle of radius square root of one half. −1.0 −0.5 0.0 0.5 1.0 Original feature x₁ −1.0 −0.5 0.0 0.5 1.0 Original feature x₂ A B C

Which score is positive, which is negative, and which is exactly zero?

Feature values determine the score

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.50

A is on the label-1 side. B is on the label-0 side. C sits on the decision boundary.

The boundary is where the score is zero

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

A line in the new coordinates

The same boundary in original and squared coordinatesA circle x1 squared plus x2 squared equals one half becomes the straight line u plus v equals one half when u equals x1 squared and v equals x2 squared. −1.0 −0.5 0.0 0.5 1.0 x₁ −1.0 −0.5 0.0 0.5 1.0 x₂ Original coordinates 0.0 0.2 0.4 0.6 0.8 1.0 x₁² 0.0 0.2 0.4 0.6 0.8 1.0 x₂² Squared coordinates

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.

The same sigmoid gives probabilities

\[ p=\sigma(z)=\frac{1}{1+\mathrm{e}^{-z}} \]

PointScoreProbability of label 1
A+10.73
B−20.12
C00.50

At a probability cutoff of 0.5, the score-zero circle is also the decision boundary.

We can score locations between the examples

A worked circular decision ruleThe illustrative score is two minus four times the squared radius. The score is zero on the circle of radius square root of one half. −1.0 −0.5 0.0 0.5 1.0 Original feature x₁ −1.0 −0.5 0.0 0.5 1.0 Original feature x₂

Evaluate the same score on a grid of input coordinates. Colour each location using the predicted class.

This is the idea behind the practical’s contour plot. Each grid location gets the same feature transformation as a training example.

Filling the grid reveals the regions

A worked circular decision ruleThe illustrative score is two minus four times the squared radius. The score is zero on the circle of radius square root of one half. −1.0 −0.5 0.0 0.5 1.0 Original feature x₁ −1.0 −0.5 0.0 0.5 1.0 Original feature x₂ Class 0 Class 1

The green line joins locations with score zero. The regions show what the model would predict throughout the input space.

A more complicated gap

SVM on two simulated crescent groupsOrange squares and blue circles form two interlocking crescents. −1.0 −0.5 0.0 0.5 1.0 1.5 2.0 Measurement 1 −0.5 0.0 0.5 1.0 Measurement 2 Class 0 Class 1

A circle is one possible shape. These two groups need a boundary with a different bend.

The same idea with more polynomial terms

A curved boundary using cubic input featuresLogistic regression on all polynomial terms up to degree three follows the curved gap between the two groups. −1.0 −0.5 0.0 0.5 1.0 1.5 2.0 Measurement 1 −0.5 0.0 0.5 1.0 Measurement 2 Class 0 Class 1

Here the input table contains terms up to degree 3. Logistic regression learns a weighted score on those columns.

All polynomial terms up to degree three are used, with a separate intercept. The fit uses C=5. The training examples match the later radial-feature illustration.

A feature for similarity to a reference point

Similarity around one training pointThe shading is darkest near the training point at the origin. A and B are one unit away and C is two units away. −2 −1 0 1 2 Measurement 1 −2.0 −1.5 −1.0 −0.5 0.0 0.5 1.0 1.5 2.0 Measurement 2 A B C Training point New points

A different choice of feature measures how close an input is to a chosen reference point.

Nearby inputs have higher similarity

RBF similarity decreases with distanceAt gamma one, the similarity equals one at distance zero, about 0.37 at distance one, and about 0.018 at distance two. 0.0 0.5 1.0 1.5 2.0 2.5 3.0 Distance between inputs 0.0 0.2 0.4 0.6 0.8 1.0 RBF similarity

At the reference point the feature is 1. It becomes smaller as we move away.

A radial feature around each reference point

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

The feature we have just defined

The newly defined radial feature versus distanceAt gamma one, the radial feature is one at the reference point, 0.37 at distance one and 0.018 at distance two. 0.0 0.5 1.0 1.5 2.0 2.5 3.0 Distance from reference point ‖x − cⱼ‖ 0.0 0.2 0.4 0.6 0.8 1.0 New feature value φⱼ(x) 1.00 0.37 0.02 γ = 1

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

Three reference points give three features

How local features become a model scoreEach radial feature is positive. Its weight determines whether it raises or lowers the score. The final score sums the weighted features and bias. −2 −1 0 1 2 Input x −1.0 −0.5 0.0 0.5 1.0 Feature value φ1 (centre -1) φ2 (centre 0) φ3 (centre 1)

For a one-measurement example, choose reference values −1, 0 and 1. Each curve is a feature before applying any model weights.

The one-dimensional centres are −1, 0 and 1. All three features use gamma=2.

A weight changes the contribution

How local features become a model scoreEach radial feature is positive. Its weight determines whether it raises or lowers the score. The final score sums the weighted features and bias. −2 −1 0 1 2 Input x −1.0 −0.5 0.0 0.5 1.0 Contribution to score Feature φ₂ Contribution −φ₂

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

How local features become a model scoreEach radial feature is positive. Its weight determines whether it raises or lowers the score. The final score sums the weighted features and bias. −2 −1 0 1 2 Input x −1.0 −0.5 0.0 0.5 1.0 Contribution to score w1φ1 w1 = 1 w2φ2 w2 = -1 w3φ3 w3 = 1

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.

Add the contributions at x = 0

FeatureValue at x=0WeightContribution
Left reference point0.135+1+0.135
Middle reference point1−1−1
Right reference point0.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.

The total score at every input

How local features become a model scoreEach radial feature is positive. Its weight determines whether it raises or lowers the score. The final score sums the weighted features and bias. −2 −1 0 1 2 Input x −1.0 −0.5 0.0 0.5 1.0 Contribution to score Sum with bias −0.1

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

The bias is −0.1. All weights in this numerical illustration are chosen by hand. A fitted classifier learns weights from its labelled examples.

How local should each feature be?

\[ \phi_j(\mathbf{x})=\exp\!\left(-\gamma\|\mathbf{x}-\mathbf{c}_j\|^2\right) \]

Three choices of gammaRaising gamma makes the similarity curve fall faster with distance. 0.0 0.5 1.0 1.5 2.0 2.5 3.0 Distance between inputs 0.0 0.2 0.4 0.6 0.8 1.0 RBF similarity γ = 0.08 γ = 2 γ = 30

Changing \(\gamma\) changes each feature’s width. The fitted score combines many such features, with a learned weight for each.

Broad local features

A logistic classifier with transformed inputsThe classifier uses radial features centred at training points with gamma 0.08. The background shows its predicted classes. −1.0 −0.5 0.0 0.5 1.0 1.5 2.0 Measurement 1 −0.5 0.0 0.5 1.0 Measurement 2 Class 0 Class 1

The score combines broad contributions. Several examples still fall on the wrong side of its curved boundary.

Features that follow the curved gap

A logistic classifier with transformed inputsThe classifier uses radial features centred at training points with gamma 2. The background shows its predicted classes. −1.0 −0.5 0.0 0.5 1.0 1.5 2.0 Measurement 1 −0.5 0.0 0.5 1.0 Measurement 2 Class 0 Class 1

The model is still logistic regression. Changing the input features lets its boundary follow the gap.

Very local features make small pockets

A logistic classifier with transformed inputsThe classifier uses radial features centred at training points with gamma 30. The background shows its predicted classes. −1.0 −0.5 0.0 0.5 1.0 1.5 2.0 Measurement 1 −0.5 0.0 0.5 1.0 Measurement 2 Class 0 Class 1

This fit gets all 86 training labels right. On 600 fresh simulated examples it gets 569 right, compared with 596 for the previous fit.

All radial fits use the same training examples as centres and LogisticRegression with C=5. Coordinates are standardised using training data. Only gamma changes.

Decision trees

Imagine a parts inspection line

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.

The measurements and known labels

Two readings for each partSixteen labelled parts plotted by temperature and vibration. 0 2 4 6 8 10 Temperature (scaled) 0 2 4 6 8 10 Vibration (scaled) Clear Defect

Each point is one of 16 inspected parts. Orange squares are clear. Blue circles are defective.

A rule we could write by hand

Prediction tree for part inspectionIf temperature is at most 6, the clear leaf applies. Otherwise, the second split checks whether vibration is at most 5.YesNoYesNoTemperature ≤ 6?ClearVibration ≤ 5?ClearDefect

Suppose a test rig flags a part when both its temperature and vibration are high. We can draw that inspection rule as a tree.

These are illustrative scaled measurements. The handcrafted cutoffs are temperature 6 and vibration 5.

What happens to a new part?

Prediction tree for part inspectionIf temperature is at most 6, the clear leaf applies. Otherwise, the second split checks whether vibration is at most 5.YesNoYesNoTemperature ≤ 6?ClearVibration ≤ 5?ClearDefect

The part has temperature 8 and vibration 4. Follow the questions to a leaf.

The part reaches the clear leaf

Prediction tree for part inspectionThe path for temperature 8 and vibration 4 follows no at the first split and yes at the second split to a clear leaf.YesNoYesNoTemperature ≤ 6?ClearVibration ≤ 5?ClearDefect

Temperature 8 sends it right. Vibration 4 then sends it to the clear leaf.

The rule on the measured parts

The result after two splitsParts with temperature above six and vibration above five fall into the blue defect region. 0 2 4 6 8 10 Temperature (scaled) 0 2 4 6 8 10 Vibration (scaled) Clear Defect

The questions divide the measurement plane into rectangular regions. In this small dataset, the rule classifies all 16 parts correctly.

Can the tree learn its own questions?

Two readings for each partSixteen labelled parts plotted by temperature and vibration. 0 2 4 6 8 10 Temperature (scaled) 0 2 4 6 8 10 Vibration (scaled) Clear Defect

We supplied the cutoffs by hand. A decision-tree algorithm can choose its features and thresholds from the labelled training data.

Which cut separates the labels better?

Two candidate first splitsCandidate A uses temperature 6. Candidate B uses vibration 5. 0 2 4 6 8 10 Temperature (scaled) 0 2 4 6 8 10 Vibration (scaled) A B Clear Defect

Cut A tests temperature. Cut B tests vibration. Which leaves the groups less mixed?

The labels on each side

CutAt 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.

Gini impurity measures the mixture

\[ G=1-p_{\mathrm{clear}}^2-p_{\mathrm{defect}}^2 \]

GroupGini impurity
All one class0
Half clear, half defect0.5
4 clear and 6 defects1 − 0.42 − 0.62 = 0.48

A smaller value means a purer group.

Decision-tree classification criteria.

Weight each group by its size

\[ G_A=\frac{6}{16}(0)+\frac{10}{16}(0.48)=0.300 \]

First cutWeighted Gini
A   Temperature 60.300
B   Vibration 50.341

The algorithm prefers A. It can then repeat the search within the mixed branch.

The parent impurity is 0.469. Cut A gives the larger reduction. A depth-two DecisionTreeClassifier fitted to these points selects temperature 6 and then vibration 5.

The learned second split

The result after two splitsParts with temperature above six and vibration above five fall into the blue defect region. 0 2 4 6 8 10 Temperature (scaled) 0 2 4 6 8 10 Vibration (scaled) Clear Defect

The mixed branch splits at vibration 5. In this example, learning from the labels recovers the rule we first drew by hand.

A tree can approximate a curved boundary

A decision tree on the alignment readingsCoordinate splits approximate the circular alignment tolerance with a staircase. −2 −1 0 1 2 Horizontal beam offset (mm) −2.0 −1.5 −1.0 −0.5 0.0 0.5 1.0 1.5 2.0 Vertical beam offset (mm) Within tolerance Outside tolerance Tolerance boundary

On the laser alignment data, repeated coordinate cuts make a staircase around the acceptable region.

This plot uses the same simulated laser shots as the beam example. The tree depth is limited to four.

Why fit several trees?

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.

Random forest construction.

Training rows can repeat

SampleRows selected for one tree
Original1   2   3   4   5   6   7   8
Tree 11   2   2   4   5   7   7   8
Tree 21   1   3   3   4   6   6   8

Each sample draws rows with replacement. Some rows appear several times and others are absent.

A small illustrative bootstrap sample. The fitted forest plots use actual bootstrap samples of the 72 beam-alignment measurements.

Trees also try different features

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.

The example uses two original coordinates and scikit-learn’s default square-root feature rule. Each split initially considers one coordinate. Feature randomness at each split.

Three trees see different samples

Three trees with different training samplesThree fitted trees produce different boundaries. For the same marked point P, the defect probabilities are zero, one and one. −2 0 2 Horizontal offset −2 0 2 Vertical offset Tree 1 P −2 0 2 Horizontal offset Tree 2 P −2 0 2 Horizontal offset Tree 3 P

Each panel shows the training rows for one tree. How do the three trees classify the same ringed reading P?

Combine the three predictions

TreeProbability of outside tolerance
10
21
31

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

These values come from the first three trees in the plotted forest at P=(1.100,0.467). The three-tree mean is an illustrative subensemble. The full forest has 60 trees. Averaging class probabilities.

The forest combines the full set of trees

A tree and a forest on the alignment dataBoth see the same labelled shots. The forest averages the class probabilities of sixty trees. −2 0 2 Horizontal offset (mm) −2 0 2 Vertical offset (mm) One tree −2 0 2 Horizontal offset (mm) 60 trees

Each tree supplies a probability for each new reading. The forest averages all 60. The individual staircases combine into a different boundary.

Why the average can be more stable

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.

The benefit depends on individual model performance and the dependence between their errors. Random forests.

Optimisers

The training cost is a surface

Gradient descent across a loss surfaceA sequence of updates moves down a bowl while zigzagging between the steep sides. Each height gives the training cost for that pair of weights. 0 1 2 3 Weight u −1.0 −0.5 0.0 0.5 1.0 Weight v 0 5 10 15 20 25 Training cost J

Each position gives a pair of model weights. Its height is the cost on the training data. We want to move toward lower cost.

The slope tells us a direction

A weight update moves against the local slopeAt w equals 1.25 the gradient is positive. Subtracting a positive multiple of it moves left toward the minimum. −2.0 −1.5 −1.0 −0.5 0.0 0.5 1.0 1.5 2.0 Weight w 0 10 20 30 40 50 Training cost J Local slope

At the blue point the slope is positive. Moving the weight to the left reduces the cost.

The update from earlier lectures

\[ w_{\mathrm{new}}=w_{\mathrm{old}}-\eta\frac{\partial J}{\partial w} \]

Current weightCurrent slopeLearning rateNew weight
1.2531.250.0250.46875

The slope supplies a direction and magnitude. The learning rate scales the step.

Small, middle and large learning rates

Three learning rates on the same objectiveWith a small rate progress is slow. The middle rate descends while overshooting. The large rate moves away from the minimum. −2 −1 0 1 2 Weight w 0 10 20 30 40 50 Training cost J Small steps η = 0.008 −2 −1 0 1 2 Weight w Middle steps η = 0.07 −2 −1 0 1 2 Weight w leaves this range Large steps η = 0.095

All three runs start at the same weight. Small steps take time. Larger steps can cross the minimum and even move away from it.

With two weights, one rate can be awkward

Updates viewed from aboveThe same steps viewed from above reveal repeated crossings of the narrow valley. −0.5 0.0 0.5 1.0 1.5 2.0 2.5 3.0 Weight u −1.0 −0.5 0.0 0.5 1.0 Weight v Start Gradient descent η = 0.075

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.

The example uses exact gradients of \(J(u,v)=\frac12(u^2+25v^2)\), starting from (2.8,1.1). The axes are weights and the contours show equal cost.

The cost after each update

Objective history with 1 optimiser curvesAll curves start at the same weights and use the same quadratic objective. The axes and the previously drawn curves stay fixed as another method is added. 0 5 10 15 20 25 30 35 40 Update number 1 0 − 6 1 0 − 5 1 0 − 4 1 0 − 3 1 0 − 2 1 0 − 1 1 0 0 1 0 1 Training cost J Gradient descent η = 0.075

This is our reference run. We will add each optimiser to this same plot, starting from the same weights. The cost axis is logarithmic.

All objective comparisons use the exact gradient of the same toy quadratic. Each legend reports the chosen learning rate. These settings illustrate the methods and their rate dependence.

Momentum · 1964

Updates viewed from aboveThe contours show the same quadratic training cost. Gradient descent zigzags. Momentum averages the gradients before choosing a step. −0.5 0.0 0.5 1.0 1.5 2.0 2.5 3.0 Weight u −1.0 −0.5 0.0 0.5 1.0 Weight v Start Gradient descent η = 0.075 Momentum η = 0.075

Momentum keeps a running direction. Persistent gradients build up in the average, while alternating gradients partly cancel.

Polyak’s heavy-ball work is a landmark for momentum methods. The plotted variant uses an exponential average, an equivalent parameterisation after adjusting the step scale. Polyak, 1964.

A moving average of gradients

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

Momentum on the cost plot

Objective history with 2 optimiser curvesAll curves start at the same weights and use the same quadratic objective. The axes and the previously drawn curves stay fixed as another method is added. 0 5 10 15 20 25 30 35 40 Update number 1 0 − 6 1 0 − 5 1 0 − 4 1 0 − 3 1 0 − 2 1 0 − 1 1 0 0 1 0 1 Training cost J Gradient descent η = 0.075 Momentum η = 0.075

The blue curve adds momentum. Averaging the gradient changes the path and how the cost falls.

Two weights with different histories

UpdateGradient for weight AGradient for weight B
11000
21000
31000
411

At update 4, both current gradients are 1.

Can we do better and give each weight its own learning rate?

AdaGrad · 2011

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

Apply this rule to each weight separately. Epsilon keeps the denominator positive. Duchi, Hazan and Singer, 2011.

The fourth AdaGrad step

\[ s_A=3(100)^2+1^2=30\,001\qquad s_B=1^2=1 \]

WeightSum of squaresSquare rootUpdate at rate 0.2
A30,001≈173.2≈−0.0012
B11−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.

Both current gradients are 1 and the base rate is 0.2. The table neglects epsilon. A’s update is −0.2/√30001 ≈ −0.001155. B’s is −0.2. AdaGrad adjusts the multiplier for each weight using its own history.

Its gradient multiplier keeps shrinking

An AdaGrad step shrinks with repeated equal gradientsStarting at 0.2, the step magnitude falls with the inverse square root of the update number. 5 10 15 20 25 30 35 40 Update t 0.000 0.025 0.050 0.075 0.100 0.125 0.150 0.175 0.200 0.225 Step magnitude AdaGrad Fixed first step size

If the same gradient appears repeatedly, the sum keeps growing. AdaGrad can eventually make very small updates.

AdaGrad on the cost plot

Objective history with 3 optimiser curvesAll curves start at the same weights and use the same quadratic objective. The axes and the previously drawn curves stay fixed as another method is added. 0 5 10 15 20 25 30 35 40 Update number 1 0 − 6 1 0 − 5 1 0 − 4 1 0 − 3 1 0 − 2 1 0 − 1 1 0 0 1 0 1 Training cost J Gradient descent η = 0.075 Momentum η = 0.075 AdaGrad η = 0.3

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.

RMSProp · 2012

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

RMSProp was introduced in Hinton’s Neural Networks for Machine Learning lecture. Adaptive learning rates lecture.

One large gradient, then quiet

Memory of one gradient spikeWhen later gradients are zero, AdaGrad keeps the accumulated square. RMSProp discounts the spike by 0.9 per update. 5 10 15 20 25 Update t 0.0 0.2 0.4 0.6 0.8 1.0 Fraction of the first stored value AdaGrad RMSProp (ρ = 0.9)

AdaGrad retains the original contribution. RMSProp discounts it, allowing a later gradient to receive a larger multiplier.

Each curve is normalised to its value just after the spike. Gradients are zero after that first spike. The parameter updates are also zero during those quiet steps.

RMSProp on the cost plot

Objective history with 4 optimiser curvesAll curves start at the same weights and use the same quadratic objective. The axes and the previously drawn curves stay fixed as another method is added. 0 5 10 15 20 25 30 35 40 Update number 1 0 − 6 1 0 − 5 1 0 − 4 1 0 − 3 1 0 − 2 1 0 − 1 1 0 0 1 0 1 Training cost J Gradient descent η = 0.075 Momentum η = 0.075 AdaGrad η = 0.3 RMSProp η = 0.11

The green curve adds RMSProp. On this problem and at these rates, its recent-gradient scaling gives a different pattern of progress.

Adam · 2014

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

The Adam preprint appeared in December 2014 and the paper was presented at ICLR 2015. Kingma and Ba on Adam.

Correcting the zero starting values

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

Adam’s first step by hand

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 numerical approximation treats epsilon as negligible for this nonzero gradient.

Adam on the cost plot

Objective history with 5 optimiser curvesAll curves start at the same weights and use the same quadratic objective. The axes and the previously drawn curves stay fixed as another method is added. 0 5 10 15 20 25 30 35 40 Update number 1 0 − 6 1 0 − 5 1 0 − 4 1 0 − 3 1 0 − 2 1 0 − 1 1 0 0 1 0 1 Training cost J Gradient descent η = 0.075 Momentum η = 0.075 AdaGrad η = 0.3 RMSProp η = 0.11 Adam η = 0.14

The purple curve adds Adam. At the rates shown, it moves quickly at first and later overshoots. Changing the learning rate changes each run.

A sequence of optimiser developments

YearMethodAdded idea
1847Gradient descentFollow the negative gradient
1964MomentumUse the previous direction
2011AdaGradTrack each weight’s squared gradients
2012RMSPropDiscount older squared gradients
2014AdamCombine corrected moving averages
Selected historical landmarks, with dates of initial publication or introduction. Adam’s conference paper appeared in 2015. Cauchy. Polyak. AdaGrad. Hinton lecture. Adam preprint.

Lion · 2023

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.

Symbolic Discovery of Optimization Algorithms, by Xiangning Chen and colleagues. The paper lists Google and UCLA affiliations. Lion research paper.

Lion uses the sign of the direction

Combined directionSignUpdate
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.

This illustration uses zero weight decay. The Lion paper combines the current gradient with stored momentum for the sign step, then updates the stored momentum.

The optimiser in a training loop

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.

The model, compatible loss function and current batch already exist. The final four lines repeat for each batch. PyTorch also supplies SGD, Adagrad and RMSprop. PyTorch optimiser API.

Today we covered

  • Useful nonlinear features and the boundaries they create.
  • How trees learn questions, and how forests combine trees.
  • How an optimiser uses gradients and their history to choose updates.