k-NN

Distances, k, classification and regression

8 lessons · 14 past questions · 38 marks in the papers collected here

Open the interactive lessons →k-NN past questions

Diagrams, animations, quizzes and checked solutions are on the interactive pages.

Contents

  1. Orientation: what you will learn and why
  2. Big picture: concept map, model comparison and the recipe
  3. Start here: distance and voting
  4. The k-NN algorithm and how to run it
  5. Choosing k: smooth boundary, overfitting and training error
  6. Properties and cost: lazy, non-parametric, counting distances
  7. k-NN regression: averaging the neighbours
  8. Leave-one-out cross-validation with k-NN, and changing labels

1. Orientation: what you will learn and why

k-nearest neighbours (k-NN) is the simplest learning method there is: to label a new point, look at the training points closest to it and copy their answers. There is no formula for $w$, no training loop, no tree. All the work happens at prediction time.

What you will be able to do

Why this topic matters for Quiz 2

Counted only from the PYQs in this project (not a prediction):

What the PYQs askPYQsMarks
The k-NN algorithm and distances39
Choosing k: smoothness and training error410
Properties and cost38
k-NN regression26
LOOCV with k-NN and changing labels25

In total 14 PYQs worth 38 marks across 8 papers (3 MCQ, 1 MSQ, 10 numeric). Two further 2022 questions (Jul 2022 Q21, Q22) depend on a figure whose point coordinates are not in the bank text, so they are listed under the flags and not solved here.

How this topic connects

The model-comparison topic (later) asks which models can reach zero training error, which uses the k-NN facts here. The cross-validation topic reuses the LOOCV procedure shown in the last section.

Tags: [SRC] from your files, [DERIVED] answer I worked out because the bank gives no key, [ADDED] my own example, [FLAG] disagreement between my calculation and a key.
How to use this page

Read each section, do the quick checks, then attempt each PYQ before opening its solution.

What is new in this upgrade [ADDED]

The route through this topic
distance and votethe algorithmchoosing kregression and leave-one-out

2. Big picture: concept map, model comparison and the recipe

[ADDED] Read this page first. It shows the whole topic on one screen.

The concept map

Store datano training stepDistanceto every training pointSortsmallest firstTake kthe k nearestVote or averageclass: vote value: meanThree knobs you can turnksmall: jagged, overfitslarge: smooth, underfitsDistance metricEuclidean, Manhattancan change the answerFeature scalebig units dominate distancerescale firstCosttraining: nothing. Prediction: n distances (does not depend on k). LOOCV: a prediction for each point, leaving that point out.
k-NN has no training step. A prediction is: distance to every training point, sort, take $k$, vote or average. Three knobs change the answer: $k$, the distance metric and the feature scale.

k-NN next to the other models of this course

k-NNLinear regressionKernel regressionDecision treeNaive Bayes
Trainingnone (stores data)solve $XX^Tw=Xy$solve $K\alpha=y$grow a tree by entropycount / estimate per class
Needs training points to predict? (PYQ definition)yesnoyesnono
Parametric?noyesnoyes (tree)yes
Cost of one prediction$n$ distancesone dot product, $d$$n$ kernel valuesfollow one patha product over features
Decision boundaryjagged to smooth, set by $k$one straight line / planecurvedaxis-parallel rectanglesstraight or curved
Main knob$k$ (and the metric)none (or $\lambda$)kernel and degreedepth / min leaf sizesmoothing
Sensitive to feature scale?yes, stronglyweights adjustyes (dot products)nono

The exam recipe, in five lines

Mnemonics and recognition cues [ADDED]

Analogy and its limit [ADDED]

AnalogyWhat it explains wellWhere it breaks
Ask the $k$ nearest neighbours in a new cityvoting, the role of $k$, why one odd neighbour matters less when $k$ is largerreal neighbours differ in trust; plain k-NN gives every neighbour exactly the same vote, however far away
Houses with similar features have similar pricesregression by averagingif a feature is in dollars and another in rooms, "similar" is dominated by dollars unless you rescale

Recall questions

How many distances does one prediction need?

$n$, one per training point, whatever $k$ is.

Which is the training error of 1-NN (no duplicate points with different labels)?

$0$, because each point is its own nearest neighbour.

What separates LOOCV from training error?

LOOCV removes the point before predicting it. Training error does not.

Tips and tricks
  • Write down three things before computing: the distance, the value of $k$, and the tie rule.
  • Small $k$ gives a wiggly boundary, large $k$ a smooth one.

3. Start here: distance and voting

Picture it

Walking across a field (straight line) against walking along city blocks.

Piece 1. Distance between two points

Definition: Euclidean and Manhattan distance

For $a=(a_1,\dots,a_d)$ and $b=(b_1,\dots,b_d)$: Euclidean $d_2(a,b)=\sqrt{(a_1-b_1)^2+\dots+(a_d-b_d)^2}$ (straight-line); Manhattan $d_1(a,b)=|a_1-b_1|+\dots+|a_d-b_d|$ (walk along the grid).

Example: $a=(1,2)$, $b=(4,6)$: differences $(-3,-4)$; $d_2=\sqrt{9+16}=5$; $d_1=3+4=7$.

A time saver

To rank neighbours you can compare squared distances $\sum(a_i-b_i)^2$; the order is the same and you avoid square roots. (Taking a square root never changes which of two non-negative numbers is bigger.)

Piece 2. Majority vote and average

Classification: count the labels among the $k$ neighbours; the label with the most votes wins. With two classes and odd $k$ there is never a tie. Regression: the prediction is the plain average of the neighbours' numeric labels.

Piece 3. Sorting by distance, step by step

  1. Write each training point and its distance to the test point.
  2. Sort the distances from smallest to largest.
  3. Take the first $k$.
  4. Read their labels and vote (or average).
Trap: count the right thing

You compute a distance to every training point; only then do you pick the $k$ smallest. Choosing $k$ does not change how many distances you compute.

Two metrics, one picture [ADDED]

test (0,0)P = (3, 0)Q = (2, 2)Same two points, two metricsEuclid: d(P)=3.00, d(Q)=2.83 → Q nearerManhattan: d(P)=3, d(Q)=4 → P nearerBlue circles: points at Euclidean distance 3(solid) and 2.83 (dashed).Red diamond: points at Manhattan distance 3.Q is inside the circle but outside the diamond.
Test point at the origin. The set of points at Manhattan distance $3$ is a diamond; the set at Euclidean distance $3$ is a circle. $P=(3,0)$ lies on both. $Q=(2,2)$ is at Euclidean distance $\sqrt8\approx2.83$ (inside the circle, so Euclidean says $Q$ is nearer) but at Manhattan distance $4$ (outside the diamond, so Manhattan says $P$ is nearer). The choice of metric can change the neighbours, hence the prediction.

Feature scale: why you rescale [ADDED]

Test person $(\text{age}=30,\ \text{income}=50{,}000)$. Candidate $P_1=(31,\ 52{,}000)$ is almost the same age. Candidate $P_2=(60,\ 50{,}100)$ is 30 years older.

Units$d(T,P_1)$$d(T,P_2)$Nearest
income in dollars2000.00104.40$P_2$ (income difference swamps age)
income in thousands2.23630.000$P_1$

The same people, the same rule, a different answer, only because of units. Rule: when features have very different scales, rescale them (for example subtract the mean and divide by the standard deviation) before running k-NN. Exam questions usually give features on comparable scales; if one feature is much larger, rescaling is the first thing to think about.

A quick glossary [ADDED]

WordMeaningExample
neighbourone of the $k$ closest training points$N_3(x)=\{7,19,4\}$ in the toy figure
majority votethe label that most neighbours carry2 blue, 1 red: blue
tieequal votes (possible only for even $k$ with two classes)$k=2$, one of each
lazy learnerno work at training timek-NN
hyperparametera number you choose, not learned from the data$k$, the metric
Which is nearer to $(0,0)$ in Manhattan distance: $(3,0)$ or $(2,2)$?

$(3,0)$: distance $3$ against $4$.

Worked example: votes, ties and averages

$k=4$ neighbours with labels $1,1,0,0$: the vote is tied $2$ to $2$, so the answer depends on the tie rule the question gives (often "choose the closer group" or "choose label 1"). For regression with $k=3$ and neighbour labels $3,5,10$, the prediction is the average $(3+5+10)/3=6$.

Memory line

Euclidean is straight; Manhattan adds the gaps.

4. The k-NN algorithm and how to run it

Intuition

Everyday analogy

You move to a new city and want to know whether a restaurant is good. You ask the $k$ people who live closest to it. If most say "good" you believe "good". That is k-NN: neighbours vote.

Definition

Definition: k-NN classifier

Given training pairs $(x_i,y_i)$, a distance $d$ and an integer $k\ge1$. For a test point $x$: (1) compute $d(x,x_i)$ for all $i$; (2) pick the $k$ training points with the smallest distance, called the neighbours; (3) predict the most common label among them.

Formula: k-NN prediction

$$\hat y(x)=\arg\max_{c}\ \sum_{i\in N_k(x)}\mathbf 1[y_i=c]$$ $N_k(x)$ is the set of the $k$ closest training indices, $\mathbf 1[\cdot]$ is $1$ if the statement is true and $0$ otherwise. We simply count votes per class $c$.

Why it works

If labels change smoothly with position, close points tend to share a label. Copying the nearest labels is therefore a good guess, and using several ($k>1$) protects against a single odd point.

Worked examples

Worked example: Simple: three points

Problem. Training: $A=(0,0)$ label $1$, $B=(1,0)$ label $1$, $C=(5,5)$ label $0$. Test $(0.4,0)$, $k=1$.

What is asked. The prediction.

Idea / formula used. Nearest neighbour.

Distance to $A=0.4$.
Distance to $B=0.6$.
Distance to $C=\sqrt{4.6^2+5^2}\approx6.8$.
Nearest is $A$ with label $1$.
Answer: Predict $1$.
Common mistake: choosing the point with the largest feature value instead of the smallest distance.
Worked example: Exam level: 3-NN in $\mathbb R^3$

Problem. $x_1=(0,1,1),x_2=(4,0,0),x_3=(1,2,2),x_4=(2,2,0),x_5=(-3,1,1)$ with labels $1,0,0,1,0$. Test $(1,1,1)$, $k=3$.

What is asked. The predicted label.

Idea / formula used. Squared distances, sort, vote.

$d^2$: $x_1{:}\,1$, $x_2{:}\,11$, $x_3{:}\,2$, $x_4{:}\,3$, $x_5{:}\,16$.
Three smallest: $x_1(1),x_3(2),x_4(3)$.
Their labels are $1,0,1$: label $1$ wins $2$ to $1$.
Answer: $1$
Common mistake: counting labels over all five points, where $0$ is the majority.
Worked example: Tricky: adding a point must not change the vote

Problem. Test point at the origin. A $-1$ point is at distance $1$, $+1$ points at distances $2$ and $3$, and a $-1$ point at distance $5$. With $k=3$ a new $-1$ point is added.

What is asked. Where can it go so that the prediction stays the same?

Idea / formula used. Track which three points are nearest.

Now the three nearest are at distances $1,2,3$: votes $-1,+1,+1$, so $+1$.
If the new $-1$ point is closer than $3$, it pushes out the $+1$ at distance $3$ and $-1$ gets two votes.
If it is farther than $3$, the three nearest do not change.
Answer: anywhere farther than $3$ from the test point
Common mistake: thinking only points closer than the nearest neighbour matter.

Common mistakes

A full run on a picture [ADDED]

0246810#1: d² = 0.45#2: d² = 2.60#3: d² = 3.20test point3 nearest: labels blue, red, bluevotes: red 1, blue 2 → predict blueDashed ring: radius = distance to the 3rd neighbour.Everything inside the ring is a neighbour.
Twenty training points (blue = class 0, red = class 1; the red point inside the blue cluster at $(3,3)$ is a deliberate outlier). The star is the test point $(4.6,3.2)$. The dashed ring has radius equal to the distance to the third neighbour.

Squared distances to the test point (all computed by the code, five smallest shown):

RankTraining pointLabelSquared distance
1(4, 3.5)blue0.45
2(3, 3)red2.60
3(3, 4)blue3.20
4(4, 1.5)blue3.25
5(6, 2)red3.40

k = 1: the nearest is $(4,3.5)$, blue: predict blue. k = 3: the three nearest have labels blue, red, blue: two blue, one red: predict blue. k = 5: labels blue, red, blue, blue, red: predict blue. The red outlier is the second nearest, but with $k\ge3$ it is outvoted.

Ties and edge cases [ADDED]

SituationWhat happensWhat to do in an exam
Even $k$, two classesa vote can tie (e.g. $k=2$: one of each)the question normally uses odd $k$; if not, it will state a tie rule
Two points at the same distance at the $k$-th placemore than $k$ points qualifyuse the rule given in the question; otherwise say which neighbours you took and why
$k>n$not defineduse $k\le n$
$k=n$every point is a neighbour, so the prediction is the overall majoritythe same label for every test point
Duplicate training points with different labelsthey tie as neighbourscount both votes
A test point equal to a training pointdistance $0$, nearest neighbour is that pointfor $k=1$ the prediction is its label

Common mistakes, as a table [ADDED]

MistakeWhy it is wrongFix
Comparing first coordinates onlydistance uses all coordinatescompute the full distance for every point
Skipping a training pointit might be the nearestlist all $n$ distances before sorting
Taking the $k$ largest distancesthe neighbours are the nearestsort ascending
Square-rooting then comparing squared and unsquared valuesmixing the two gives a wrong orderstay in squared distances for the ranking
Voting in a regression problemregression predicts a numbertake the mean of the neighbours labels

Recall questions

Why can you rank neighbours by squared distance?

Square root is increasing, so the order of two non-negative numbers is unchanged.

Two classes, odd $k$: can the vote tie?

No.

Tips and tricks
  • Compare squared Euclidean distances to avoid square roots.
  • Stop sorting once you have the $k$ nearest.
Memory line

Distance, sort, take $k$, vote.

5. Choosing k: smooth boundary, overfitting and training error

Intuition

Everyday analogy

Asking one neighbour is like trusting one person's taste: very personal, easily fooled by a strange neighbour. Asking everybody in the city gives an average opinion that ignores local differences. A middle number of neighbours balances the two.

What $k$ does

$k$BoundarySensitive to outliers?Risk
small (e.g. $1$)jagged, follows every pointyesoverfit (low bias, high variance)
largesmooth, nearly straight or flatnounderfit (high bias, low variance)
$k=n$predicts the overall majority everywherenomaximum underfit
Formula: Rule to remember

Increasing $k$ makes the decision boundary smoother. Decreasing $k$ makes it more jagged. With outliers present, a larger $k$ averages them away.

Training error and "each point is its own neighbour"

When we compute the training error of k-NN, the training point itself is in the training set, so it is at distance $0$ and is one of its own $k$ neighbours.

Worked examples

Worked example: Simple: minimum mistakes for $k=3$

Problem. $80$ points, $40$ per class, $k=3$, each point is its own neighbour. Minimum possible number of training mistakes?

What is asked. The minimum.

Idea / formula used. Construct a data set with no mistakes.

Put the $40$ points of class A in one tight group and the $40$ of class B in another far-away group.
For any point, its $3$ nearest neighbours are itself and two points of its own group, so all three votes match its own class.
So no point is misclassified: $0$ mistakes. We cannot go below $0$.
Answer: $0$
Common mistake: thinking that with $k=3$ some errors are unavoidable.
Worked example: Exam level: outliers and smoothness

Problem. With outliers present, does the boundary become smoother when $k$ increases?

What is asked. Yes or no.

Idea / formula used. Outliers affect few neighbours.

An outlier is a lone point of one class in the middle of the other class.
With $k=1$ it carves a small island of its class around itself (jagged boundary).
With $k=5$ the island needs several same-class neighbours, which it does not have, so the island disappears and the boundary is smoother.
Answer: Yes (so the "decreasing $k$ is smoother" version is False).
Common mistake: reversing the direction.
Trap: direction of k

Small $k$ = flexible = jagged = low training error. Large $k$ = rigid = smooth. Mixing these up is the most common error in this topic.

How the boundary changes with $k$: a picture [ADDED]

k = 1training error 0.00, LOOCV 0.15k = 5training error 0.05, LOOCV 0.05k = 9training error 0.05, LOOCV 0.05
The same twenty points (the outlier is the red dot with a black ring). Blue area: the region where a test point would be predicted blue. For $k=1$ a small red island appears around the outlier. For $k=5$ and $k=9$ the island is gone and the boundary is smooth. The number of neighbouring grid cells with different predictions (a roughness count) is 55 for $k=1$, 42 for $k=5$ and 40 for $k=9$, about 1.4 times smoother at $k=9$.

Error against $k$ [ADDED]

1357911131517190.00.20.40.60.81.0k (number of neighbours)error ratetraining error (a point counts itself)LOOCV error (the point is left out)
Training error (blue) and LOOCV error (red dashed) for odd $k$ from $1$ to $19$ on the toy data. Training error is $0$ at $k=1$ and then stays at 0.05 (the outlier is always outvoted). LOOCV error is 0.15 at $k=1$, drops to 0.05 for $k=3$ to $15$, and then rises; at $k=19=n-1$ it is 1.00.

Three facts to read off the picture: (1) the training error does not tell you the best $k$, since $k=1$ looks perfect; (2) the leave-one-out error is the honest estimate; (3) a very large $k$ is a disaster. With $n=20$ balanced points, $k=19$ uses all other points as neighbours. Removing a blue point leaves $9$ blue and $10$ red, so the vote is always for the other class, and the LOOCV error is $1.00$.

Minimum training mistakes: the reasoning [ADDED]

$k$A point is wrong in training only if...Minimum possible total
1it differs from itself (impossible, unless two identical points have different labels)0
3its two other neighbours both have the other label (1 vote against 2)0 (put each class in tight clusters of at least 2)
general odd $k$at least $\frac{k+1}2$ of its neighbours (counting itself) have the other label0

Why the minimum is $0$ for any $k$: place all points of each class in a very tight cluster of at least $\frac{k+1}2$ points far from the other class. Every point's neighbourhood is then pure. The maximum has a different answer, which is why the question says "minimum".

Effect of $k$ on bias and variance: a compact table [ADDED]

$k$VarianceBiasTraining errorLOOCV error
very smallhighlowlowest (0 at $k=1$)can be high (noise)
moderatemediummediumsmall but non-zerousually lowest
very largelowhighhighhigh

How to choose $k$ [ADDED]

Recall questions

A larger $k$ makes the boundary...?

Smoother.

Why is the training error of $k=1$ a bad guide?

It is $0$ by construction (each point is its own neighbour).

Tips and tricks
  • With $k=1$ the training error is 0, unless identical points carry different labels.
  • With $k=n$ every prediction is the overall majority class.
Memory line

Small $k$ wiggles, large $k$ smooths.

6. Properties and cost: lazy, non-parametric, counting distances

Picture it

A student who does no revision and looks everything up during the exam.

Properties (true / false list)

StatementTrue?Reason
k-NN is a lazy learnerTrueit does no work at training time; it just stores the data
k-NN needs the training data at prediction timeTrueneighbours come from the stored data
k-NN is non-parametricTrueno fixed set of weights; the data itself is the model
$k$ is the number of featuresFalse$k$ is the number of neighbours
k-NN estimates probability distributionsFalseit just votes, no distribution is fitted
The distance metric can change the predictionTruedifferent metrics give different nearest points
Prediction cost grows with the training-set sizeTruemore distances to compute
$k$ is a hyperparameter chosen by cross-validationTrueit is not learned by minimising training error

Counting distance computations

Formula: Distances per prediction

A plain k-NN prediction computes the distance from the test point to every training point: exactly $n$ distances for $n$ training points. This number does not depend on $k$.

Worked example: Simple: how many distances?

Problem. $100$ training points, $k=10$ (or $k=5$). How many distances to predict one test point?

What is asked. The count.

Idea / formula used. One per training point.

The test point is compared with each of the $100$ training points.
That is $100$ distances; $k$ only decides how many of them we keep afterwards.
Answer: $100$
Common mistake: answering $k$, or $100-1$.

A careful note on "every prediction needs all distances"

In this course the basic algorithm is used, so every prediction computes all $n$ distances. Special data structures (like kd-trees) can avoid some computations in practice, but they are outside the syllabus; do not choose a statement that relies on them.

Trap: k is not the number of features

A very common wrong option: "$k$ is the number of features used". $k$ counts neighbours.

Compare the cost with numbers [ADDED]

Quantityk-NNLinear regression
Training worknone (storing the data)about $nd^2$ to form $XX^T$ and $d^3$ to solve
Prediction work$n$ distances, each about $d$ operations: about $nd$one dot product: about $d$
Memoryall $n$ points, $nd$ numbers$d$ weights
Depends on $k$?only to pick the $k$ smallest of the $n$ distancesno
$n$$d$k-NN prediction (about $nd$)Linear prediction (about $d$)
10022002
10,000220,0002
10,00050500,00050

Doubling $n$ doubles the cost of every k-NN prediction. That is the practical weakness of k-NN.

True-false drill [ADDED]

StatementTrue?Reason
Once trained, k-NN makes predictions without referring to the training dataFalsethe neighbours are found in the stored data
Every prediction does not require computing distances to all training points (basic algorithm)Falsethe basic algorithm computes all $n$ distances
The cost of prediction generally increases with the training-set sizeTruemore points, more distances
The distance metric can affect the predicted classTruesee the Euclidean and Manhattan picture
k-NN fits a probability modelFalseit only counts votes
A larger $k$ always improves accuracyFalsetoo large a $k$ underfits (see the LOOCV curve)

Recall questions

A model that needs all training points at prediction time is called...?

Non-parametric (in the PYQ definition).

Cost of one k-NN prediction in terms of $n$?

Proportional to $n$.

Tips and tricks
  • There is no training work beyond storing the data; the cost comes at prediction.
  • One query needs a distance to each of the $n$ training points.
Where k-NN spends time
training: store the dataquery arrivesn distances computedthe k nearest decide

7. k-NN regression: averaging the neighbours

Intuition

Everyday analogy

Estimating the price of a house by looking at the prices of the three most similar houses nearby and taking their average.

Formula: k-NN regression

$$\hat y(x)=\frac1k\sum_{i\in N_k(x)}y_i$$ $N_k(x)$ is the set of the $k$ nearest training points and $y_i$ their numeric labels. We average instead of voting.

Worked examples

Worked example: Simple: one feature

Problem. Training $(1,2),(2,4),(10,20)$ as $(x,y)$. Predict at $x=2.5$ with $k=2$.

What is asked. The prediction.

Idea / formula used. Two closest, average.

Distances: $1.5$, $0.5$, $7.5$.
Two nearest: $x=2$ and $x=1$ (distances $0.5$ and $1.5$) with $y=4$ and $y=2$.
Average $=(4+2)/2=3$.
Answer: $3$
Common mistake: including the far point $(10,20)$.
Worked example: Exam level: average of three neighbours

Problem. Points $(0,0),(1,3),(2,2),(4,4),(5,0),(4,5)$ with $y=2.0,3.1,4.0,6.4,5.0,7.2$. Test $(2,3)$, $k=3$.

What is asked. The predicted value.

Idea / formula used. Squared distances, sort, average the three smallest.

Squared distances in order: $13,1,1,5,18,8$.
Smallest three: the 2nd and 3rd points ($1$) and the 4th ($5$).
Average $=(3.1+4.0+6.4)/3=13.5/3$.
Answer: $4.5$
Common mistake: averaging the $y$ values of the first three listed points.
Worked example: Tricky: two points at the same distance

Problem. Test $(3,3)$; points $(3,4),(2,3),(3,1),(5,4),(6,6)$ with $y=5.0,4.0,3.0,7.0,9.0$; $k=3$.

What is asked. The prediction.

Idea / formula used. Rank by squared distance and check where ties fall.

Squared distances: $1,1,4,5,18$.
Two points tie at $1$; both are inside the three nearest.
The third is the point at $4$. The next is $5$, so there is no tie for the last place.
Average $=(5+4+3)/3$.
Answer: $4$
Common mistake: keeping only one of the tied points.

k-NN regression draws a staircase [ADDED]

012345678910110246810k = 3 (average of 3 nearest)k = 1 (copy the nearest)Both are flat between jumps (a staircase).k = 1 passes through every dot.
Eight points $(x,y)$. For $k=1$ the prediction copies the nearest label, so the curve passes through every dot and is flat between the midpoints of neighbouring $x$ values. For $k=3$ the prediction is the average of three labels, so it jumps less and is smoother. Both are step functions; the code checks that $k=1$ reproduces every training label.

A worked prediction from this data: at $x=4$ with $k=3$ the nearest are $x=3$ ($y=3.1$) and $x=5$ ($y=3.0$) at distance $1$, then a tie between $x=2$ and $x=6$ at distance $2$. Taking $x=2$ ($y=1.8$) by the order of the list gives $(3.1+3.0+1.8)/3=2.6333$. Had $x=6$ ($y=4.6$) been chosen the answer would be $(3.1+3.0+4.6)/3=3.5667$. This is exactly why a question that creates such a tie must say how to break it.

Classification against regression [ADDED]

ClassificationRegression
Outputa labela real number
Combine neighbours bymajority voteaverage
Even $k$ a problem?can tieno (an average always exists)
Boundary / curveregion boundariesstaircase of flat pieces
Typical errorfraction wrongsquared error or absolute error

Common mistakes, as a table [ADDED]

MistakeFix
Voting in regressionaverage
Dividing by $n$ instead of $k$divide the sum of the $k$ neighbour labels by $k$
Ignoring a tie at the $k$-th placeread the question for a rule

Recall questions

3-NN regression, neighbour labels $2,4,9$. Prediction?

$(2+4+9)/3=5$.

What does 1-NN regression predict at a training point?

Its own label.

Tips and tricks
  • Average the neighbours' target values; do not take a vote.
  • A prediction can never leave the range of the neighbours' values.
Memory line

Average the neighbours.

8. Leave-one-out cross-validation with k-NN, and changing labels

Intuition

Everyday analogy

To test whether a teacher's method works, hide one student's answer, predict it from the others, then compare with the real answer. Repeat for every student and count how many predictions are wrong.

Definition: Leave-one-out cross-validation (LOOCV)

For each training point $i$: remove it, run the model on the other $n-1$ points, predict the label of point $i$, and note whether the prediction is wrong. The LOOCV error is $\dfrac{\text{number of wrong predictions}}{n}$.

For k-NN this means: for each point, find its $k$ nearest neighbours among the other points (the point itself is excluded), vote, compare.

Worked example: Mar 2025 data

Worked example: Exam level: LOOCV for 3-NN

Problem. One feature: $x=1,2,3,6,7$ with labels $0,0,1,1,1$.

What is asked. The leave-one-out error with $k=3$.

Idea / formula used. Predict each point from its three nearest other points.

$x=1$: neighbours $2,3,6$ vote $0,1,1\to1$. Wrong.
$x=2$: neighbours $1,3,6$ vote $0,1,1\to1$. Wrong.
$x=3$: neighbours $2,1,6$ vote $0,0,1\to0$. Wrong.
$x=6$: neighbours $7,3,2$ vote $1,1,0\to1$. Right.
$x=7$: neighbours $6,3,2$ vote $1,1,0\to1$. Right.
Answer: error $3/5=0.6$
Common mistake: letting a point be its own neighbour.

Can changing labels reduce the error?

Yes. The error counts disagreements between a point and the vote of its neighbours. If we flip the label of point 7 to $0$, then points 5, 6 and 7 are predicted correctly, and the other four points are unaffected. In this data set the LOOCV error drops from $3/7$ to $0$. So the answer to "is it possible to reduce the error by changing the labels of certain points" is Yes.

Trap: train/validation split

In LOOCV the left-out point must not be among its own neighbours. In training-error questions the point is its own neighbour. Read the question to see which one is asked.

A complete small LOOCV, point by point [ADDED]

Six points on a line: $x=0,1,2$ with label $0$ and $x=10,11,12$ with label $1$. Using $k=3$, remove each point in turn and predict it from the other five.

Left outTrue label3 nearest others (position, label)VoteCorrect?
00(1, 0) (2, 0) (10, 1)0yes
10(0, 0) (2, 0) (10, 1)0yes
20(1, 0) (0, 0) (10, 1)0yes
101(11, 1) (12, 1) (2, 0)1yes
111(10, 1) (12, 1) (2, 0)1yes
121(11, 1) (10, 1) (2, 0)1yes

Zero mistakes, so the LOOCV error is $0/6=0$. Now repeat with $k=5$: each point's five neighbours are all other points, which hold $2$ of its own class and $3$ of the other.

Left outTrue labelVotes among the 5 othersVoteCorrect?
002 zeros, 3 ones1no
102 zeros, 3 ones1no
202 zeros, 3 ones1no
1013 zeros, 2 ones0no
1113 zeros, 2 ones0no
1213 zeros, 2 ones0no

Every prediction is wrong, so the LOOCV error is $6/6=1$. This is the same effect as $k=19$ on the toy data above. Take-away: "larger $k$" is not always better; pick $k$ by validation error.

Training error and LOOCV error side by side [ADDED]

Training errorLOOCV error
Is the point in its own neighbour set?yes (distance $0$)no (left out)
Value for $k=1$$0$ (no label clashes)can be large
Estimates performance on new data?no (optimistic)yes (nearly unbiased)
Cost$n$ predictions$n$ predictions, each from $n-1$ points

Can changing labels reduce the error? (the pattern of PYQ kn14) [ADDED]

Yes, in general. Using the toy data: the LOOCV error with $k=1$ is $0.15$ (three points are wrong). If we change the label of the outlier $(3,3)$ from red to blue, the 1-NN LOOCV error becomes 0.00 and the 3-NN error becomes 0.00. A label change removes the mistake at that point and also removes the damage that it did to the neighbours that used it. The question asks only whether it is possible; one example is enough to answer "Yes". (Your exam dataset decides the exact answer; always test by recomputing the LOOCV error for the changed label.)

Common mistakes, as a table [ADDED]

MistakeWhy it is wrongFix
Keeping the left-out point among the neighboursit would predict itselfdelete it first
Dividing the mistakes by $k$LOOCV divides by $n$errors over the number of points
Using only some pointsLOOCV uses every point onceloop over all $n$
Computing distances to the left-out point itselfdistance $0$ to itselfskip it

Recall questions

LOOCV makes how many predictions for $n$ points?

$n$, each from $n-1$ points.

Three of eight points are predicted wrongly in LOOCV. Error?

$3/8=0.375$.

Tips and tricks
  • Remove the point itself before looking for its neighbours.
  • When a label changes, recheck only the points that count it among their neighbours.
Memory line

Hide the point, then ask its neighbours.

Leave-one-out with k-NN
hide one pointfind its neighbours among the restpredict and compareaverage over all points

Practise this topic →

Weeks covering this topic

Other MLT topics