Summative assessment

  • Part A is available now. It is collected at 2 pm on 8 December.
  • Part B is released then and collected at 2 pm on 9 December.
  • Validate and submit. Your latest submitted version is collected. This is individual work, with no GenAI.

Machine learning: review and practice

Today we will cover

  • Connect the main ideas from the course.
  • Use results to guide a sequence of model choices.
  • Examine what a successful test result does and does not establish.

What is Machine learning?

What is machine learning?A recreation of the introductory lecture diagram. Inputs and a human-written program enter a computer, which produces answers.DataWritten programComputerAnswersWrite the rule ourselves.

In ordinary programming, we supply the rule that turns inputs into answers.

What is Machine learning?

What is machine learning?A recreation of the introductory lecture diagram. Example inputs and their known answers enter a learning algorithm, which produces a learned program. This supervised-learning diagram concerns learning from labels.Example dataKnown answersLearningalgorithmLearnedprogramLearn the rule from examples.

In supervised learning, example inputs and answers help us learn a rule.

The goal is prediction on new examples

Learning a sensor response from examplesIllustrative synthetic sensor readings. Stage 0: Unknown coefficients illustrate the difficulty of writing a complete theory. The displayed formula is a candidate, not a claimed physical law. −1.00 −0.75 −0.50 −0.25 0.00 0.25 0.50 0.75 1.00 Scaled sensor setting 0.00 0.25 0.50 0.75 1.00 1.25 1.50 1.75 Sensor output (V) A first-principles model? y = a₀ + a₁x + a₂x² + a₃ sin(ωx + φ) + … a₀ = ? a₁ = ? a₂ = ? ω = ? φ = ?

A detailed theory can be difficult to work out. Could we learn the relationship from measured examples?

Synthetic sensor example. The formula is deliberately a possible explanatory model with unknown terms, not a supplied scientific law.

Learn a relationship from the readings

Learning a sensor response from examplesIllustrative synthetic sensor readings. Stage 1: Degree one, three and nine least-squares curves fitted to the same thirty training readings. −1.00 −0.75 −0.50 −0.25 0.00 0.25 0.50 0.75 1.00 Scaled sensor setting 0.00 0.25 0.50 0.75 1.00 1.25 1.50 1.75 Sensor output (V) Training readings Fitted degree 1 Fitted degree 3 Fitted degree 9

We can fit different curves to the measured inputs and outputs. Which one should we trust?

All three least-squares curves use the same thirty training points. Curves differ by polynomial degree.

A training fit is a first check

Learning a sensor response from examplesIllustrative synthetic sensor readings. Stage 2: One fitted curve, using training readings only. −1.00 −0.75 −0.50 −0.25 0.00 0.25 0.50 0.75 1.00 Scaled sensor setting 0.00 0.25 0.50 0.75 1.00 1.25 1.50 1.75 Sensor output (V) Training readings Fitted curve

This curve describes the readings we used to fit it. That alone does not show how well it predicts new readings.

The goal is prediction on new examples

Learning a sensor response from examplesIllustrative synthetic sensor readings. Stage 3: The same unchanged degree-nine fit is scored on twenty-four independent validation readings. −1.00 −0.75 −0.50 −0.25 0.00 0.25 0.50 0.75 1.00 Scaled sensor setting 0.00 0.25 0.50 0.75 1.00 1.25 1.50 1.75 Sensor output (V) Training readings Fitted curve Validation readings

Keep the curve fixed, then compare its predictions with readings it did not fit.

The twenty-four open red validation readings were generated independently. The fitted degree-nine curve is unchanged between the previous and current slides.

Match the task to the output

Match the task to the outputPetal measurements lead to a class label through classification. A sensor setting leads to a predicted reading through regression. Sixty-four measurements can become fewer coordinates through dimensionality reduction, without requiring class labels.PetalmeasurementsClassificationFlowerspeciesSensorsettingRegressionPredictedreading64 numericalinputsDimensionalityreductionFewercoordinates

Classification and regression use example targets. Dimensionality reduction can learn from the inputs alone.

A linear score

A linear boundary and a perceptron correctionActual Iris petal measurements for versicolor and virginica. Stage 0. The trial separator is taken from a fitted logistic model and rescaled without changing its position, then treated as a starting point for one perceptron update. The circled virginica has a negative starting score and a positive score after the update with eta 0.01. Other predictions can also change. 3.0 3.5 4.0 4.5 5.0 5.5 6.0 6.5 7.0 Petal length (cm) 1.00 1.25 1.50 1.75 2.00 2.25 2.50 2.75 Petal width (cm) Versicolor (0) Virginica (1)

Can we separate these two species using petal length and petal width?

A linear score

A linear boundary and a perceptron correctionActual Iris petal measurements for versicolor and virginica. Stage 1. The trial separator is taken from a fitted logistic model and rescaled without changing its position, then treated as a starting point for one perceptron update. The circled virginica has a negative starting score and a positive score after the update with eta 0.01. Other predictions can also change. 3.0 3.5 4.0 4.5 5.0 5.5 6.0 6.5 7.0 Petal length (cm) 1.00 1.25 1.50 1.75 2.00 2.25 2.50 2.75 Petal width (cm) Versicolor (0) Virginica (1) Trial boundary

\[ z=w_l x_l+w_w x_w+b \]

A score of zero marks the straight boundary.

What happens after a perceptron mistake?

A linear boundary and a perceptron correctionActual Iris petal measurements for versicolor and virginica. Stage 2. The trial separator is taken from a fitted logistic model and rescaled without changing its position, then treated as a starting point for one perceptron update. The circled virginica has a negative starting score and a positive score after the update with eta 0.01. Other predictions can also change. 3.0 3.5 4.0 4.5 5.0 5.5 6.0 6.5 7.0 Petal length (cm) 1.00 1.25 1.50 1.75 2.00 2.25 2.50 2.75 Petal width (cm) Virginica Versicolor (0) Virginica (1) Trial boundary

The circled virginica has label +1, but its score is -0.048. Which way should its score move?

For the perceptron illustration, labels are −1 and +1. The starting line is a rescaled fitted logistic separator, used here only as a trial boundary. This is separate from the later probability model.

The update pushes its score towards its label

A linear boundary and a perceptron correctionActual Iris petal measurements for versicolor and virginica. Stage 3. The trial separator is taken from a fitted logistic model and rescaled without changing its position, then treated as a starting point for one perceptron update. The circled virginica has a negative starting score and a positive score after the update with eta 0.01. Other predictions can also change. 3.0 3.5 4.0 4.5 5.0 5.5 6.0 6.5 7.0 Petal length (cm) 1.00 1.25 1.50 1.75 2.00 2.25 2.50 2.75 Petal width (cm) Virginica Versicolor (0) Virginica (1) Previous boundary After one update

\[ w\leftarrow w+\eta yx,\qquad b\leftarrow b+\eta y \]

For this example, the score changes from -0.048 to 0.234. Other predictions can change too.

One actual perceptron correction to the displayed starting parameters, using eta 0.01 and the measured petal coordinates. It is not a complete perceptron training run.

Should these flowers receive the same confidence?

Should these flowers receive the same confidence?Actual Iris examples. A and B are strong examples of versicolor and virginica according to a fitted two-feature logistic model. C has a fitted probability near one half. Only data and highlighted examples appear here, before the probability surface is revealed. 3.0 3.5 4.0 4.5 5.0 5.5 6.0 6.5 7.0 Petal length (cm) 1.00 1.25 1.50 1.75 2.00 2.25 2.50 2.75 Petal width (cm) Versicolor (0) Virginica (1) A B C

A looks strongly versicolor, B strongly virginica, and C is near the overlap. Should our predictions be equally confident?

A probability from the same score

A probability from the linear scoreThe same fitted two-input logistic model maps its score through a sigmoid. Actual displayed probabilities for highlighted flowers are computed from this model. This is a review illustration, separate from the digit investigation. 3.0 3.5 4.0 4.5 5.0 5.5 6.0 6.5 7.0 Petal length (cm) 1.00 1.25 1.50 1.75 2.00 2.25 2.50 2.75 Petal width (cm) Versicolor (0) Virginica (1) A: < 0.001 B: > 0.999 C: 0.52 0.00 0.15 0.30 0.45 0.60 0.75 0.90 P(virginica)

\[ p(y=1\mid x)=\frac{1}{1+e^{-z}} \]

The sigmoid converts a linear score into a probability. Labels are now 0 and 1.

A boundary side is evidence

Population frequencies affect a conditional probabilityIllustrative flower populations, not actual Iris points. There are fifty versicolor flowers, three on the virginica side. There are fifty virginica flowers, forty-seven on that side. The conditional probability of virginica given that side is 47/50, or 94%. 3.0 3.5 4.0 4.5 5.0 5.5 6.0 6.5 7.0 Petal length (illustrative) 1.0 1.5 2.0 2.5 3.0 Petal width (illustrative) Virginica side Virginica: 50 Versicolor: 50

The population has 50 virginica and 50 versicolor flowers. A flower falls on the virginica side. How likely is it to be virginica?

Illustrative counts, not points from the measured Iris data. The rule sends 94% of virginica and 6% of versicolor to the virginica side.

Condition on the evidence we observed

Population frequencies affect a conditional probabilityIllustrative flower populations, not actual Iris points. There are fifty versicolor flowers, three on the virginica side. There are fifty virginica flowers, forty-seven on that side. The conditional probability of virginica given that side is 47/50, or 94%. 3.0 3.5 4.0 4.5 5.0 5.5 6.0 6.5 7.0 Petal length (illustrative) 1.0 1.5 2.0 2.5 3.0 Petal width (illustrative) Virginica side Virginica: 50 Versicolor: 50

\[ P(V\mid\mathrm{side})=\frac{47}{47+3}=0.94 \]

Among the fifty flowers on that side are forty-seven virginica and three versicolor. The denominator conditions on the side.

Change the population, keep the same rule

Population frequencies affect a conditional probabilityIllustrative flower populations, not actual Iris points. There are fifty versicolor flowers, three on the virginica side. There are 450 virginica flowers, 423 on that side. The conditional probability of virginica given that side is 423/426, approximately 99.3%. The 94% and 6% conditional side rates are unchanged. 3.0 3.5 4.0 4.5 5.0 5.5 6.0 6.5 7.0 Petal length (illustrative) 1.0 1.5 2.0 2.5 3.0 Petal width (illustrative) Virginica side Virginica: 450 Versicolor: 50

Now there are 450 virginica and 50 versicolor. The same rule puts 423 virginica and 3 versicolor on that side.

\[ P(V\mid\mathrm{side})=\frac{423}{423+3}\approx0.993 \]

Prior frequencies change the posterior

Same side ratesFirst populationSecond population
Prior P(virginica)50%90%
P(virginica | side)94%99.3%

\[ P(V\mid S)=\frac{P(S\mid V)P(V)}{P(S\mid V)P(V)+P(S\mid\neg V)P(\neg V)} \]

The meaning of the observed evidence depends on how common each class was before seeing it.

S is the event of landing on the virginica side. Conditional side rates remain P(S|V)=0.94 and P(S|not V)=0.06 in both illustrative populations.

Two wrong labels, two different probabilities

Confidence changes the penaltyFor true label one, binary cross-entropy is negative natural log of p. Marked probabilities 0.01, 0.49 and 0.9 have losses approximately 4.61, 0.71 and 0.11. At cutoff 0.5 the first two decisions are both wrong. 0.0 0.2 0.4 0.6 0.8 1.0 Predicted probability of label 1 0 1 2 3 4 5 Loss when the true label is 1 p = 0.01 p = 0.49 p = 0.9

The true label is 1. At a cutoff of 0.5, p = 0.01 and p = 0.49 are both wrong. Should they receive the same penalty?

Cross-entropy distinguishes the errors

Confidence changes the penaltyFor true label one, binary cross-entropy is negative natural log of p. Marked probabilities 0.01, 0.49 and 0.9 have losses approximately 4.61, 0.71 and 0.11. At cutoff 0.5 the first two decisions are both wrong. 0.0 0.2 0.4 0.6 0.8 1.0 Predicted probability of label 1 0 1 2 3 4 5 Loss when the true label is 1 p = 0.01 loss = 4.61 p = 0.49 loss = 0.71 p = 0.9 loss = 0.11

\[ \ell=-y\ln p-(1-y)\ln(1-p) \]

A confident mistake receives a much larger loss.

One cost collects the example losses

\[ J=\frac{\ell_1+\ell_2+\cdots+\ell_N}{N} \]

\[ J=\frac{1}{N}\sum_{i=1}^{N}\ell_i \]

A mean loss describes the predictions across a set of examples. Training can also include a regularisation penalty.

Forward and backward calculations

Backpropagation through the Iris modelForward arrows connect parameters, score, probability, flower loss and training cost. Curved arrows run back from cost to weights, carrying the local slopes. Parameters w₁, w₂, b Score zᵢ Probability pᵢ = σ(zᵢ) Flower loss ℓ(yᵢ, pᵢ) Training cost mean loss J feature value sigmoid slope loss slope share of mean

The forward pass calculates predictions and loss. The backward pass applies the chain rule to calculate gradients.

This diagram concerns a differentiable model. A backward pass computes loss derivatives; the optimiser performs a subsequent parameter update. Trees and nearest-neighbour methods use different fitting procedures.

The optimiser takes the step

\[ \theta_{\mathrm{new}}=\theta-\eta\frac{\partial J}{\partial\theta} \]

Move parameters against their local cost slopes. Then calculate the next predictions using the changed parameters.

Batch, step and epoch

TermMeaning for iterative training
BatchExamples used together to calculate an update.
StepOne parameter update.
EpochOne complete pass through the training examples.

The learning rate controls the scale of a step.

The learning rate changes the path

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

Too small: slow progress. Goldilocks: useful steps. Too large: repeated overshooting can move us away from the minimum.

Reuses the earlier three U-shaped objective plots. The plotted paths are actual updates for the stated scalar objective and learning rates. It is a gradient-descent illustration, not the L-BFGS solver used in the digit investigation.

What do these loss curves suggest?

Illustrative training and validation loss curvesSchematic curves, not measured runs. Left: both losses remain high relative to an assumed attainable reference. Right: training loss falls while validation stays higher and eventually rises. These patterns motivate diagnostic questions rather than uniquely identifying a cause. 0 10 20 30 40 50 Epoch 0.0 0.2 0.4 0.6 0.8 1.0 Loss Both remain high Training Validation Attainable reference 0 10 20 30 40 50 Epoch A persistent gap Training Validation

Would more epochs be your first response in both cases?

Illustrative curves. A low attainable reference is assumed in the left panel.

Use curves to ask the next question

Illustrative training and validation loss curvesSchematic curves, not measured runs. Left: both losses remain high relative to an assumed attainable reference. Right: training loss falls while validation stays higher and eventually rises. These patterns motivate diagnostic questions rather than uniquely identifying a cause. 0 10 20 30 40 50 Epoch 0.0 0.2 0.4 0.6 0.8 1.0 Loss Both remain high Training Validation Attainable reference 0 10 20 30 40 50 Epoch A persistent gap Training Validation

Both high: compare with an attainable reference, then check optimisation, representation and capacity.

A persistent gap: check the split and data, then consider excessive flexibility or limited training information.

A curve pattern is evidence for a diagnostic question, not a unique explanation of the cause.

Which data should make each decision?

DecisionData role
Fit weights, axes or reference information?
Choose a model or checkpoint?
Evaluate the frozen choice?

Which data should make each decision?

DecisionData role
Fit weights, axes or reference informationTraining
Choose a model or checkpoint?
Evaluate the frozen choice?

Which data should make each decision?

DecisionData role
Fit weights, axes or reference informationTraining
Choose a model or checkpointValidation
Evaluate the frozen choice?

Which data should make each decision?

DecisionData role
Fit weights, axes or reference informationTraining
Choose a model or checkpointValidation
Evaluate the frozen choiceTest

Each set has a job

Three data rolesTraining examples fit parameters or reference information. Validation examples guide choices. Test examples evaluate a frozen choice. The case study uses 1077, 360 and 360 images, from a fixed stratified split.TrainingFit parametersValidationChoose modelTestFinal checkDecide the split before fitting and choosing the model.

Preprocessing learns from training data too. Validation and test examples reuse those fitted steps.

Bias and variance

Bias and variance with visible training measurementsEach line is fitted to one of six noisy samples of the same response, one plus 0.2 x squared. Every model uses 12 observations per sample. Black points show the first sample and the thicker curve is its fitted model. Other samples are shown through their fitted curves. The eighty-point samples contain the corresponding twelve-point subsets. No true-response dashed curve is drawn. −2 −1 0 1 2 Input x 0.5 1.0 1.5 2.0 2.5 Sensor response High bias Linear −2 −1 0 1 2 Input x Good fit Quadratic −2 −1 0 1 2 Input x High variance Flexible polynomial

Each fit uses 12 data points. The thin curves show how the fitted model changes across repeated noisy samples.

Six samples of the response 1+0.2x² with noise standard deviation 0.15. Black points show the first sample, whose fit is the thick line. All other lines use fresh noise on the same twelve inputs. The dashed true response is omitted.

More data helps some problems more than others

Bias and variance with visible training measurementsEach line is fitted to one of six noisy samples of the same response, one plus 0.2 x squared. Every model uses 80 observations per sample. Black points show the first sample and the thicker curve is its fitted model. Other samples are shown through their fitted curves. The eighty-point samples contain the corresponding twelve-point subsets. No true-response dashed curve is drawn. −2 −1 0 1 2 Input x 0.5 1.0 1.5 2.0 2.5 Sensor response High bias Linear −2 −1 0 1 2 Input x Good fit Quadratic −2 −1 0 1 2 Input x High variance Flexible polynomial

More data points can decrease variance. Each fit now uses 80 readings. The straight model still cannot follow the curve.

The larger samples include the twelve earlier observations and sixty-eight additional ones. Same model families, response and noise. The six high-degree fits now vary less.

A cutoff creates a decision

The cutoff changes the inspection decisionsThe same illustrative twenty parts are scored at cutoff 0.5. Counts: TP 8, FP 3, FN 2, TN 7. Recall 0.8, precision 0.727273. Points on the cutoff are flagged. The score values are explanatory, not a new measured experiment. 0.0 0.2 0.4 0.6 0.8 1.0 Model score Actual clear Actual defect Flag if score ≥ 0.5

FlaggedNot flagged
Actual defect8 true positives2 false negatives
Actual clear3 false positives7 true negatives

\[ \mathrm{Recall}=\frac{8}{8+2}=0.80\qquad\mathrm{Precision}=\frac{8}{8+3}=0.73 \]

The same twenty illustrative scores are used throughout. Flag means score greater than or equal to the cutoff. Actual defects are the positive class.

A lower cutoff flags more parts

The cutoff changes the inspection decisionsThe same illustrative twenty parts are scored at cutoff 0.25. Counts: TP 10, FP 7, FN 0, TN 3. Recall 1, precision 0.588235. Points on the cutoff are flagged. The score values are explanatory, not a new measured experiment. 0.0 0.2 0.4 0.6 0.8 1.0 Model score Actual clear Actual defect Flag if score ≥ 0.25

FlaggedNot flagged
Actual defect10 true positives0 false negatives
Actual clear7 false positives3 true negatives

\[ \mathrm{Recall}=\frac{10}{10+0}=1.00\qquad\mathrm{Precision}=\frac{10}{10+7}=0.59 \]

The same twenty illustrative scores are used throughout. Flag means score greater than or equal to the cutoff. Actual defects are the positive class.

A higher cutoff flags fewer parts

The cutoff changes the inspection decisionsThe same illustrative twenty parts are scored at cutoff 0.8. Counts: TP 4, FP 1, FN 6, TN 9. Recall 0.4, precision 0.8. Points on the cutoff are flagged. The score values are explanatory, not a new measured experiment. 0.0 0.2 0.4 0.6 0.8 1.0 Model score Actual clear Actual defect Flag if score ≥ 0.8

FlaggedNot flagged
Actual defect4 true positives6 false negatives
Actual clear1 false positives9 true negatives

\[ \mathrm{Recall}=\frac{4}{4+6}=0.40\qquad\mathrm{Precision}=\frac{4}{4+1}=0.80 \]

The same twenty illustrative scores are used throughout. Flag means score greater than or equal to the cutoff. Actual defects are the positive class.

A ROC curve sweeps the cutoff

Three inspection cutoffs on one ROC curveThe full ROC is calculated from the same twenty fixed scores. The three highlighted points correspond exactly to cutoffs 0.25, 0.5 and 0.8 in the preceding plots. Their false-positive and true-positive rate pairs are (0.7,1), (0.3,0.8) and (0.1,0.4). 0.0 0.2 0.4 0.6 0.8 1.0 False-positive rate 0.0 0.2 0.4 0.6 0.8 1.0 True-positive rate (recall) Cutoff 0.5 Cutoff 0.25 Cutoff 0.8

Each cutoff gives one pair of rates. Sweeping through all cutoffs traces the full ROC curve.

The same constructed scores give AUC 0.82. The three highlighted points exactly match the preceding cutoff decisions. AUC measures score ranking, not probability calibration.

Cross-validation repeats a complete fit

Cross-validation refits the entire pipelineThree folds rotate the checked examples. Within each fold, preprocessing and the classifier learn only from that fold’s training examples. The orange fold uses those fitted objects without contributing to their fit.Fold 1CheckFitFitFresh preprocessing and modellearned from the blue rows onlyFold 2FitCheckFitFresh preprocessing and modellearned from the blue rows onlyFold 3FitFitCheckFresh preprocessing and modellearned from the blue rows onlyEach fold starts a new fit of every learned step.

Each fold learns its own preprocessing and model from its training portion. Compare settings on the same folds.

Three-fold schematic from the previous lecture. Related examples, such as photos of one cardholder, should stay together when the goal is generalisation to new holders. A random image split tests a different claim.

What if the useful boundary is curved?

A nonlinear representation makes a straight cutoff possibleThe same 110 illustrative beam offsets. Labels depend on whether squared radial offset exceeds 1.69 square millimetres. Only measurements and known labels appear, with no boundary drawn. −2 −1 0 1 2 Horizontal beam offset (mm) −2 −1 0 1 2 Vertical beam offset (mm) Within tolerance Outside tolerance

These beam measurements have known labels. Could one straight line enclose all the accepted readings?

A new feature can simplify the rule

\[ \phi=(\mathrm{Horizontal\ beam\ offset})^2+(\mathrm{Vertical\ beam\ offset})^2 \]

This is the squared distance from the target centre. A single cutoff on that value could decide whether the offset is acceptable.

Both original offsets are in millimetres, so the new feature is in square millimetres.

A straight cutoff in the new feature

A nonlinear representation makes a straight cutoff possibleThe same 110 illustrative beam offsets. Labels depend on whether squared radial offset exceeds 1.69 square millimetres. The only new predictor is horizontal offset squared plus vertical offset squared. Its vertical cutoff separates the classes. Vertical rows are display offsets, not a second predictor. 0 2 4 6 8 New feature: horizontal offset² + vertical offset² (mm²) Cutoff = 1.3² = 1.69 mm² Rows separate the marks for visibility Within tolerance Outside tolerance

\[ \mathrm{Accept\ if}\quad\phi\leq1.3^2=1.69\ \mathrm{mm}^2 \]

These are exactly the same 110 points and labels as the preceding raw plot. Vertical row offsets separate the marks for viewing and are not another predictor.

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

We have temperature, vibration and the known outcome for each part. What questions could separate the labels?

A tree learns its questions

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

Successive questions divide the inputs into regions. During fitting, the tree chooses useful questions from labelled examples.

The questions divide the input space

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

This small example needs two threshold questions. Their leaves create the rectangular decision regions.

Different samples can produce different trees

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

The trees see different training samples. What do they predict for the same marked point P?

Combine the trees’ predictions

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

\[ P(\mathrm{defect}\mid P)=\frac{0+1+1}{3}\approx0.67 \]

Average the class probabilities, then choose the class.

The three actual trees in the earlier beam illustration assign defect probabilities zero, one and one at the marked point P. This is not the later three-hundred-tree digit forest.

A forest can make predictions more stable

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

Different training samples and feature choices produce varied trees. Their average can be less sensitive to one particular fitted tree.

The reused beam illustration compares one tree with sixty trees on the same alignment dataset. The digit case study later uses three hundred trees.

Support vector machines

Linear SVM geometryThe fitted soft-margin boundary gives two prediction regions. Defect A is inside the margin on the defect side. Defect B falls on the clear side and is misclassified. −3 0 3 Texture contrast −3 0 3 Edge strength Predict defect Predict clear Clear Defect Decision boundary B A

An SVM balances a wide separating margin against costly violations. A soft margin allows exceptions.

Reuses the earlier fitted soft-margin boundary. Support vectors determine the solution; the penalty parameter controls the cost of violations. This recap does not introduce a new kernel or mathematical derivation.

Nearest neighbours use reference examples

A new flower and its nearest reference examplesThe same one hundred versicolor and virginica training measurements and one new query location. The 5 nearest training examples are ringed using Euclidean distance after training standardisation. 3.0 3.5 4.0 4.5 5.0 5.5 6.0 6.5 7.0 Petal length (cm) 0.75 1.00 1.25 1.50 1.75 2.00 2.25 2.50 2.75 Petal width (cm) Versicolor Virginica New flower

At prediction time, find nearby stored training examples and use their labels to vote.

The neighbourhood controls the regions

Three neighbourhood sizes on the same ninety examplesDecision regions for one, nine and all ninety neighbours. Every panel uses the same example coordinates, labels, distance convention, axis limits and class colours. Smoothness and training appearance alone do not establish predictive performance. k = 1 k = 9 k = 90 (all)

Small k can follow individual examples. With k equal to the whole reference set, the same majority wins everywhere.

The three panels use the same ninety synthetic examples: fifty squares and forty circles. At k=90 all points vote at every location.

The representation changes distance

House inputs have different numerical scalesAn illustrative house has floor area 2000 square feet and four bedrooms. Assume training means 1500 square feet and three bedrooms, and standard deviations 500 square feet and one bedroom. Raw deviations are five hundred and one; each becomes one standard deviation after standardisation. The bars compare numerical differences in different units, not predictive importance.Raw differencesAfter standardisationFloor area+500 ft²+1 sBedrooms+1 bedroom+1 sBoth inputs are one training standard deviation above their means.

Expressing measurements in training standard deviations changes their relative numerical influence on a distance rule.

Illustrative house: 2000 ft² and four bedrooms, against means 1500 and three, standard deviations 500 and one. Both transformed deviations are +1. This does not establish equal predictive usefulness.

Many inputs can weaken neighbour contrast

The nearest input can become less distinctiveFor each of two and one hundred independent uniform dimensions, ninety references are ranked by Euclidean distance to one new uniform query. Distances are divided by their own mean. The rank still exists, but the relative contrast between nearest and typical references is weaker in the hundred-input example. 0 20 40 60 80 Reference examples, nearest first 0.0 0.5 1.0 1.5 2.0 Distance divided by mean distance 2 inputs 0 20 40 60 80 Reference examples, nearest first 100 inputs

“Nearest” can be only slightly closer than typical examples. Useful structure and a suitable representation still matter.

Independent uniform-coordinate example from the previous lecture. This is relative distance concentration, not a universal assertion about all high-dimensional data.

PCA keeps directions of variation

Projected temperature readingsThe same eighty centred sensor measurements are projected onto a unit direction at 0 degrees. Squared projected scores sum to 316.00000000; dividing by seventy-nine gives sample variance 4.00000000. Orange points are the projections and faint connectors show discarded perpendicular offsets. −5.0 −2.5 0.0 2.5 5.0 A minus its mean (°C) −6 −4 −2 0 2 4 6 B minus its mean (°C) 0°

At 0°, the projected sample variance is 4.00 °C². Could another direction keep more?

The same eighty centred temperature readings and the same Celsius units are used in every orientation. PC1 is the direction with maximum projected variance. The variance in PC2 is 0.32 °C².

PCA keeps directions of variation

Projected temperature readingsThe same eighty centred sensor measurements are projected onto a unit direction at 20 degrees. Squared projected scores sum to 502.87121389; dividing by seventy-nine gives sample variance 6.36545840. Orange points are the projections and faint connectors show discarded perpendicular offsets. −5.0 −2.5 0.0 2.5 5.0 A minus its mean (°C) −6 −4 −2 0 2 4 6 B minus its mean (°C) 20°

At 20°, the projected sample variance is 6.37 °C². Could another direction keep more?

The same eighty centred temperature readings and the same Celsius units are used in every orientation. PC1 is the direction with maximum projected variance. The variance in PC2 is 0.32 °C².

PCA keeps directions of variation

Projected temperature readingsThe same eighty centred sensor measurements are projected onto a unit direction at 70 degrees. Squared projected scores sum to 502.87121389; dividing by seventy-nine gives sample variance 6.36545840. Orange points are the projections and faint connectors show discarded perpendicular offsets. −5.0 −2.5 0.0 2.5 5.0 A minus its mean (°C) −6 −4 −2 0 2 4 6 B minus its mean (°C) 70°

At 70°, the projected sample variance is 6.37 °C². Could another direction keep more?

The same eighty centred temperature readings and the same Celsius units are used in every orientation. PC1 is the direction with maximum projected variance. The variance in PC2 is 0.32 °C².

PCA keeps directions of variation

Projected temperature readingsThe same eighty centred sensor measurements are projected onto a unit direction at 45 degrees. Squared projected scores sum to 606.72000000; dividing by seventy-nine gives sample variance 7.68000000. Orange points are the projections and faint connectors show discarded perpendicular offsets. −5.0 −2.5 0.0 2.5 5.0 A minus its mean (°C) −6 −4 −2 0 2 4 6 B minus its mean (°C) 45°

At 45°, the projected sample variance is 7.68 °C². This direction keeps 96% of the original variance.

The same eighty centred temperature readings and the same Celsius units are used in every orientation. PC1 is the direction with maximum projected variance. The variance in PC2 is 0.32 °C².

Could compression lose the useful distinction?

A low-variance petal width can distinguish speciesIllustrative synthetic flower measurements, not Iris observations. The species have identical petal lengths spanning two to eight centimetres, but different widths near 0.85 and 1.15 centimetres. Unscaled covariance PCA retains more than ninety-nine percent of variance in the petal-length direction and discards the class distinction. Tiny vertical display offsets in the one-dimensional comparison are only to distinguish plotted markers, not retained features. 2 3 4 5 6 7 8 Petal length (cm) 0.6 0.8 1.0 1.2 1.4 Petal width (cm) Species A Species B

Which direction varies most? Which distinguishes these illustrative flower species?

Large variance and useful evidence can differ

A low-variance petal width can distinguish speciesIllustrative synthetic flower measurements, not Iris observations. The species have identical petal lengths spanning two to eight centimetres, but different widths near 0.85 and 1.15 centimetres. Unscaled covariance PCA retains more than ninety-nine percent of variance in the petal-length direction and discards the class distinction. Tiny vertical display offsets in the one-dimensional comparison are only to distinguish plotted markers, not retained features. 2 3 4 5 6 7 8 Petal length (cm) 0.6 0.8 1.0 1.2 1.4 Petal width (cm) Species A Species B 2 3 4 5 6 7 8 Retained petal-length coordinate The species now overlap

The retained length coordinate preserves over 99% of the variance but loses the width distinction between species.

Synthetic illustrative flower measurements, not Iris data. This counterexample uses unscaled, centred inputs. PCA preserves input variation, not a class-separation objective.

A neural network learns intermediate features

A sigmoid feedforward networkThere are 1 hidden layers of three sigmoid units. Grey edges carry the forward calculation. Blue arrows carry loss gradients backwards to the weights and biases. The input measurements stay fixed.Loss ℓℓ(y, p)Inputsxₗx_wFixed dataHidden layerh₁σh₂σh₃σSigmoid featuresProbabilitypσp(virginica)W, bv, c

Hidden units transform the input. The output combines those learned responses, and one loss trains both sets of weights.

Nonlinear activations change what can be represented

Two nonlinear activationsSigmoid and ReLU responses. Nonlinear activations prevent a stack of affine maps collapsing to one affine map. Sigmoid can have small slopes when saturated; ReLU supplies a different gradient pattern but is not a universal solution. −4 −2 0 2 4 Unit input 0.0 0.2 0.4 0.6 0.8 1.0 Unit output Sigmoid −4 −2 0 2 4 Unit input 0 1 2 3 4 5 ReLU

Without nonlinear activations, stacked affine layers still give one affine map. With them, the feature map can bend.

Return to XOR

Nonlinear features can solve XORFour XOR corner labels. No one straight line separates the two positive corners from the two negative corners. 0 1 Input x₁ 0 1 Input x₂ 0 1 1 0

Could one straight line separate the two positive corners from the negative corners?

Hidden features can create a different region

Nonlinear features can solve XORFour XOR corner labels. Two threshold-like hidden features can form a positive middle band in x₁+x₂, bounded at 0.5 and 1.5. The drawn sharp band is conceptual; smooth sigmoids can approximate it. 0 1 Input x₁ 0 1 Input x₂ 0 1 1 0

Two threshold-like responses can select the middle band. A nonlinear representation changes the possible decision regions.

More layers, the same training principle

A sigmoid feedforward networkThere are 2 hidden layers of three sigmoid units. Grey edges carry the forward calculation. Blue arrows carry loss gradients backwards to the weights and biases. The input measurements stay fixed.Loss ℓℓ(y, p)Inputsxₗx_wFixed dataHidden layer 1h₁σh₂σh₃σSigmoid featuresHidden layer 2r₁σr₂σr₃σSigmoid featuresProbabilitypσp(virginica)W, bU, dv, c

Forward calculations produce an output. Backpropagation carries loss gradients through every layer, then the optimiser updates the parameters.

A two-hidden-layer Iris network from lecture five. More capacity can represent more complex functions but also requires suitable data and successful optimisation; it does not itself guarantee generalisation.

CNNs reuse local weights

A kernel operation from patch to responseA three by three binary patch is multiplied element by element by a kernel with rows minus one, zero, one. The nine products are zero, zero, one repeated three times, and sum to three. Bias is zero.Patch001001001Kernel-101-101-101Products001001001×=Sum3Multiply the nine matching pairs, then add their products.

The same filter reads many image patches. Training learns which local responses help the task.

The shown hand-chosen explanatory kernel yields a sum of three. Real CNN filter values are learned. Parameter sharing supplies a useful inductive bias for spatial inputs.

Pretrained models reuse learned features

Using a pretrained image modelAn image enters a feature extractor whose weights have already been trained. A new task-specific output head is fitted to suitable labelled examples. Fine-tuning some reused weights may also help.New imagePixel valuesPretrained modelLearned visual featuresNew output headFit new labelsMost visual features can be reused; adapt the last step.

An existing image feature extractor can support a new output head. Check the new task and input convention with representative examples.

Optimisers change how parameters move

ApproachIdea
SGDUse the current gradient estimate.
MomentumAccumulate a direction across updates.
AdaGrad / RMSPropUse gradient history to adjust parameter scales.
AdamCombine a moving direction with adaptive scaling.

The optimiser changes the route through parameter space. Validation still decides whether the resulting model is useful.

Control flexibility as well as optimisation

Loss contours meet L1 and L2 weight budgetsThe same quadratic loss is drawn in two panels. The lowest allowed contour touches the L1 diamond at (1, 0) and the L2 circle at a point with both weights positive. The crosses mark the unconstrained minimum. −1 0 1 2 3 Weight w₁ −1 0 1 2 Weight w₂ Lowest allowed loss Best without penalty L1 weight budget −1 0 1 2 3 Weight w₁ −1 0 1 2 Weight w₂ Lowest allowed loss Best without penalty L2 weight budget

Weight penalties, capacity choices and validation-based early stopping can constrain the fitted solution.

Earlier L1/L2 constraint illustration. A fixed penalty parameter favours smaller parameter norms. Early stopping uses validation behaviour and is different from merely lowering training cost.

Different methods fit different things

MethodWhat is fitted or retained
Logistic / neural modelsWeights and biases.
Trees and forestsSplit rules and leaf predictions.
Nearest neighboursReference examples and a search structure.
PCAMeans and projection directions.

A shared prediction workflow does not mean every method uses backpropagation.

The next choice needs a reason

ObservationA useful first question
Poor training and validation fitHave we checked optimisation, representation and capacity?
Excellent training, weaker validationHow specific or sample-sensitive is this fit?
Good held-out score, poor new inputsDoes the evaluation represent the intended use?

We will now use this reasoning in one complete investigation.

An ML investigation

Start with the data

Training rowx₂₈x₃₆x₄₄Other inputsLabel
Example 1400…9
Example 2161515…1
Example 3151213…8
Example 41129…4

There are 64 numerical inputs and a supplied label from 0 to 9. Can we predict the label on new rows?

Four actual rows from the fixed training split. The displayed columns are one-based pixel coordinates 28, 36 and 44. The other sixty-one inputs are omitted from the table only, not the model. This frames the task as an empirical mapping from measurements to labels.

Reading handwritten digits

Real training examples from the digit collectionTen actual training images from scikit-learn load_digits, one per label zero to nine, selected as original samples near their own training class means. Each image has sixty-four measured brightness values from zero to sixteen. No test images appear in this gallery.0123456789Actual training images: 8 × 8 pixels, one label from 0 to 9.

Here the 64 measurements are the pixels of an 8 × 8 image. The label tells us which digit it represents.

All case-study numbers are computed from scikit-learn 1.8.0 load_digits. Fixed stratified split, random_state=8: 1077 training, 360 validation, 360 test. Each model is fitted only on training rows. Selection uses validation accuracy; ties prefer the linear model, then forest, then the single tree. The selected trained model is frozen without refitting before final test evaluation. The translation diagnostic is evaluated afterwards and does not change model selection. scikit-learn digit dataset.These are prepared arrays, not raw camera images. We can begin with the supplied input columns and labels, then use the application context to guide checks.

Define success before comparing models

  • Primary measure: accuracy on held-out examples.
  • Secondary checks: probability loss, mistakes and model complexity.

We will also test a small position change after freezing the model.

All case-study numbers are computed from scikit-learn 1.8.0 load_digits. Fixed stratified split, random_state=8: 1077 training, 360 validation, 360 test. Each model is fitted only on training rows. Selection uses validation accuracy; ties prefer the linear model, then forest, then the single tree. The selected trained model is frozen without refitting before final test evaluation. The translation diagnostic is evaluated afterwards and does not change model selection. The stress test is one zero-filled column shift to the right, restricted to images whose rightmost column is blank, so no foreground is lost. It is a diagnostic and does not select a new model.

Inspect the training examples

Different training examples of threes and ninesEight original training images, using the first four threes and first four nines in the fixed training index order. Every original pixel is displayed as one square, with no smoothing. These show variation within labels and possible similarities between labels. No validation or test rows are shown.Label: 3Label: 3Label: 3Label: 3Label: 9Label: 9Label: 9Label: 9Different handwriting; the same fixed pixel grid.

There is variation within a label as well as differences between labels. Each image still supplies the same 64 pixel coordinates.

Eight original training rows: the first four threes and first four nines in the fixed training index order. No test examples are used here. The complete collection contains 1,797 images. Brightness arrays use zero for background and sixteen for strong stroke; the display is inverted to dark ink on a white slide. Digit dataset.

Fix the data split

Three data rolesTraining examples fit parameters or reference information. Validation examples guide choices. Test examples evaluate a frozen choice. The case study uses 1077, 360 and 360 images, from a fixed stratified split.Training1,077 imagesValidation360 imagesTest360 imagesDecide the split before fitting and choosing the model.

Use the same training and validation rows for all three experiments. Keep the final test set outside these choices.

All case-study numbers are computed from scikit-learn 1.8.0 load_digits. Fixed stratified split, random_state=8: 1077 training, 360 validation, 360 test. Each model is fitted only on training rows. Selection uses validation accuracy; ties prefer the linear model, then forest, then the single tree. The selected trained model is frozen without refitting before final test evaluation. The translation diagnostic is evaluated afterwards and does not change model selection.

Give the first score a reference

Always predicting the most common training label would get 36/360 validation images right.

That is about 10%. Our first learned model should demonstrate much more than this.

All case-study numbers are computed from scikit-learn 1.8.0 load_digits. Fixed stratified split, random_state=8: 1077 training, 360 validation, 360 test. Each model is fitted only on training rows. Selection uses validation accuracy; ties prefer the linear model, then forest, then the single tree. The selected trained model is frozen without refitting before final test evaluation. The translation diagnostic is evaluated afterwards and does not change model selection. The most common training label is 1; its actual validation count is 36. This simple reference is calculated from training class frequency, not chosen from validation performance.

Experiment 1: multinomial logistic regression

linear = make_pipeline(
    StandardScaler(),
    LogisticRegression(C=1, solver="lbfgs",
                       max_iter=2000, random_state=8)
)
linear.fit(X_train, y_train)

With ten labels, this fits ten linear class scores and converts them to probabilities with softmax.

All case-study numbers are computed from scikit-learn 1.8.0 load_digits. Fixed stratified split, random_state=8: 1077 training, 360 validation, 360 test. Each model is fitted only on training rows. Selection uses validation accuracy; ties prefer the linear model, then forest, then the single tree. The selected trained model is frozen without refitting before final test evaluation. The translation diagnostic is evaluated afterwards and does not change model selection. LogisticRegression documentation.The shown solver is explicit for clarity. L-BFGS was already the default in the original numerical run, so this is the same model, not a new fit with changed settings. Standardisation is fitted using training only. C=1 uses the default L2 regularisation.

Ten scores from 64 inputs

\[ z_k=\sum_{j=1}^{64}w_{kj}\widetilde{x}_j+b_k,\qquad k=0,\ldots,9 \]

One measured input gives ten scores and ten probabilitiesActual fitted linear-model outputs for one training image labelled three, source index 578. Softmax of the ten recorded class scores equals the model probability output. Probabilities sum to one. This example illustrates the calculation and is not evidence of generalisation. 0 1 2 3 4 5 6 7 8 9 Candidate digit −6 −4 −2 0 2 4 6 Score zₖ Ten linear class scores 0 1 2 3 4 5 6 7 8 9 Candidate digit 0.0 0.2 0.4 0.6 0.8 1.0 Probability 0.727 Softmax probabilities

\[ P(y=k\mid x)=\frac{e^{z_k}}{\sum_{c=0}^{9}e^{z_c}} \]

Tilde x denotes each pixel after the fitted training scaler. The actual chart uses training image 578, labelled three. It is selected for a true-class probability near 0.75 so that several bars are visible, not as an error-rate sample. Each class has its own weights and bias. We choose the class with largest probability. Softmax couples all ten probabilities; these are not ten independent sigmoid outputs.

Straight boundaries in many inputs

Straight boundaries in a slice of the actual digit modelAn actual two-dimensional slice of the fitted multinomial model. Two PCA directions are learned on the standardized training inputs solely for display. The other 62 directions are fixed at the training mean. Each displayed polygon is calculated by intersecting exact affine score inequalities. No projected observations are overlaid because observations usually do not lie in this plane. This is not a reduced-input model or an accuracy plot. −6 −4 −2 0 2 4 6 Direction 1 through the pixel inputs −4 −2 0 2 4 6 Direction 2 through the pixel inputs 2 3 4 6 7 8

This is one two-dimensional slice of the fitted 64-input model. Where two class scores tie, their boundary is straight.

The figure uses two PCA directions through standardized training inputs solely to choose a display plane. All other directions are fixed at their training mean. No observations are projected onto the regions. This is not a two-feature model and not an accuracy assessment. The original validation predictions remain exactly unchanged.

Would linear scores be enough?

The prepared input coordinates may already contain useful class structure.

Hypothesis: a simple linear baseline can recognise many examples. We will measure how well it generalises.

What should we examine besides the training score?

The linear baseline is already strong

Training fit and validation predictionsMeasured accuracies from the fixed 1077-image training set and the same 360-image validation set. Models shown: linear. The original final test set has no role in these comparisons. Linear model 0 20 40 60 80 100 Accuracy (%) 99.8% 96.1% Training Validation

ModelTrain correctValidation correctValidation loss
Linear model1,075 / 1,077346 / 3600.115
All case-study numbers are computed from scikit-learn 1.8.0 load_digits. Fixed stratified split, random_state=8: 1077 training, 360 validation, 360 test. Each model is fitted only on training rows. Selection uses validation accuracy; ties prefer the linear model, then forest, then the single tree. The selected trained model is frozen without refitting before final test evaluation. The translation diagnostic is evaluated afterwards and does not change model selection. Loss in this table is mean validation cross-entropy, lower is better.

Which mistakes repeat?

Validation confusion matrix for the linear baselineRows are true labels and columns predicted labels for the same 360 validation images used in model comparison. Cell values are actual example counts, not percentages. Only nonzero counts are printed; the diagonal represents correct predictions.Predicted digit00112233445566778899Observed digit341331236133335137362341341134Counts from the 360 validation images.

Read an off-diagonal cell as an observed digit receiving another label.

All case-study numbers are computed from scikit-learn 1.8.0 load_digits. Fixed stratified split, random_state=8: 1077 training, 360 validation, 360 test. Each model is fitted only on training rows. Selection uses validation accuracy; ties prefer the linear model, then forest, then the single tree. The selected trained model is frozen without refitting before final test evaluation. The translation diagnostic is evaluated afterwards and does not change model selection. Largest directed off-diagonal counts: 3 → 5 (3), 7 → 4 (2), 1 → 8 (2). Cell values are validation counts, not training or test counts.

Look at the mistaken inputs

Actual mistaken digit predictionsSix validation errors by the linear model, ordered by largest predicted-class probability among its mistakes. Labels and displayed probabilities are computed from the fitted model. This illustrates selected errors rather than a representative error-frequency sample.True: 3Pred: 5p = 0.89True: 4Pred: 9p = 0.87True: 1Pred: 8p = 0.79True: 9Pred: 8p = 0.75True: 3Pred: 2p = 0.74True: 7Pred: 4p = 0.69Six of the linear model’s validation mistakes.

Some errors are uncertain; others assign high probability to the wrong class.

All case-study numbers are computed from scikit-learn 1.8.0 load_digits. Fixed stratified split, random_state=8: 1077 training, 360 validation, 360 test. Each model is fitted only on training rows. Selection uses validation accuracy; ties prefer the linear model, then forest, then the single tree. The selected trained model is frozen without refitting before final test evaluation. The translation diagnostic is evaluated afterwards and does not change model selection. Six actual validation errors, selected in descending predicted-class probability among the fourteen mistakes. The chosen images illustrate failure types and are not a random sample of the error population.

A reason to try a different rule

Hypothesis: learned pixel combinations may fix mistakes that linear class scores leave behind.

A tree can learn successive brightness questions, creating a more flexible decision rule.

The training fit is already very strong. Extra flexibility also risks overfitting, so validation must decide.

We deliberately compare another family while retaining the same raw information, split and primary measure. A tree can express nonlinear interactions, but that alone does not predict its validation performance.

Experiment 2: a decision tree

tree = DecisionTreeClassifier(random_state=8)
tree.fit(X_train, y_train)

Let the tree choose its splits without an explicit depth limit.

All case-study numbers are computed from scikit-learn 1.8.0 load_digits. Fixed stratified split, random_state=8: 1077 training, 360 validation, 360 test. Each model is fitted only on training rows. Selection uses validation accuracy; ties prefer the linear model, then forest, then the single tree. The selected trained model is frozen without refitting before final test evaluation. The translation diagnostic is evaluated afterwards and does not change model selection. The tree sees the raw pixel arrays; their common units already match. Axis-aligned splits do not require the same standardisation used by the linear model. Decision trees.

The tree learns actual pixel questions

Actual learned pixel thresholdsThe first three internal nodes of the fitted unpruned decision tree are shown using one-based row and column positions in the eight-by-eight image. Yes means brightness less than or equal to the recorded threshold. These are actual fitted thresholds, not manually chosen rules; lower branches are omitted.Pixel (5, 5)brightness ≤ 0.5?Pixel (6, 3)brightness ≤ 5?YesContinue splitting…Pixel (3, 6)brightness ≤ 0.5?NoContinue splitting…First two levels only. Pixel rows and columns start at 1.

Each input follows the questions until it reaches a leaf with class probabilities.

All case-study numbers are computed from scikit-learn 1.8.0 load_digits. Fixed stratified split, random_state=8: 1077 training, 360 validation, 360 test. Each model is fitted only on training rows. Selection uses validation accuracy; ties prefer the linear model, then forest, then the single tree. The selected trained model is frozen without refitting before final test evaluation. The translation diagnostic is evaluated afterwards and does not change model selection. The diagram is the actual root and its two children. Pixel positions are one-based row and column indices. Only the top two levels are displayed; it is not the full tree.

Perfect training accuracy

The tree gets 1,077/1,077 training images right.

Have we solved the problem?

Now reveal the validation result

Training fit and validation predictionsMeasured accuracies from the fixed 1077-image training set and the same 360-image validation set. Models shown: linear, tree. The original final test set has no role in these comparisons. Linear model Single tree 0 20 40 60 80 100 Accuracy (%) 99.8% 100.0% 96.1% 83.9% Training Validation

ModelTrain correctValidation correctValidation loss
Linear model1,075 / 1,077346 / 3600.115
Single tree1,077 / 1,077302 / 3605.807
All case-study numbers are computed from scikit-learn 1.8.0 load_digits. Fixed stratified split, random_state=8: 1077 training, 360 validation, 360 test. Each model is fitted only on training rows. Selection uses validation accuracy; ties prefer the linear model, then forest, then the single tree. The selected trained model is frozen without refitting before final test evaluation. The translation diagnostic is evaluated afterwards and does not change model selection. The tree makes 58 validation mistakes. Its pure leaves can give the true class probability zero on a wrong prediction. Numerical log_loss clips probabilities at machine precision, so the reported mean cross-entropy is finite rather than infinity.

More specific did not mean more useful

This tree has depth 13 and 117 leaves.

It reproduces the training labels perfectly but makes more mistakes on the validation examples.

The gap motivates checking how sensitive the fitted rules are to the particular training sample.

The observed gap does not uniquely establish a cause. The next diagnostic directly changes training samples to investigate sensitivity, using validation only.

Change the sample, change the tree

Changing the training sample changes predictionsThree new decision-tree fits use bootstrap resamples of the original training set, with the learner’s random seed held fixed. They disagree on at least one prediction for 123 of 360 validation images. Six disagreements are displayed. Only training rows were resampled; these are validation diagnostics, not final test results.True 3A: 1B: 9C: 9True 9A: 9B: 5C: 3True 1A: 1B: 1C: 4True 4A: 0B: 4C: 4True 3A: 3B: 2C: 2True 8A: 2B: 8C: 8These three refits disagree on 123 of 360 validation inputs.

Refit the same learner on three bootstrap samples of the training rows. Their predictions can disagree.

All case-study numbers are computed from scikit-learn 1.8.0 load_digits. Fixed stratified split, random_state=8: 1077 training, 360 validation, 360 test. Each model is fitted only on training rows. Selection uses validation accuracy; ties prefer the linear model, then forest, then the single tree. The selected trained model is frozen without refitting before final test evaluation. The translation diagnostic is evaluated afterwards and does not change model selection. Three diagnostic tree fits, with the learner seed held fixed at eight. Resampling uses seeds 100, 101 and 102. They disagree on at least one prediction for 123/360 validation images. Displayed examples are the first six disagreements.

What could averaging help with?

A forest averages multiple tree predictionsSeveral trees use bootstrap resamples and random feature subsets. Their class-probability predictions are averaged for a new input. This is a simplified three-tree illustration; the case study uses three hundred trees.Tree 1Different training viewsTree 2Different training viewsTree 3Different training viewsAverage class probabilitiesThen choose a class

Could different trees compensate for some of one another’s sample-specific choices?

Experiment 3: a random forest

forest = RandomForestClassifier(
    n_estimators=300, max_features="sqrt", random_state=8
)
forest.fit(X_train, y_train)

Bootstrap the training rows, vary the features considered at splits, then average the trees’ class probabilities.

All case-study numbers are computed from scikit-learn 1.8.0 load_digits. Fixed stratified split, random_state=8: 1077 training, 360 validation, 360 test. Each model is fitted only on training rows. Selection uses validation accuracy; ties prefer the linear model, then forest, then the single tree. The selected trained model is frozen without refitting before final test evaluation. The translation diagnostic is evaluated afterwards and does not change model selection. n_jobs=1 is used in the numerical run for a simple reproducible execution setup. No search over tree counts, depths or seeds was used to choose a favourable narrative. RandomForestClassifier.

The forest improves on the single tree

Training fit and validation predictionsMeasured accuracies from the fixed 1077-image training set and the same 360-image validation set. Models shown: linear, tree, forest. The original final test set has no role in these comparisons. Linear model Single tree Forest 0 20 40 60 80 100 Accuracy (%) 99.8% 100.0% 100.0% 96.1% 83.9% 97.5% Training Validation

ModelTrain correctValidation correctValidation loss
Linear model1,075 / 1,077346 / 3600.115
Single tree1,077 / 1,077302 / 3605.807
Random forest1,077 / 1,077351 / 3600.331
All case-study numbers are computed from scikit-learn 1.8.0 load_digits. Fixed stratified split, random_state=8: 1077 training, 360 validation, 360 test. Each model is fitted only on training rows. Selection uses validation accuracy; ties prefer the linear model, then forest, then the single tree. The selected trained model is frozen without refitting before final test evaluation. The translation diagnostic is evaluated afterwards and does not change model selection. Mean validation cross-entropies are approximately 0.115, 5.807 and 0.331 for linear, tree and forest respectively.

Read the whole comparison

Validation measureLinear modelForest
Correct labels346 / 360351 / 360
Mean cross-entropy0.1150.331
Model structure10 linear class scores300 trees

The forest gets five more labels right here. The linear model has the lower probability loss.

Which result matters depends on the purpose of the predictions.

All case-study numbers are computed from scikit-learn 1.8.0 load_digits. Fixed stratified split, random_state=8: 1077 training, 360 validation, 360 test. Each model is fitted only on training rows. Selection uses validation accuracy; ties prefer the linear model, then forest, then the single tree. The selected trained model is frozen without refitting before final test evaluation. The translation diagnostic is evaluated afterwards and does not change model selection. The primary criterion was stated in advance as accuracy. A five-image validation difference is not proof that one family will be universally superior. Model-structure descriptions are not a timing or memory benchmark.

Freeze the choice

Selected model: Random forest. It has the highest validation accuracy among the three candidates.

The primary goal here is to return the correct digit label. If probability loss were the priority, the comparison would favour the linear model.

The trained forest and its choices are now fixed.

All case-study numbers are computed from scikit-learn 1.8.0 load_digits. Fixed stratified split, random_state=8: 1077 training, 360 validation, 360 test. Each model is fitted only on training rows. Selection uses validation accuracy; ties prefer the linear model, then forest, then the single tree. The selected trained model is frozen without refitting before final test evaluation. The translation diagnostic is evaluated afterwards and does not change model selection. The model is not refitted using validation rows in this example, so the frozen object is exactly the one evaluated in the preceding comparisons.

Open the final test set

Frozen forestResult
New test images360
Correct labels351 / 360
Accuracy97.5%
Mean cross-entropy0.357

These are different images from the validation set. The equal correct count is a coincidence.

All case-study numbers are computed from scikit-learn 1.8.0 load_digits. Fixed stratified split, random_state=8: 1077 training, 360 validation, 360 test. Each model is fitted only on training rows. Selection uses validation accuracy; ties prefer the linear model, then forest, then the single tree. The selected trained model is frozen without refitting before final test evaluation. The translation diagnostic is evaluated afterwards and does not change model selection. Test results were first obtained after choosing the model from validation. The validation and test index sets are disjoint; both happen to give 351 correct labels.

What has that test established?

The forest works well on held-out, prepared images from this collection.

A random image split does not establish performance on new writers, phone cameras or differently prepared crops.

The claim must stay within the scope of the evidence.

load_digits does not supply writer identifiers for this demonstration, so we have not evaluated an explicit held-out-writer split. The mailroom is an application scenario, not the source of the measured dataset.

A small deployment change

The same digit changes positionAn actual frozen-test example from the subset with a blank rightmost column. Moving all pixels one column right and zero-filling the first column preserves total ink. The chosen forest predicts the original as three and shifted as nine. The example is selected to illustrate a failure observed in the declared stress diagnostic; model selection remains unchanged.Original positionOne column rightWould the prediction stay the same?True digit: 3. The rightmost column was blank, so no ink was lost.

The same digit moves by one column. Should the chosen model’s answer stay the same?

One pixel changes many input coordinates

The same digit changes positionAn actual frozen-test example from the subset with a blank rightmost column. Moving all pixels one column right and zero-filling the first column preserves total ink. The chosen forest predicts the original as three and shifted as nine. The example is selected to illustrate a failure observed in the declared stress diagnostic; model selection remains unchanged.Original positionOne column rightPrediction: 3Prediction: 9True digit: 3. The rightmost column was blank, so no ink was lost.

The digit is still a 3. The fixed forest now predicts 9.

This one failure case is an actual frozen-test example. The full paired diagnostic on the next slide measures how widespread the effect is rather than inferring a population rate from one image.

Measure the change on matched inputs

Paired accuracy under a position changeThe same 325 frozen-test images before and after an ink-preserving one-column shift. Eligibility depends only on the rightmost pixel column being blank. Clean accuracy is 316/325, shifted accuracy 160/325. This diagnostic does not use different denominator sets or remove strokes and does not trigger any further fitting. Original position One-column shift 0 20 40 60 80 100 Accuracy (%) 316/325 97.2% 160/325 49.2%

The same 325 test images are scored before and after the shift. No digit strokes were removed.

All case-study numbers are computed from scikit-learn 1.8.0 load_digits. Fixed stratified split, random_state=8: 1077 training, 360 validation, 360 test. Each model is fitted only on training rows. Selection uses validation accuracy; ties prefer the linear model, then forest, then the single tree. The selected trained model is frozen without refitting before final test evaluation. The translation diagnostic is evaluated afterwards and does not change model selection. Only frozen-test images with a blank rightmost column are eligible. Eligibility is based on input pixels, not predictions or target labels. All 325 images retain their total ink after shifting. Clean is 316/325 (97.23%); shifted is 160/325 (49.23%). This is a diagnostic on a subset, not a second estimate on all 360 test images.

What should we investigate next?

The validation winner is sensitive to a small change in position.

Would adding more trees address the cause, or should we first investigate the inputs and how they are prepared?

A new hypothesis follows from the failure

  • Check how digit crops vary in the intended application.
  • Investigate consistent alignment or representative shifted training examples.
  • Evaluate the complete workflow again on a suitable held-out set.

These are proposed next experiments. They have not been demonstrated to fix the problem here.

A CNN or another representation could also be investigated if justified by the intended data and resources. The case study deliberately stops at three model families; no further models were trained using the diagnostic test results.

What did three experiments teach us?

ObservationWhat we learned here
Linear baseline: 346/360The prepared pixel coordinates already support a strong simple model.
Single tree: 302/360A perfect training fit can leave a much weaker validation fit.
Forest: 351/360Combining varied trees helps here, while accuracy and loss still disagree.

The position check then shows a weakness of this fitted forest on its raw pixel inputs.

The first and third interpretations are inferences from this particular comparison, not general rankings of model families. Only the selected forest underwent the reported shift diagnostic, so it does not establish a relative robustness ranking of all three methods.

A reusable engineering loop

An evidence-driven investigationAn investigation states a question, makes a controlled comparison, examines validation results and errors, and decides what to keep or investigate next. The final test evaluates a frozen choice rather than repeatedly choosing new settings.QuestionMotivated changeExperimentFair comparisonEvidenceScores and errorsDecisionNext actionThe next experiment should follow from what the last one showed.

Keep the question, the measured result and the next decision connected. An unsuccessful change can still teach you something useful.

Keep the whole prediction process

A whole machine-learning workflowRaw measurements pass through a representation and a model to make predictions. Training procedures differ across model families; this diagram does not assert that all methods use gradient descent.MeasurementsInput xRepresentationFeatures φ(x)ModelFit from examplesPredictionClass or numberEvaluate the complete prediction process on new examples.

For this frozen forest, a new input must supply the same 64 pixel coordinates in the same order and numerical convention.

The selected forest uses raw load_digits arrays. If another chosen workflow included a scaler or PCA, those fitted transformations would also need to be retained and reused. This statement does not add nonexistent preprocessing to the selected forest.

Today we covered

  • The course’s models share a need for a suitable representation and meaningful evaluation.
  • Training performance alone cannot choose the model.
  • A sequence of motivated experiments can improve predictions and expose limitations.
  • A good held-out score supports a specific claim about specific inputs.

Questions