• I'll collect last week's assignment at 2 pm today.
  • This week's assignment is now released (ROC curves today, non-linear models on thursday)
  • Summative assignment released on Friday (more details on thursday)

Last week’s Iris problem

Use petal length and petal width to distinguish versicolor from virginica.

A fitted line through overlapping Iris measurementsThe same 100 versicolor and virginica flowers and fitted boundary as in the reveal. The horizontal axis is petal length and the vertical axis is petal width. 1 2 3 4 5 6 7 Petal length (cm) 0.0 0.5 1.0 1.5 2.0 2.5 Petal width (cm) Versicolor (0) Virginica (1) Fitted boundary

Which points would this fitted line get wrong?

The boundary makes both kinds of mistake

A fitted line through overlapping Iris measurementsAll 100 versicolor and virginica observations and the threshold 0.5 line fitted on 60 of them. Rings mark six wrong decisions, with three observations from each true class on the wrong side. 1 2 3 4 5 6 7 Petal length (cm) 0.0 0.5 1.0 1.5 2.0 2.5 Petal width (cm) Versicolor (0) Virginica (1) Fitted boundary Misclassified flower

Some virginica fall on the versicolor side, and some versicolor fall on the virginica side. The petal measurements overlap.

A score becomes a probability

\[ z=w_1x_1+w_2x_2+b\qquad p=\sigma(z)=\frac{1}{1+e^{-z}} \]

A continuous probability mapA regularised illustrative logistic fit using 60 training flowers. Parallel contours show probabilities 0.1, 0.5 and 0.9 for virginica. 3.0 3.5 4.0 4.5 5.0 5.5 6.0 6.5 7.0 Petal length (cm) 1.0 1.2 1.4 1.6 1.8 2.0 2.2 2.4 2.6 Petal width (cm) p = 0.1 p = 0.5 p = 0.9 Versicolor (0) Virginica (1) 0.0 0.5 1.0 P(virginica)

The fitted score changes across the plot. The contour at \(p=0.5\) is the usual decision boundary.

Moving the cutoff moves the boundary

Changing the classification thresholdA regularised illustrative logistic fit using 60 training flowers. Grey and green boundaries use thresholds 0.5 and 0.8 for the same fitted probabilities. 3.0 3.5 4.0 4.5 5.0 5.5 6.0 6.5 7.0 Petal length (cm) 1.0 1.2 1.4 1.6 1.8 2.0 2.2 2.4 2.6 Petal width (cm) Versicolor (0) Virginica (1) Threshold 0.5 Threshold 0.8

A lower cutoff labels more flowers as virginica. The fitted weights and the individual probability estimates stay fixed.

Two mistakes can have different losses

Both flowers are virginica. At a 0.5 cutoff, both predictions below are errors.

Two wrong class decisions with different probabilitiesBoth flowers are virginica. Predicted probabilities 0.01 and 0.49 fall to the left of the 0.5 decision threshold, so both are classified as versicolor. 0.00 0.25 0.50 0.75 1.00 Estimated probability of virginica Predict versicolor Predict virginica Confident error p = 0.01 Marginal error p = 0.49

Which flower should have the greater loss, the one with \(p=0.49\) or \(p=0.01\)?

Cross-entropy penalises confident mistakes

\[ \ell_i=-\ln(p_{\mathrm{correct},i})\qquad J=\frac{1}{N}\sum_{i=1}^N\ell_i \]

Log loss as a function of the probability of the observed labelThe curve decreases from a large loss near probability zero to loss zero at probability one. The marked examples are probabilities 0.01, 0.49 and 0.99. 0.0 0.2 0.4 0.6 0.8 1.0 Probability assigned to the correct label 0 1 2 3 4 5 Loss

The probability of the correct label is 0.49 for one flower and 0.01 for the other. Their losses are about 0.71 and 4.61.

How the loss reaches the weights

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

Backpropagation multiplies slopes along the chain. For sigmoid and cross-entropy, the slope with respect to the score is \(p_i-y_i\).

\[ \frac{\partial J}{\partial w_j}=\frac{1}{N}\sum_{i=1}^N(p_i-y_i)x_{ij} \]

An update changes the predictions

Iris decision line after one updateThe dashed line is the original width-only boundary. The solid line after one update slopes down across the plot. The same circled virginica is now above the solid line. 1 2 3 4 5 6 7 Petal length (cm) 0.0 0.5 1.0 1.5 2.0 2.5 Petal width (cm) Versicolor (0) Virginica (1) New boundary Starting boundary

One step on the circled virginica raised its predicted probability from 0.450 to 0.530. That completes our recap of logistic regression.

Today we will cover

  • Loss curves and generalisation
  • ROC curves and decision thresholds
  • Support vector machines
  • Cross-validation

Loss curves

One loss landscape and its training pathThe left panel plots loss as a function of one weight and marks the weights visited by updates 0 to 4. The right panel plots the same five loss values against update number. 0.0 0.5 1.0 1.5 2.0 2.5 Weight w 0 1 2 3 Loss J 0 1 2 4 Loss landscape 0 1 2 3 4 Update number 0 1 2 3 Loss J 0 1 2 4 Loss along one run

The landscape gives loss at possible weights. The curve on the right records loss at the weights we visited.

Definitions

  • Step changes the weights once.
  • Epoch means one pass through the training data. It can contain many steps.
  • Checkpoint records the weights at a particular point in the run.

In the sensor example we will use one full-batch step per epoch.

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

Training loss falls from 0.40 to 0.20. Does the model now predict new examples better?

Fit the curve on the blue readings

Fit the sensor curve on training dataThe green curve is fitted on the filled blue 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 curve

The blue readings are the training data. Use them to fit the green curve.

Add the held-out readings

Score the same fit on validation dataThe green curve is fitted on the filled blue training readings. Open red markers show the additional validation readings used to score the same curve. −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

We kept the red readings aside during training. Score the same fitted curve on them to get the validation loss.

The hold-out loss tells us more

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

Both runs fit their training examples better. The hold-out curves tell us whether the improvement carries over to new examples.

Put some data aside before fitting

Three parts of the datasetTraining is used to fit the weights, validation to choose settings, and test for the final check.TrainingFit weightsValidationChoose settingsTestFinal check

Each split has a job. Training examples supply the gradients. Validation and test examples measure performance on data outside the fit.

How much data should we hold out?

Two illustrative splits for datasets of different sizesFor one thousand examples, allocate 60 percent to training, 20 to validation and 20 to test. For one million examples, allocate 98 percent to training, 1 to validation and 1 to test.1,000 examplesTraining 60%Validation 20%Test 20%1,000,000 examplesTraining 98%Validation 1%Test 1%

Which split leaves you with more examples to validate the model?

One per cent can be a large hold-out

Dataset sizeTrainingValidationTest
1,000600200200
1,000,000980,00010,00010,000

60/20/20 was a common rule of thumb for smaller datasets. At large scale, a 98/1/1 split can still leave many examples for validation and test.

Choose hold-out sizes that let you measure the performance differences you care about.

Which set makes each decision?

  • Which data tell us how to update the weights?
  • Which data tell us which checkpoint to keep?
  • Which data give a final estimate of performance?

Training, validation and test

SplitWhen we use itExample
TrainingDuring the fitCalculate the next gradient
ValidationWhile choosing settingsChoose a degree or stopping epoch
TestAfter making those choicesReport the final performance

Repeatedly choosing a model using the test set would make it another validation set.

Fit the response of a sensor

Noisy measurements from a simulated sensorThere are 26 filled blue training markers and 65 open orange validation markers across the same range of settings. −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 Validation readings

These simulated readings include measurement noise. Fit a flexible curve to the blue points and score it on the orange points.

Epoch 1

Sensor fit at epoch 1The graph shows the fit at epoch 1, over the same training and validation observations. The validation mean squared error is 0.146. −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 Validation readings Fitted curve

The fit is still taking shape. The orange readings are held out of every update.

Epoch 17

Sensor fit at epoch 17The graph shows the fit at epoch 17, over the same training and validation observations. The validation mean squared error is 0.061. −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 Validation readings Fitted curve

The fitted curve now follows more of the broad pattern in the readings.

Epoch 250

Sensor fit at epoch 250The graph shows the fit at epoch 250, over the same training and validation observations. The validation mean squared error is 0.107. −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 Validation readings Fitted curve

The curve follows more of the small swings between training readings. Look at where the orange readings fall relative to it.

The training loss keeps falling

Sensor loss over 250 epochsThe training loss falls. The horizontal axis uses a logarithmic scale to show early epochs. 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²) Training

The model family and training set stay fixed. Each epoch gives the same model another update.

Now reveal the validation loss

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

Both losses fall early. After epoch 17, the validation loss rises while the training loss keeps falling.

Which checkpoint would you keep?

EpochTraining MSEValidation MSE
10.1040.146
170.0100.061
2500.0070.107

You need to predict new readings. Take a moment to choose a checkpoint.

Keep the best validation checkpoint

EpochTraining MSEValidation MSE
10.1040.146
170.0100.061
2500.0070.107

Choose epoch 17 and save those weights. Once all settings are decided, the test set gives the final check.

Should we stop at the first rise?

Early stopping with noisy validation lossThe validation loss ticks up at epoch 5. 1 2 3 4 5 6 7 8 9 10 Epoch 0.100 0.125 0.150 0.175 0.200 0.225 0.250 Validation loss First increase

Validation loss often fluctuates. In this example, it rises at epoch 5. Would you stop training here?

Allow a few epochs for improvement

Early stopping with noisy validation lossThe validation loss ticks up at epoch 5. The best checkpoint is epoch 7. Training stops at epoch 10 after three further epochs without improvement. 1 2 3 4 5 6 7 8 9 10 Epoch 0.100 0.125 0.150 0.175 0.200 0.225 0.250 Validation loss Restore epoch 7 Stop at epoch 10

With a patience of three epochs, stop at epoch 10 and restore the best saved weights from epoch 7.

What if we change the model?

Keep the same readings. This time fit a separate polynomial for each degree.

A low degree gives few shapes to choose from. A high degree can follow more bends. What would you look for in the training and validation errors?

Degree 1 misses the bend

Sensor fit using a degree 1 polynomialThe fit uses the same training observations. Validation mean squared error is 0.148. −1.00 −0.75 −0.50 −0.25 0.00 0.25 0.50 0.75 1.00 Scaled sensor setting −0.5 0.0 0.5 1.0 1.5 Sensor output (V) Training readings Validation readings Degree 1 fit

Even the best straight line has substantial error on both splits. This model underfits the broad shape.

Degree 5 follows the signal

Sensor fit using a degree 5 polynomialThe fit uses the same training observations. Validation mean squared error is 0.031. −1.00 −0.75 −0.50 −0.25 0.00 0.25 0.50 0.75 1.00 Scaled sensor setting −0.5 0.0 0.5 1.0 1.5 Sensor output (V) Training readings Validation readings Degree 5 fit

This fit picks up the broad variation and reduces the loss on both splits.

Degree 8 follows finer detail

Sensor fit using a degree 8 polynomialThe fit uses the same training observations. Validation mean squared error is 0.063. −1.00 −0.75 −0.50 −0.25 0.00 0.25 0.50 0.75 1.00 Scaled sensor setting −0.5 0.0 0.5 1.0 1.5 Sensor output (V) Training readings Validation readings Degree 8 fit

The extra flexibility brings the training loss down. Validation loss rises, including near the sparsely sampled edge.

One point for each finished fit

Training and validation loss for nine polynomial degreesTraining error falls with degree. Validation error is lowest at degree 5 and rises for the most flexible models in this sweep. 1 2 3 4 5 6 7 8 9 Polynomial degree 0.000 0.025 0.050 0.075 0.100 0.125 0.150 0.175 Mean squared error (V²) Lowest validation loss Training Validation

The horizontal axis is model degree. In this sweep, degree 5 has the lowest validation loss.

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

Each thin line comes from a fresh sample of 20 readings from the same simulated sensor. Which model misses the signal in a consistent way? Which changes most with the sample?

Bias is a systematic miss

Bias across repeated fitsThe six degree-1 fits are compared at setting 0.86. Their mean prediction is 1.08 volts, with standard deviation 0.06 volts. The simulated signal is 0.66 volts. −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) Error in the mean Individual fits Simulated signal Mean of six fits

The mean of the straight-line fits sits above the true signal at the marked setting. A model that can bend gives the fit a way to follow the signal there.

Variance is sensitivity to the sample

Variance across repeated fitsThe six degree-12 fits are compared at setting 0.86. Their mean prediction is 0.64 volts, with standard deviation 0.19 volts. The simulated signal is 0.66 volts. −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) Spread among fits Individual fits Simulated signal Mean of six fits

At the same setting, the more flexible model gives quite different predictions when we fit it to different samples. More data or a less flexible model may make it more stable.

Bias, variance and test error

Fix the sensor setting \(x\). Let \(\hat f_D(x)\) be the prediction from training sample \(D\), and \(f(x)\) the true mean response.

\[ \bar f(x)=\mathbb{E}_D[\hat f_D(x)] \]

\[ \mathrm{Bias}(x)=\bar f(x)-f(x)\qquad \mathrm{Var}_D[\hat f_D(x)]=\mathbb{E}_D[(\hat f_D(x)-\bar f(x))^2] \]

Average the squared error over training samples and independent new readings at this setting.

\[ \mathrm{MSE}(x)=\mathrm{Bias}(x)^2+\mathrm{Var}_D[\hat f_D(x)]+\mathrm{Var}(Y\mid X=x) \]

The last term is measurement noise. The next slide reports standard deviation, the square root of variance.

Compare the fits at one sensor setting

At the marked setting (0.86), the true signal is 0.657 V.

ModelMean predictionMean minus signalSD across six fits
Degree 11.076 V+0.419 V0.058 V
Degree 120.645 V-0.012 V0.185 V

The straight line has a bigger systematic miss here. The flexible curve has more spread. Both contribute to prediction error.

Reading loss curves in practice

If both losses stay high

Both losses remain highBoth losses remain high 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 Reference loss

If both losses stay high

Both losses remain highBoth losses remain high 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 Reference loss

Then ask what counts as high. Compare with an attainable loss on the same task. If training has converged and a better fit is possible, change the model or its inputs.

If training loss barely falls or rises

Three learning rates on one simple loss landscapeVery small steps make slow progress, a useful step reaches a low loss, and overshooting raises the loss. 0 2 4 6 8 10 12 Update number 0.0 0.5 1.0 1.5 2.0 Training loss Very small step Useful step Overshoots

If training loss barely falls or rises

Three learning rates on one simple loss landscapeVery small steps make slow progress, a useful step reaches a low loss, and overshooting raises the loss. 0 2 4 6 8 10 12 Update number 0.0 0.5 1.0 1.5 2.0 Training loss Very small step Useful step Overshoots

Then check the learning rate. Try a larger step if progress is very slow. Try a smaller step if updates overshoot.

If the validation gap persists

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

If the validation gap persists

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

Then check for overfitting. Try an earlier checkpoint, a simpler fit or more training data. Compare validation loss on the same examples.

If validation loss is lower

Validation loss is below training lossValidation loss is below training loss 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

If validation loss is lower

Validation loss is below training lossValidation loss is below training loss 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

Then check how you measured both losses. Use the same loss and prediction settings. A validation sample can also be easier by chance.

Would more training readings help?

Learning curve across training sample sizesA degree-nine model is refitted on fifty simulated training samples at each size. Validation loss decreases and the training-validation gap narrows as the number of readings grows. 20 30 45 70 105 180 Number of training readings 0.01 0.02 0.03 0.04 0.05 0.06 Mean squared error (V²) Training Validation

Would more training readings help?

Learning curve across training sample sizesA degree-nine model is refitted on fifty simulated training samples at each size. Validation loss decreases and the training-validation gap narrows as the number of readings grows. 20 30 45 70 105 180 Number of training readings 0.01 0.02 0.03 0.04 0.05 0.06 Mean squared error (V²) Training Validation

If validation loss keeps falling as the sample grows, collecting more readings may help. Each point here refits the same model family with a different amount of data.

A boundary that fits every training part

Flexible and smoother classifiers for simulated partsModel 1 and Model 2 are shown on the same axes. The 72 parts used to fit both models are shown. Model 1 follows a more irregular boundary, and Model 2 uses one straight line. −3 0 3 Texture contrast −3 0 3 Edge strength Model 1 −3 0 3 Texture contrast Model 2 Clear Defect

Model 1 fits every training label. Model 2 draws a clean straight line. Which boundary would you trust on new parts?

Show the same boundaries on new parts

Flexible and smoother classifiers for simulated partsModel 1 and Model 2 are shown on the same axes. One hundred new parts are shown. Rings highlight four defects in a separate pocket. Model 1 catches all four, while Model 2 misses them. −3 0 3 Texture contrast −3 0 3 Edge strength Model 1 −3 0 3 Texture contrast Model 2 Clear Defect

Model 1 got 92 of 100 correct. Model 2 got 85. Model 1 catches the ringed pocket of defects. Its complex boundary captures a real feature of the simulation.

ROC curves

How do the decisions change when we move the cutoff?

From a score to an inspection decision

A camera system scores each manufactured part for possible surface defects. A flagged part goes to a person for a closer look.

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

These twelve example scores come with actual labels from inspection. Higher scores indicate stronger evidence of a defect.

Flag every score of 0.55 or higher

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

How many of the flagged parts are defective? How many defects did we miss?

Read the four counts

Actual conditionFlaggedLeft alone
Defective4 true positives2 false negatives
Clear2 false positives4 true negatives

A false positive uses a review slot. A false negative lets a defective part pass.

Raise the cutoff to 0.80

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.80, 2 defects and 0 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.80 Flag for review

Two defects are caught and no clear parts are flagged. Four defects pass.

Lower the cutoff to 0.40

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.40, 5 defects and 3 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.40 Flag for review

Five defects are caught and three clear parts are flagged. One defect passes.

Use a rate for each actual class

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

At cutoff 0.55 we catch 4 of the 6 defects, and flag 2 of the 6 clear parts.

TPR is the fraction of actual defects caught. FPR is the fraction of actual clear parts flagged.

One cutoff gives one point

Receiver operating characteristicAt cutoff 0.55 the point is at false positive rate 2/6 and true positive rate 4/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.55

Plot FPR = 2/6 on the horizontal axis and TPR = 4/6 on the vertical axis.

Add the other cutoffs

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

Lowering the cutoff sends more parts to review. Each threshold gives its own trade-off.

Sweep through all the scores

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

The receiver operating characteristic (ROC) curve traces the cutoff points. Each newly flagged defect moves it up. Each newly flagged clear part moves it right.

Area under the ROC curve

Receiver operating characteristicThe shaded area below the ROC curve is 0.778. 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) AUC = 0.778 Chance ranking Inspection model

The area summarises the ranking across cutoffs. An ideal ordering has area 1. A chance ranking has expected area 0.5.

When two ROC curves cross

Receiver operating characteristicModel A catches more at zero false positive rate. Model B can catch all defects at false positive rate two sixths, an operating point where A catches five sixths. 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) Chance ranking Inspection model A Inspection model B

A catches more defects when no false alerts are allowed. At FPR = 2/6, B can catch all six. The useful part of the curve depends on the inspection policy.

You have six review slots

CutoffDefects caughtClear parts flaggedTotal reviews
0.80202
0.55426
0.40538

Which of these cutoffs catches the most defects within the six-slot limit?

Choose a cutoff for the constraint

0.55 catches four defects and fills six review slots. At 0.40 the system would ask for eight reviews.

Use validation data to choose the cutoff. Evaluate the chosen rule on new parts.

What if defects are rare?

Suppose a cutoff catches 80% of defects and flags 2% of clear parts. In this example 100 out of 10,000 parts are defective.

Actual conditionPartsFlagged
Defective10080
Clear9,900198

Most flagged parts are clear. The false positive rate acts on a much larger group.

Use precision when flags matter

\[ \mathrm{Precision}=\frac{\mathrm{TP}}{\mathrm{TP}+\mathrm{FP}}=\frac{80}{278}\approx 29\% \]

\[ \mathrm{Recall}=\frac{\mathrm{TP}}{\mathrm{TP}+\mathrm{FN}}=\frac{80}{100}=80\% \]

Precision asks how many flags were useful. Recall asks how many defects were caught.

Precision–recall curves

Precision and recall for the same score pattern at two prevalencesEach dot is a threshold with at least one flagged part. The within-class threshold rates are identical in the two examples. In the one-percent case, precision drops sharply as soon as false alerts appear. 0.0 0.2 0.4 0.6 0.8 1.0 Recall (fraction of defects caught) 0.0 0.2 0.4 0.6 0.8 1.0 Precision (fraction of flags that are defects) 50% defects 1% defects

Here we hold the score pattern within each class fixed. At 1% prevalence, the same ROC trade-off can give much lower precision.

Support vector machines

A line between the classes

Linear SVM geometryThe synthetic clear parts and defective parts can be separated by a straight line. −3 0 3 Texture contrast −3 0 3 Edge strength Clear Defect

Two measurements describe each part. Where would you draw a line to split the two groups?

Two lines make the same decisions

Linear SVM geometryTwo parallel lines separate all the points. Line A runs through the middle of the gap, and line B is nearer the defects. −3 0 3 Texture contrast −3 0 3 Edge strength Clear Defect Line A Line B

A and B both get every label right. Which leaves more room before the nearest point crosses the line?

Many more do

Linear SVM geometrySix lines of different slopes separate every clear part from every defective part. −3 0 3 Texture contrast −3 0 3 Edge strength Clear Defect

We can tilt the line and still separate the groups. Which line leaves the most room on both sides?

Find the widest empty strip

Linear SVM geometryAn empty strip of width 1.2 units runs between the closest points of the two classes. −3 0 3 Texture contrast −3 0 3 Edge strength Clear Defect Decision boundary

A hard-margin SVM puts the boundary in the middle of the widest strip it can fit between the classes.

Which points define the strip?

Linear SVM geometryThe three circled points touch the edges of the margin and are the support vectors for this fit. −3 0 3 Texture contrast −3 0 3 Edge strength Clear Defect Decision boundary

The ringed points are the support vectors. They set the edges of the strip. Moving a point far from the strip can leave the line where it is.

Put numbers on the strip

Linear SVM geometryThe central line is score 0. The dashed margins are scores minus 1 and plus 1. The arrow spans the strip perpendicular to all three lines. −3 0 3 Texture contrast −3 0 3 Edge strength Clear Defect Decision boundary z = +1 z = 0 z = −1

\[ z=\mathbf{w}^{\mathsf{T}}\mathbf{x}+b \]

The decision boundary is at score 0. We scale the score so the two edges are at −1 and +1.

Fit a linear SVM in Python

Use the two part measurements as features and clear or defect as labels.

from sklearn.svm import SVC

model = SVC(kernel="linear")
model.fit(X_train, y_train)
y_pred = model.predict(X_new)

You can use an algorithm without deriving it. Focus on when it suits the data and how to check its predictions on new examples.

Now introduce three awkward points

Linear SVM geometryThree added defects enter the original margin or cross its boundary. −3 0 3 Texture contrast −3 0 3 Edge strength Clear Defect Decision boundary

One new defective part sits among the clear parts. Where could you put a straight line that gets everything right?

Allow a soft margin

Linear SVM geometryThe soft-margin fit permits parts inside the shaded band and permits classification errors. −3 0 3 Texture contrast −3 0 3 Edge strength Clear Defect Decision boundary

The soft-margin SVM balances a wide strip with penalties for violating it. Points may lie inside the strip or across the line.

Two kinds of margin violation

Linear SVM geometryThe circled defect A is correctly classified but inside the band. The circled defect B is on the wrong side of the line. −3 0 3 Texture contrast −3 0 3 Edge strength Clear Defect Decision boundary B A

Both ringed parts are defects. A is on the correct side of the boundary but inside the strip. B is on the wrong side.

A fitted soft-margin boundary

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

Hinge loss makes the penalty visible

Hinge loss for the signed marginThe hinge loss is one minus the signed margin below one, and zero at or above one. Point A has margin 0.27 and point B has margin -0.93. −1 0 1 2 Signed margin m = yz 0.0 0.5 1.0 1.5 2.0 2.5 Hinge loss B A Zero loss at or beyond the margin

\[ \ell=\max(0,1-yz) \]

A has \(yz=0.27\) and loss \(0.73\). B is across the boundary and pays a loss of \(1.93\).

What is the model trying to balance?

\[ J(\mathbf{w},b)=\frac{1}{2}\|\mathbf{w}\|^2+C\sum_{i=1}^{N}\max(0,1-y_i z_i) \]

  • A smaller weight norm widens the strip.
  • A smaller hinge loss reduces the margin violations.

The model minimises the sum. \(C\) sets how much the violations count.

How much should violations cost?

Two soft-margin SVMs fit to the same pointsThe smaller C fit has a wider margin. The larger C fit has a narrower margin and a shifted boundary. Both misclassify one point. −3 0 3 Texture contrast −3 0 3 Edge strength Smaller C = 0.12 −3 0 3 Texture contrast Larger C = 8 Clear Defect

A larger \(C\) increases the penalty for violations. Here it shifts the line and narrows the strip.

Both fits miss one defect

FitMargin widthWrong labelsTotal hinge loss
Smaller C2.4115.23
Larger C1.0613.56

The geometry and the severity of violations change even when the number of wrong labels stays the same.

Cross-validation

When your dataset is small, a single validation score can depend heavily on which examples land in that split.

Set aside the final test set and divide the remaining development data into five folds.

One split can change which setting wins

Held-out foldSetting A · AUCSetting B · AUC
10.860.91
20.760.65

Setting B looks better on the first fold. A looks better on the second. How could we use the available data to compare them?

Fit once and score one fold

Five-fold cross-validationA fresh model trains on four folds and scores the omitted fold. In the first run the scored fold is fold one.Fold 1Fold 2Fold 3Fold 4Fold 5Fit 1ScoreTrainTrainTrainTrainTest held out

Start a fresh model. Fit it on folds 2 to 5, then score it on fold 1.

Take turns holding out each 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 row fits a new model. By the end, every development example has been scored once by a model fitted without that example.

How many fits do we make?

Imagine 1,000 examples for development and another 200 set aside for the final test.

  • Each fold contains 200 development examples.
  • Each fit trains on 800 and validates on the remaining 200.
  • Five-fold cross-validation requires five fits per setting. Comparing two settings takes ten fits.

The final 200 test examples stay outside these fits.

Compare settings on the same folds

SettingFold 1Fold 2Fold 3Fold 4Fold 5Mean AUC
A0.860.760.900.800.880.84
B0.910.650.890.720.930.82

A has the higher mean in this illustrative example. Look at the variation across folds before treating a small difference as decisive.

Fit preprocessing inside each fold

Suppose the SVM uses standardised features.

Part of the splitWhat to do
Training foldsLearn the means and standard deviations. Transform those inputs and fit the SVM.
Held-out foldTransform with the training means and standard deviations. Score the fitted model.

Learning the scaling from all the data would let the held-out fold influence the fit.

Choose folds for the data you have

DataSplit to use
Independent examples with rare positivesStratify to keep similar class proportions.
Several images of the same partGroup by part so all its images are in one fold.
Measurements in time orderTrain on earlier observations and validate on later ones.

Refit, then use the test set

  • Choose the settings using the validation results.
  • Fit the chosen model and its preprocessing on all the development data.
  • Use the test set for the final estimate of performance.

Today we have covered

  • Loss curves to see how well a model generalises as we train.
  • ROC curves to read the trade-offs as a cutoff moves.
  • Support vector machines to choose a boundary using margins.
  • Cross-validation to compare settings across several splits.
AI: Safety and Alignment with Dr Will Yeadon. Tuesday 17 November 2026, 7–8 pm, Penthouse Rooms, Collingwood College. Networking reception from 8 pm. Free for all Collingwood students. No previous knowledge or sign-up needed.