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.

The assignment uses a physics setting

One event becomes a row of measurementsA symbolic collision event is represented by several numerical input columns and a binary target. No assessment values or feature relationships are shown.One recorded eventA row of measured numbersAx₁Bx₂Cx₃……Label0 or 1The model receives the numbers.

The assessment is about machine learning. One row describes one recorded event, and the columns are numerical measurements.

The names provide context. You can reason about the ML task as inputs A, B, C, … and a label.

The supplied dataset is synthetic and simplified. These slides explain the published variable glossary only. No physical formulas, process signatures, expected feature usefulness, data distributions or model recommendations are needed.

Particles and transverse momentum

Transverse momentum and measured objectsLeft: transverse momentum is the component perpendicular to the beam. Right: a charged lepton and a jet are schematic reconstructed objects seen along the beam direction. No physical thresholds or class relationships are implied.Side viewLooking along the beamBeam directionpTParticleLeptonJet: a spray of particles

Name in the notebookPlain meaning
lepton_ptSideways momentum of a charged lepton, such as an electron or muon.
jet1_pt, jet2_ptSideways momenta of the two leading jets: reconstructed sprays of particles.
Transverse means perpendicular to the beam. Leading jets are ordered by transverse momentum. These definitions provide terminology and imply no expected relationship with the assessment labels. ATLAS Open Data glossary.

Missing transverse energy

Missing transverse momentum is an imbalanceTwo schematic views along the beam. In the first, three transverse momentum vectors sum to zero. In the second, two observed vectors imply a missing vector that would close the balance. This explains terminology, not any relationship with the assessment target.Balanced visible momentaVisible momenta do not balanceDashed arrow: inferred imbalance

missing_et summarises an imbalance in the measured transverse momenta.

It is one reconstructed number describing the event.

The common missing-energy terminology refers here to the magnitude of missing transverse momentum, reconstructed from the negative vector sum of measured transverse momenta. Invisible particles and measurement effects can both contribute. No interpretation of signal versus background is implied. ATLAS explanation of missing momentum.

Mass and angles

Angles and a mass of a pairA transverse angular separation compares two directions. The invariant mass of a lepton pair summarises their combined energy and momentum. No mass formula, resonances, thresholds or assessment values are supplied.ΔφLepton 1Lepton 2Angle in the transverse planeTwo leptons togetherCombined energy and momentumPair mass: one numerical summary

Name in the notebookPlain meaning
dilepton_massMass calculated for two leptons considered together.
delta_phi_llAngle between the two lepton directions, viewed along the beam.
delta_phi_lep_metAngle between a lepton and the missing-momentum direction.
Invariant pair mass combines the particles’ reconstructed energies and momenta. No calculation is required here. Delta denotes a difference and phi an angle around the beam. The sketch supplies no physical scales or class signatures. ATLAS Open Data glossary.

Measurements and labels

RoleIn the supplied notebook
Inputs XThe numerical columns selected by detector_features.
Target ysignal: 1 for the named process of interest, 0 for background.

Use the supplied information and the evidence in your investigation. No additional physics knowledge is required.

This repeats the assessment’s input/target distinction. It adds no feature-selection advice or expected model behaviour.

Recap

Forward pass

The prediction and training calculationInputs pass through the model to predictions and a loss. On the backward version the chain rule carries loss gradients to parameters, and the optimiser subsequently changes the parameters.InputsMeasurementsNetworkWeights θPredictionProbabilitiesLossObserved labelForward pass: calculate a prediction, then its loss.

Use the current weights to calculate the output. With a target, we can also calculate a loss.

Backward pass and weight update

The prediction and training calculationInputs pass through the model to predictions and a loss. On the backward version the chain rule carries loss gradients to parameters, and the optimiser subsequently changes the parameters.InputsMeasurementsNetworkWeights θPredictionProbabilitiesLossObserved labelBackward pass: gradients of the lossThe optimiser then updates the weights.

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

The chain rule gives gradients. The optimiser uses those gradients to change the weights.

CNN Kernels

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.

\[ 0+0+1+0+0+1+0+0+1=3 \]

One patch gives one response. The same kernel weights are reused at the next location.

A three by three patch with identical rows (0,0,1) is multiplied entry by entry by the three by three kernel with rows (−1,0,1). The bias is zero. The following slide shows the completed feature map from the same explanatory kernel.

CNN Kernels

A filter moves over an imageA five by five input is scanned with a three by three vertical-edge filter. Multiply corresponding numbers and add them. The valid feature map is three by three with rows 3, 3, 0.Input pixels0011100111001110011100111Filter weights-101-101-101Feature map330330330Use the same nine weights at every position.

Multiply matching entries and add. Slide the same weights across the image.

Convolution and parameter sharing.

Class probabilities and cross-entropy

\[ p_k=\frac{e^{z_k}}{\sum_j e^{z_j}},\qquad\ell=-\sum_k y_k\ln p_k \]

Observed labelPredicted probabilityLoss
Correct class0.8−ln(0.8) ≈ 0.22
Correct class0.1−ln(0.1) ≈ 2.30

The loss penalises assigning little probability to the observed class.

Pretrained models

Using a pretrained image modelAn image enters a feature extractor whose weights have already been trained. The original output head predicts the classes it was trained to recognise. Reuse works best when the new inputs are sufficiently related to the pretraining task.New imagePixel valuesPretrained modelLearned visual featuresExisting classesOriginal output headThe weights have already learned from many training images.

You can download an image model whose weights have already been trained.

For related image-recognition tasks, this can get you much of the way towards a useful model.

The weights encode learned visual features, not just an architecture description. Use the preprocessing expected by those weights. Performance depends on how well the new task and inputs match what was learned. https://docs.pytorch.org/tutorials/beginner/transfer_learning_tutorial.html

Pretrained models

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.

Reuse the feature extractor and fit a small new output head for your labels. You can also fine-tune some of the existing weights.

You still need suitable examples and an evaluation on new data.

A common transfer-learning baseline freezes a pretrained feature extractor and fits a new classification head. Fine-tuning can adapt the existing features. This does not guarantee that every image task is solved by replacing the head. https://docs.pytorch.org/tutorials/beginner/transfer_learning_tutorial.html

Dimensionality, PCA and nearest neighbours

Today we will cover

  • Why more input dimensions can make learning harder.
  • How PCA constructs a smaller set of coordinates.
  • How nearest neighbours use those coordinates to predict.
  • Keeping the complete prediction workflow together.

One input column is one dimension

ExampleDimensions for each example
Two Iris measurements2: petal length and petal width
All four Iris measurements4
An 8 × 8 grayscale image64: one brightness value per pixel
A hidden representationOne coordinate per hidden-unit output

More columns give us more ways for two examples to differ.

The same data must cover a larger space

The same fifty points occupy more spaceFifty uniformly sampled points are shown in one, two and three dimensions. Dividing each coordinate into five bins creates 5, 25 and 125 possible cells. This is an illustrative independent-uniform example. 0.0 0.2 0.4 0.6 0.8 1.0 x₁ 1 input: 5 bins 0.0 0.2 0.4 0.6 0.8 1.0 x₁ 0.0 0.2 0.4 0.6 0.8 1.0 x₂ 2 inputs: 25 bins 0 1 x₁ 0 1 x₂ 0 1 x₃ 3 inputs: 125 bins

There are 50 examples in every panel. Divide each input range into five bins. What happens to the number of possible cells?

The number of cells multiplies

\[ \mathrm{Number\ of\ cells}=5^d \]

Input dimensions dCellsExamples per cell, on average
1510
2252
31250.4
109,765,625About 0.000005

Keeping comparable coverage can require far more data. This is one aspect of the curse of dimensionality.

Illustrative uniform occupancy, not a universal sample-complexity law. Real data can be concentrated in a much smaller structured part of the available space.

What counts as a local neighbourhood?

Adding a condition shrinks the included regionThe same fifty uniform examples and axes in both views. The highlighted interval is 0.3 to 0.7 on the first input, with all second-input values included. 19 actual plotted examples satisfy the shown conditions. The theoretical uniform fractions are forty and sixteen percent; finite counts need not equal their expectations. 0.0 0.2 0.4 0.6 0.8 1.0 Input x₁ 0.0 0.2 0.4 0.6 0.8 1.0 Input x₂ Restrict x₁ only

Keep examples with 0.3 ≤ x₁ ≤ 0.7. The second input can have any value.

The highlighted strip contains 19 of these 50 points.

The same fifty uniform examples as the preceding dimensionality plots. A width of 0.4 on the first coordinate has an expected uniform fraction 40%. The actual finite sample contains nineteen examples.

Adding a second condition

Adding a condition shrinks the included regionThe same fifty uniform examples and axes in both views. The highlighted interval is 0.3 to 0.7 on the first input and on the second input. 8 actual plotted examples satisfy the shown conditions. The theoretical uniform fractions are forty and sixteen percent; finite counts need not equal their expectations. 0.0 0.2 0.4 0.6 0.8 1.0 Input x₁ 0.0 0.2 0.4 0.6 0.8 1.0 Input x₂ Restrict x₁ and x₂

Now also require 0.3 ≤ x₂ ≤ 0.7. Only 8 of the 50 points remain inside the box.

\[ \mathrm{Fraction\ of\ area}=0.4\times0.4=0.16 \]

The same points, axes and interval widths as the preceding slide. Eight of the fifty plotted examples meet both conditions. For independent uniform coordinates the expected fraction is sixteen percent. A third width-0.4 condition would retain fraction 0.4³ = 6.4%. This is a volume illustration, not a universal data-density claim.

Distance combines differences across inputs

Distances from one input to three reference pointsNew input Q is zero, zero. Reference A is three, four; B one, one; and C six, zero. The same units and equal coordinate weights are used throughout. Dashed lines connect Q to each reference; a right triangle marks A’s coordinate differences of three and four. 0 1 2 3 4 5 6 7 Input x₁ 0 1 2 3 4 5 Input x₂ A = (3, 4) B = (1, 1) C = (6, 0) Difference: 3 4 New input Q = (0, 0)

\[ d(x,x^{\prime})=\sqrt{\sum_j(x_j-x_j^{\prime})^2} \]

Which reference point is closest to the new input Q?

One distance by hand

Distances from one input to three reference pointsNew input Q is zero, zero. Reference A is three, four; B one, one; and C six, zero. The same units and equal coordinate weights are used throughout. Dashed lines connect Q to each reference; a right triangle marks A’s coordinate differences of three and four. 0 1 2 3 4 5 6 7 Input x₁ 0 1 2 3 4 5 Input x₂ A = (3, 4) B = (1, 1) C = (6, 0) Difference: 3 4 New input Q = (0, 0)

\[ d(Q,A)=\sqrt{(3-0)^2+(4-0)^2}=5 \]

The differences in the two inputs are 3 and 4. Square them, add them, then take the square root.

Compare the three distances

ReferenceCoordinatesDistance from Q
A(3, 4)√(9 + 16) = 5
B(1, 1)√(1 + 1) ≈ 1.41
C(6, 0)√(36 + 0) = 6

B is nearest in this two-input representation.

An extra input can change the neighbour

Add a third measurement, and let Q = (0, 0, 0).

ReferenceThree inputsDistance from Q
A(3, 4, 0)√(9 + 16 + 0) = 5
B(1, 1, 8)√(1 + 1 + 64) ≈ 8.12

A is now closer. Every input contributes, even if the extra measurement is unhelpful for the task.

An illustrative change of representation with equal numerical coordinate weights. No claim about an assessment feature is implied. The point is that a distance rule includes every selected coordinate regardless of whether it predicts the target.

Everyone starts to look like a neighbour

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

With many inputs, the nearest example can be only slightly closer than a typical example.

Illustrative independent uniform inputs. Distances are ranked from one query to ninety references, and divided by the mean. In this draw nearest/mean is about 0.11 for two inputs and 0.90 for one hundred inputs. The statement describes weakened relative contrast, not a literal assertion that every example is among all k nearest neighbours.

Relative distances can bunch together

Relative distances concentrate in this exampleDistances between 16000 independent pairs of uniformly distributed points in each of dimensions two, ten and one hundred. Distances are divided by square root of dimension so their relative spread can be compared. This example does not assert that every high-dimensional dataset behaves identically. 0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 Euclidean distance divided by √d 0.0 2.5 5.0 7.5 10.0 12.5 15.0 Density 2 inputs 10 inputs 100 inputs

In this example, distances become more alike relative to their typical size as we add inputs.

Independent uniform coordinates, 16000 pairs per curve. Euclidean distance is divided by sqrt(d). This is relative concentration, not a claim that raw distances shrink or that all structured high-dimensional data behave identically.

Principal component analysis

Two sensors in one laboratory

Two sensors in one laboratoryA schematic laboratory places sensor A and sensor B on opposite sides. Both record temperature at the same observation times. They share a large change in room conditions and can also differ slightly.A laboratory with two temperature sensorsSensor ASensor BThe room warms and cools.Record A and B at the same moment, repeatedly.

Imagine measuring the same laboratory with sensor A on one side and sensor B on the other.

How much of their change might they share?

Two sensors often move together

Two sensors often move togetherEighty synthetic paired sensor readings share a large common variation and a smaller difference. The example is constructed to give covariance eigenvalues 1.92 and 0.08 after centring and dividing each reading by two. 15.0 17.5 20.0 22.5 25.0 Sensor A (°C) 14 16 18 20 22 24 26 Sensor B (°C)

Two temperature sensors measure the same changing conditions. Could we summarise much of their variation with one number?

This is the idea of PCA

The idea of PCA in the sensor exampleTwo correlated temperatures are represented largely by one shared coordinate. This schematic describes a reduced representation of their variation, not a new supervised target or an assertion that all differences disappear.Two sensorsTwo measurementsShared temperatureOne main coordinatePCA finds directions that retain the most variation.

Replace several correlated readings with fewer coordinates that retain most of their variation.

Here one main coordinate describes the laboratory warming or cooling.

Centre the cloud

Centring moves the cloud to the originThe same sensor readings appear before and after subtracting their separate training means. Centring changes the origin without changing distances, units or the shape of the cloud. 15.0 17.5 20.0 22.5 25.0 Sensor A (°C) 14 16 18 20 22 24 26 Sensor B (°C) Original readings −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) Subtract each sensor’s mean

\[ x_{ij}^{c}=x_{ij}-\mu_j \]

Subtract the training mean of each input. The origin now represents an average reading.

Choose a direction to keep

Several directions through the same temperature dataThe same eighty centred sensor measurements are shown in degrees Celsius. Four possible projection directions, at zero, twenty, forty-five and seventy degrees, can be compared. No standardisation or change of units is applied in these projection figures. −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° 20° 45° 70°

We will project the same temperature readings onto several directions. Which direction preserves the most spread?

Variance measures the squared spread

Variance as squared distances from a meanAn illustrative four-value example uses minus three, minus one, one and three, with mean zero. Their squared deviations are nine, one, one and nine. This introduces the sample-variance calculation and is separate from the eighty sensor observations.-39-111139Four projected values, with mean 0Squared distances from the mean: 9, 1, 1, 9

\[ V=\frac{(-3)^2+(-1)^2+1^2+3^2}{4-1}=\frac{20}{3}\approx6.67 \]

This four-value example has mean zero. Variance summarises the squared distances from that mean.

Sample variance uses denominator N−1. This mini-example introduces the calculation before returning to the eighty sensor observations. The subsequent sensor plots use the same centred Celsius units, without an unannounced rescaling.

Project onto the horizontal direction

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°

\[ V_{0^\circ}=\frac{316.00}{79}\approx4.00 \]

There are 80 readings. Add their squared projected values and divide by 79.

The displayed squared-score total and variance are calculated from the same eighty sensor observations, in centred Celsius units. A unit projection direction is used. The variance divides by N−1 = 79. This gives 316.000000000000/79 = 4.000000000000.

Try a 20° direction

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°

\[ V_{20^\circ}=\frac{502.87}{79}\approx6.37 \]

The points spread further along this direction. The projected variance is larger.

The displayed squared-score total and variance are calculated from the same eighty sensor observations, in centred Celsius units. A unit projection direction is used. The variance divides by N−1 = 79. This gives 502.871213888071/79 = 6.365458403646.

Try a 70° direction

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°

\[ V_{70^\circ}=\frac{502.87}{79}\approx6.37 \]

This direction gives the same variance as 20° for this symmetric sensor example.

The displayed squared-score total and variance are calculated from the same eighty sensor observations, in centred Celsius units. A unit projection direction is used. The variance divides by N−1 = 79. This gives 502.871213888071/79 = 6.365458403646.

Project along the cloud

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°

\[ V_{45^\circ}=\frac{606.72}{79}\approx7.68 \]

This direction preserves more of the temperature variation than the alternatives we tried.

The displayed squared-score total and variance are calculated from the same eighty sensor observations, in centred Celsius units. A unit projection direction is used. The variance divides by N−1 = 79. This gives 606.720000000000/79 = 7.680000000000.

The first principal component

The first component maximises projected varianceFor this sensor cloud the sample covariance has diagonal entries four and off-diagonal entries 3.68. Projected variance is four plus 3.68 times sine of twice the angle, maximised at forty-five degrees with variance 7.68. The displayed curve is computed from the same observations as the projection figures. 0 20 45 70 90 135 180 Projection direction (degrees) 0 2 4 6 8 Projected variance (°C²) PC1: 7.68

PC1 is the direction with the largest projected variance. Here it is 45°, with variance 7.68.

The plotted variance curve is calculated from the same eighty centred temperature observations as the preceding projections. The aim is conceptual understanding of a maximum-variance direction; no covariance-matrix or eigenvector calculation is needed.

What variation remains after PC1?

Projected temperature readingsThe same eighty centred sensor measurements are projected onto a unit direction at 135 degrees. Squared projected scores sum to 25.28000000; dividing by seventy-nine gives sample variance 0.32000000. 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) 135°

PC1 describes the sensors warming and cooling together. What is left when the sensors differ?

The second component (PC2)

Projected temperature readingsThe same eighty centred sensor measurements are projected onto a unit direction at 135 degrees. Squared projected scores sum to 25.28000000; dividing by seventy-nine gives sample variance 0.32000000. 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) 135°

\[ V_{135^\circ}=\frac{25.28}{79}\approx0.32 \]

With two inputs, one perpendicular direction remains. PC2 describes the smaller differences between A and B.

The displayed squared-score total and variance are calculated from the same eighty sensor observations, in centred Celsius units. A unit projection direction is used. The variance divides by N−1 = 79. This gives 25.280000000000/79 = 0.320000000000.

Rotate before dropping a coordinate

Both coordinates retain all the original informationA full orthonormal rotation of the same eighty centred temperature readings. PC1 has sample variance 7.68 and PC2 0.32, in squared Celsius units. PC1 describes shared warmth; PC2 describes sensor differences. Both together permit exact reconstruction. −5 0 5 A minus its mean (°C) −6 −4 −2 0 2 4 6 B minus its mean (°C) Original centred readings −10 −5 0 5 10 PC1 temperature coordinate −10.0 −7.5 −5.0 −2.5 0.0 2.5 5.0 7.5 10.0 PC2 difference coordinate Both principal coordinates

PC1 captures shared warmth. PC2 captures sensor differences. Keeping both preserves all the original variation.

The same centred Celsius observations are rotated into an orthonormal basis. PC1 variance is 7.68 and PC2 variance 0.32. A full rotation changes coordinates without losing information. These scores are uncorrelated on the training data, which need not mean independent.

Dropping a component loses some information

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°

PC1 alone retains 96% of the variation in the two temperature readings. We mainly lose the small A–B differences.

This is retained input variance, not a prediction R² or a guarantee about a supervised target. The stored training means are retained for reconstruction.

One coordinate still tracks the room

One coordinate still describes the room’s warmthThe original paired reading is A=20.741177510203 and B=22.127033665221 degrees Celsius. Keeping PC1 and the stored training mean reconstructs both as their mean, 21.434105587712. The individual difference is lost while the shared condition is retained. These values are an actual observation from the plotted synthetic sensor data.Two measured temperaturesReconstructed using PC1A: 20.7°CB: 22.1°CA ≈ 21.4°CB ≈ 21.4°CThe shared warmth remains. The small A–B difference is lost.

We still know whether the laboratory is warm or cool. We have given up some detail about how the two sensors differ.

How much variation did we retain?

\[ \frac{7.68}{7.68+0.32}=0.96 \]

One of two coordinates retains 96% of the temperature variance in this example.

That percentage describes spread in the inputs. It does not directly measure classification performance.

How many components?

ComponentVarianceShareCumulative share
PC18.080%80%
PC21.010%90%
PC30.77%97%
PC40.33%100%

In this illustrative example, how many components retain at least 95% of the variance?

Three components retain 97%

Add the variances of the components we keep, then divide by the total variance.

\[ \frac{8+1+0.7}{8+1+0.7+0.3}=0.97 \]

This is the cumulative explained-variance ratio for the four-component example.

House inputs on comparable scales

To predict house prices, we might use floor area and bedroom count.

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.

InputTraining meanTraining spread
Floor area1,500 ft²500 ft²
Bedrooms31

\[ \frac{2000-1500}{500}=1\qquad\frac{4-3}{1}=1 \]

Illustrative house inputs for a price-prediction task. Each transformed value is (input minus training mean) divided by training standard deviation. PCA’s objective depends on numerical scale. Standardising changes that scale; it does not establish feature usefulness. PCA centres its input but does not automatically standardise each feature.

Could most variance still miss the class?

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

Two illustrative flower species have similar petal lengths but different widths. Which direction varies most? Which distinguishes the species?

Synthetic illustrative flower measurements, not the Iris dataset. The two species have identical length coordinates. Width differs by 0.3 cm with a small shared variation orthogonal to length. Unscaled covariance PCA follows the much larger length spread.

PCA does not look at the labels

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

PC1 keeps more than 99% of the variance here, but loses the petal-width distinction between the species.

A small amount of variation can carry important predictive information.

The first component retains fraction 0.992617181471 of variance in this synthetic example. Small vertical marker offsets in the one-dimensional display only help show both colours and are not retained inputs. No class labels are used in fitting PCA.

Digits have 64 pixel inputs

Actual eight by eight digit images with visible cellsFour actual training images from scikit-learn load_digits, labels zero, two, five and eight. Every image consists of exactly sixty-four vector squares, one per original brightness value, without interpolation. Representative original images are selected by distance to their own class mean; no digit pixels are altered.0258Each image has 8 rows and 8 columns.

\[ 8\times8=64 \]

These are the small scikit-learn digit images used below. Each square is one original pixel.

Actual load_digits samples are eight by eight, not the larger MNIST images. This view draws each original brightness value as a vector square without smoothing or invented detail. https://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_digits.html

One image, 64 numbers

One image and its sixty-four numbersThe same actual eight by eight digit-two sample appears twice. Each original pixel is a vector square; on the right its brightness value, from zero to sixteen, is printed inside the square. The array can be flattened row by row into sixty-four input coordinates.The imageIts 64 brightness values00716163000716914700010901450003341620000012110000061630000012158830001016161690The same 64 measured values can be stored as one input row.

Reading the rows in order gives 64 input measurements. Nearby pixels often vary together.

The two arrays show exactly the same actual digit-two image. Values range from zero to sixteen. Drawing numbers and pixels at a larger size does not add image resolution.

Principal directions become image patterns

Principal directions as pixel patternsThe first six PCA direction vectors fitted on the 1437-image training subset, reshaped to eight by eight. Red and blue indicate opposite signed weights, using one shared symmetric scale. These are directions of variation rather than prototypes of named digits. Overall signs are arbitrary. PC1 PC2 PC3 PC4 PC5 PC6

Reshape each direction’s 64 weights into an 8 × 8 pattern. A component adds or subtracts a shared pattern from the mean image.

First six principal directions fitted on the 1437 training images, centred without per-pixel scaling. Red and blue denote opposite signs on a shared symmetric colour scale. These patterns are not class prototypes, and overall component signs are arbitrary.

Reconstruct with fewer coordinates

Sharp pixel reconstructions beside their exact originalsThe same actual digit-two, digit-five and digit-eight samples from the preceding gallery are reconstructed with 1, 5, 10, 20, 40 and all 64 components. Each original and reconstructed value is drawn as an individual vector square using one shared zero-to-sixteen grayscale mapping. The All 64 and Original columns agree to floating-point precision. PCA is fitted on the fixed training subset; this is a compression illustration, not evidence of held-out classification performance.21 PCs5 PCs10 PCs20 PCs40 PCsAll 64Original58Same examples as the earlier gallery. All 64 reconstruct the original pixels.

These are the same examples as the earlier gallery. More components retain finer detail; all 64 recover the original pixels.

The identical gallery samples appear in the reconstructions, with individual vector pixel cells and an explicit Original column. All-64 reconstruction agrees with each original to below 3×10⁻¹⁴ in pixel values. Images are training examples for a compression illustration, not evidence of classification generalisation.

Explained variance for the digit images

Explained variance on the digit training dataCumulative ratios calculated from the full PCA fit on the fixed 1437-image training subset, centred without per-pixel standardisation. Ninety and ninety-five percent reference levels are annotated with their actual component counts. 10 20 30 40 50 60 Number of retained components 0.0 0.2 0.4 0.6 0.8 1.0 Cumulative explained variance 21 components 28 components

For this training split, 21 components retain at least 90% of the variance and 28 retain at least 95%.

Computed from scikit-learn load_digits: stratified 80/20 split, random_state=7, training N=1437, PCA full SVD, no per-pixel scaling. This is not an assessment result.

Two components give a picture

A two-dimensional view of sixty-four input measurementsThe training digits projected onto the first two PCA components. Colours display labels only after fitting PCA. These two components preserve about 29% of training variance, and several classes overlap in this projection. −30 −20 −10 0 10 20 30 PC1 score −30 −20 −10 0 10 20 30 PC2 score 0 1 2 3 4 5 6 7 8 9

Two axes make the data visible, but retain only about 29% of its variance. Several classes overlap.

PCA is fitted without labels. Colours are added to interpret the training-data projection. A two-dimensional visualisation and a useful predictive representation have different goals.

Nearest neighbours

How would you label this new flower?

A new flower and its nearest reference examplesThe same one hundred versicolor and virginica training measurements and one new query location. The star has no observed label in this illustration. 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

The square and circle examples have known labels. The star is a new set of petal measurements.

One neighbour votes

A new flower and its nearest reference examplesThe same one hundred versicolor and virginica training measurements and one new query location. The 1 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

With k = 1, copy the label of the nearest reference flower: versicolor.

Three neighbours vote

A new flower and its nearest reference examplesThe same one hundred versicolor and virginica training measurements and one new query location. The 3 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

With k = 3, the votes are 2 versicolor, 1 virginica. The most common label wins.

Five neighbours vote

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

With k = 5, the votes are 2 versicolor, 3 virginica. The neighbourhood can change the decision.

All three diagrams use exactly the same query and reference rows. Neighbours are selected with Euclidean distance after StandardScaler fitted on the reference examples. The new query has no known true label here. Nearest-neighbour classification.

The nearest-neighbour calculation

  • Choose k and the distance rule.
  • Measure the new input’s distance to the reference examples.
  • Find the k nearest reference examples.
  • Use their labels to predict the new label.

\[ d(x,x^{\prime})=\sqrt{(x_1-x_1^{\prime})^2+(x_2-x_2^{\prime})^2} \]

Uniform voting is the default illustration. Search implementations may use a tree or a brute-force calculation and need not literally sort every distance.

Distance depends on the units

Difference between two flowersIn centimetresIn millimetres
Petal length0.55
Petal width0.22

If we change only width from centimetres to millimetres, its squared difference changes from 0.04 to 4.

The same physical flowers can acquire different numerical neighbours.

How do we solve this?

Changing both features by the same constant factor leaves neighbour rankings unchanged. Changing only one feature changes its relative influence on Euclidean distance.

Standardisation gives a common reference

\[ x_j^{s}=\frac{x_j-\mu_j}{s_j} \]

Compare how far each measurement is from its training mean, relative to that measurement’s training spread.

Use the same stored means and scales for every new example. The preceding flower diagrams already do this.

This makes the distance invariant to a pure change of units in an individual feature, aside from constant/degenerate features. It does not prove all inputs deserve equal predictive influence. StandardScaler.

What is the issue here?

Relative distances concentrate in this exampleDistances between 16000 independent pairs of uniformly distributed points in each of dimensions two, ten and one hundred. Distances are divided by square root of dimension so their relative spread can be compared. This example does not assert that every high-dimensional dataset behaves identically. 0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 Euclidean distance divided by √d 0.0 2.5 5.0 7.5 10.0 12.5 15.0 Density 2 inputs 10 inputs 100 inputs

A neighbour rule depends on distance. What problem could this pattern create?

Everyone can start to look like a neighbour

Relative distances concentrate in this exampleDistances between 16000 independent pairs of uniformly distributed points in each of dimensions two, ten and one hundred. Distances are divided by square root of dimension so their relative spread can be compared. This example does not assert that every high-dimensional dataset behaves identically. 0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 Euclidean distance divided by √d 0.0 2.5 5.0 7.5 10.0 12.5 15.0 Density 2 inputs 10 inputs 100 inputs

kNN still selects k examples. The problem is that “nearest” can be only slightly closer than the other examples.

The distance ranking may become a weaker clue about meaningful similarity.

The plotted example uses independent uniform coordinates. Relative contrast weakens as dimension grows; nearest and farthest remain well-defined. Structured data and a well-chosen representation can retain useful neighbourhoods, so this is not a universal impossibility result.

A small neighbourhood

The same Iris training data with k equal to 1Uniform voting among 1 nearest training points gives this boundary. The feature scaler is identical across all three plots. The background illustrates decisions across the plane, not a measured held-out performance result. 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

With k = 1, individual training examples can create small pockets of a class.

A larger neighbourhood

The same Iris training data with k equal to 5Uniform voting among 5 nearest training points gives this boundary. The feature scaler is identical across all three plots. The background illustrates decisions across the plane, not a measured held-out performance result. 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

With k = 5, one unusual example has less influence on the vote.

A much larger neighbourhood

The same Iris training data with k equal to 25Uniform voting among 25 nearest training points gives this boundary. The feature scaler is identical across all three plots. The background illustrates decisions across the plane, not a measured held-out performance result. 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

With k = 25, local differences can disappear. A smoother boundary can also miss real structure.

The plots show the same hundred reference flowers, the same standardisation and the same axes. Larger k is not guaranteed to improve performance. These are explanatory training boundaries, not held-out evaluations.

One neighbour divides the space

Neighbour votes determine decision regionsThe same ninety synthetic examples, fifty orange squares and forty blue circles, in a common coordinate system. One-neighbour classification colours each location by its nearest example. Thin Voronoi edges mark individual nearest-example cells, including edges between examples of the same class. −1.5 −1.0 −0.5 0.0 0.5 1.0 1.5 2.0 2.5 Input A −1.0 −0.5 0.0 0.5 1.0 1.5 Input B Squares: 50 Circles: 40 A B C

A new example: 50 squares and 40 circles. Each cell belongs to its nearest training point. This is a Voronoi tessellation.

The new synthetic two-input example has common numerical units and no feature scaling. At k=1 every point in a Voronoi cell copies the label of the reference point defining that cell. Thin cell edges can separate reference points of the same class, so not every cell edge is a class boundary.

Several neighbours reshape the regions

Neighbour votes determine decision regionsThe same ninety synthetic examples, fifty orange squares and forty blue circles, in a common coordinate system. Uniform majority voting among nine neighbours gives the background decision regions. −1.5 −1.0 −0.5 0.0 0.5 1.0 1.5 2.0 2.5 Input A −1.0 −0.5 0.0 0.5 1.0 1.5 Input B Squares: 50 Circles: 40 A B C

Now the nine nearest examples vote. The background shows their majority label at each location.

The same ninety points, axes and metric as the preceding slide. These are k=9 class-decision regions, rather than ordinary one-neighbour Voronoi cells. https://scikit-learn.org/stable/modules/neighbors.html

What if every example votes?

Neighbour votes determine decision regionsThe same ninety synthetic examples, fifty orange squares and forty blue circles, in a common coordinate system. No background predictions are shown. Three new query locations A, B and C prompt an audience question about using all ninety neighbours. −1.5 −1.0 −0.5 0.0 0.5 1.0 1.5 2.0 2.5 Input A −1.0 −0.5 0.0 0.5 1.0 1.5 Input B Squares: 50 Circles: 40 A B C

We set k = 90. Do the new inputs A, B and C receive different predictions?

The majority label wins everywhere

Neighbour votes determine decision regionsThe same ninety synthetic examples, fifty orange squares and forty blue circles, in a common coordinate system. All ninety examples vote at every location, so the fifty-square majority makes the whole plane the square class. −1.5 −1.0 −0.5 0.0 0.5 1.0 1.5 2.0 2.5 Input A −1.0 −0.5 0.0 0.5 1.0 1.5 Input B Squares: 50 Circles: 40 A B C

All three receive the square label. The same 50 squares and 40 circles vote at every location.

Uniform voting and k=N=90. Every location receives all reference examples, giving 50 versus 40 votes. The prediction is constant everywhere, so the class boundary disappears.

Which k should we choose?

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)

All three maps use the same examples. Which will make the best predictions for new inputs?

Which k should we choose?

Validation compares neighbour counts on the same exampleFive-fold stratified validation on the same ninety synthetic examples. Every fold uses seventy-two reference examples and checks eighteen held-out examples, so candidate k values cannot exceed seventy-two. Points are mean accuracy; bars are standard deviation across folds, not confidence intervals. No preprocessing is fitted; the two inputs already use a common numerical scale. 1 5 15 25 49 71 Neighbours k 0.4 0.5 0.6 0.7 0.8 0.9 1.0 Five-fold validation accuracy

Compare on held-out examples. Points show mean accuracy, and bars show spread across the five folds.

Here each fold fits on 72 points and checks the remaining 18.

Validation on the same ninety-point example as the preceding maps, not the earlier Iris dataset. Candidate neighbour counts are 1, 3, 5, 9, 15, 25, 49 and 71, all below the seventy-two reference examples in a fold. Error bars are fold standard deviations, not confidence intervals. A separate final test would stay outside model selection.

Nearest neighbours can also predict a number

Nearby houseObserved price
Neighbour 1£210,000
Neighbour 2£240,000
Neighbour 3£270,000

\[ \widehat{y}=\frac{210,000+240,000+270,000}{3}=240,000 \]

For regression, uniform-weight kNN averages the neighbours’ target values.

Predicting with kNN

Nearest-neighbour search during predictionFitting retains training measurements and labels, and may construct a search index. For a new input, inference compares its measurements with the stored training references, retrieves k neighbours and votes. It does not look up the new example’s unknown target label or train a neural-network weight set.Training examplesStored inputs + labelsNew inputMeasurements onlyNeighbour searchMeasure distancesVotePredicted label

model = KNeighborsClassifier(n_neighbors=5)
model.fit(X_train, y_train)
predicted = model.predict(X_new)

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

KNeighborsClassifier fitting stores reference data and labels, and may build a search index. Prediction computes or retrieves neighbours through a brute-force or indexed search. It does not require the unknown labels of the new examples. There is no gradient-descent weight fit analogous to a neural network. https://scikit-learn.org/stable/modules/neighbors.html

Combining different ML techniques

The complete prediction sequenceAn ordered sequence transforms raw input measurements and then uses a fitted predictor. The complete workflow, including fitted transformation parameters, must be reused for new inputs. The representation can combine more than one machine-learning technique.MeasurementsOriginal inputsTransformScale and/or PCAkNNFind neighboursPredictionClass or numberA pipeline keeps the ordered steps together.

One technique can create the representation that another uses. For example, PCA coordinates can become inputs to a neighbour rule.

Check the complete combination on validation data. Compression can retain useful structure or discard it.

Pipelines in practice

One prediction has several steps

The complete prediction sequenceAn ordered sequence transforms raw input measurements and then uses a fitted predictor. The complete workflow, including fitted transformation parameters, must be reused for new inputs. The representation can combine more than one machine-learning technique.Measurements4 valuesStandardise4 scaled valuesPCA2 coordinateskNNNeighbour voteA pipeline keeps the ordered steps together.

A new flower starts as raw measurements. Scaling and PCA prepare the coordinates that kNN uses.

This ordered sequence is called a pipeline.

One flower follows the complete calculation

StageValues for this flower
Raw measurements(6.20, 2.80, 4.80, 1.80)
After scaling(0.42, -0.60, 0.57, 0.77)
After PCA(1.14, -0.34)
kNN predictionvirginica

Here the inputs are all four Iris measurements: sepal length, sepal width, petal length and petal width.

Actual numerical example from StandardScaler → PCA(2) → KNeighborsClassifier(5), fitted on 120 stratified training Iris examples with random_state=7. This one flower is from the remaining thirty examples. Display values are rounded to two decimal places. No accuracy claim is made from this one prediction.

Training learns the stored steps

StepWhat comes from the training flowers
ScalingEach input’s mean and standard deviation.
PCAThe mean and directions used for projection.
kNNThe reference measurements and their labels.

The complete fitted workflow includes all of these objects.

The scaler and PCA also learn from data even though they do not use class labels. Learn them on training data, including separately inside cross-validation training folds.

New flowers reuse the fitted steps

Fit on training examples and reuse for new examplesTraining examples determine the preprocessing parameters and classifier. The same fitted preprocessing transforms validation and future examples before the fitted classifier predicts them. Evaluation examples do not fit those steps.Training rowsLearn the stepsFit preprocessingMean, scale, axesFit the classifierOn transformed training rowsNew rowsValidation or useTransform onlyReuse fitted stepsPredict onlyReuse fitted classifier

Use the stored training means, scales and PCA axes for validation flowers and future observations.

Their measurements pass through the sequence without fitting new steps.

One object keeps the steps together

from sklearn.pipeline import make_pipeline

model = make_pipeline(
    StandardScaler(),
    PCA(n_components=2),
    KNeighborsClassifier(n_neighbors=5)
)
model.fit(X_train, y_train)

One fit call learns the transformations and prepares the neighbour model, in order.

StandardScaler, PCA and KNeighborsClassifier are imported from their usual scikit-learn modules. This illustrates mechanics with four Iris inputs, not a claim that this is the optimal configuration. https://scikit-learn.org/stable/modules/generated/sklearn.pipeline.Pipeline.html

One predict call runs the sequence

predicted = model.predict(X_new)

The complete prediction sequenceAn ordered sequence transforms raw input measurements and then uses a fitted predictor. The complete workflow, including fitted transformation parameters, must be reused for new inputs. The representation can combine more than one machine-learning technique.Measurements4 valuesStandardise4 scaled valuesPCA2 coordinateskNNNeighbour voteA pipeline keeps the ordered steps together.

Pass raw measurements in. The pipeline applies its fitted scaling, then PCA, then the neighbour vote.

Validation checks the complete workflow

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.

For each fold, learn every step from the blue training rows. Use the orange rows to check the resulting predictions.

Cross-validation refits all learned steps within each fold, keeping its checked rows out of preprocessing fits as well as the predictor fit. The schematic uses three folds only to make the process easy to see. A final test remains outside selection.

Keep the complete fitted workflow

  • Keep preprocessing together with the predictor.
  • Use the same input columns, order and units for new observations.
  • Record the data split and configuration so the result can be reproduced.

The usable model is the whole sequence that turns raw measurements into a prediction.

Today we covered

  • More input dimensions can make examples sparse and distances less informative.
  • PCA constructs orthogonal coordinates that preserve input variance.
  • Nearest neighbours use the chosen representation to vote or average.
  • A pipeline fits and reuses preprocessing together with the predictor.