Distances, k, classification and regression
Open the interactive lessons →k-NN past questions
Contents
- Orientation: what you will learn and why
- Big picture: concept map, model comparison and the recipe
- Start here: distance and voting
- The k-NN algorithm and how to run it
- Choosing k: smooth boundary, overfitting and training error
- Properties and cost: lazy, non-parametric, counting distances
- k-NN regression: averaging the neighbours
- 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
- Compute Euclidean (and Manhattan) distances and find the $k$ nearest neighbours of a test point by hand.
- Predict a class (majority vote) and a number (average of the neighbours' labels).
- Say how $k$ changes the decision boundary, the training error and the risk of overfitting.
- Count distance computations and list the true and false properties of k-NN (lazy, non-parametric, cost grows with data).
- Do leave-one-out cross-validation (LOOCV) for k-NN and reason about changing labels.
- Solve the geometry-style question where a new point is added and the prediction must not change.
Why this topic matters for Quiz 2
Counted only from the PYQs in this project (not a prediction):
| What the PYQs ask | PYQs | Marks |
|---|---|---|
| The k-NN algorithm and distances | 3 | 9 |
| Choosing k: smoothness and training error | 4 | 10 |
| Properties and cost | 3 | 8 |
| k-NN regression | 2 | 6 |
| LOOCV with k-NN and changing labels | 2 | 5 |
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.
Read each section, do the quick checks, then attempt each PYQ before opening its solution.
What is new in this upgrade [ADDED]
- A big picture section (next) with a concept map, a comparison with the other models of the course and a five-line recipe.
- Figures: decision regions for $k=1,5,9$, a worked neighbour picture, training error against LOOCV error, Euclidean against Manhattan, and the staircase of k-NN regression.
- Tables for ties and edge cases, feature scaling, costs, a point-by-point LOOCV, mistakes, recall questions and a flowchart. Everything new is tagged [ADDED].
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
k-NN next to the other models of this course
| k-NN | Linear regression | Kernel regression | Decision tree | Naive Bayes | |
|---|---|---|---|---|---|
| Training | none (stores data) | solve $XX^Tw=Xy$ | solve $K\alpha=y$ | grow a tree by entropy | count / estimate per class |
| Needs training points to predict? (PYQ definition) | yes | no | yes | no | no |
| Parametric? | no | yes | no | yes (tree) | yes |
| Cost of one prediction | $n$ distances | one dot product, $d$ | $n$ kernel values | follow one path | a product over features |
| Decision boundary | jagged to smooth, set by $k$ | one straight line / plane | curved | axis-parallel rectangles | straight or curved |
| Main knob | $k$ (and the metric) | none (or $\lambda$) | kernel and degree | depth / min leaf size | smoothing |
| Sensitive to feature scale? | yes, strongly | weights adjust | yes (dot products) | no | no |
The exam recipe, in five lines
- 1. Use squared distances; the order is the same and there is no square root.
- 2. Write one distance per training point, in a list. Do not skip a point.
- 3. Sort the list and take the first $k$.
- 4. Classification: majority label. Regression: mean of the labels.
- 5. For LOOCV, do steps 1 to 4 for every point after deleting that point, then count mistakes and divide by $n$.
Mnemonics and recognition cues [ADDED]
- "Small k = Spiky, Big k = Smooth." One neighbour copies noise; many neighbours average it away.
- "Self counts in training, not in LOO." Training error: a point is its own neighbour at distance $0$. LOOCV: the point is removed first.
- "n distances, whatever k." $k$ only decides how many you keep.
- "k is the crowd size, not the number of features."
- "Lazy" = does nothing until asked. "Non-parametric" = the data is the model.
- Cue "minimum number of training mistakes": think of the best data layout: tight clusters give $0$ for $k=1$ and $k=3$ alike.
Analogy and its limit [ADDED]
| Analogy | What it explains well | Where it breaks |
|---|---|---|
| Ask the $k$ nearest neighbours in a new city | voting, the role of $k$, why one odd neighbour matters less when $k$ is larger | real neighbours differ in trust; plain k-NN gives every neighbour exactly the same vote, however far away |
| Houses with similar features have similar prices | regression by averaging | if 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.
- 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
Walking across a field (straight line) against walking along city blocks.
Piece 1. Distance between two points
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$.
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
- Write each training point and its distance to the test point.
- Sort the distances from smallest to largest.
- Take the first $k$.
- Read their labels and vote (or average).
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]
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 dollars | 2000.00 | 104.40 | $P_2$ (income difference swamps age) |
| income in thousands | 2.236 | 30.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]
| Word | Meaning | Example |
|---|---|---|
| neighbour | one of the $k$ closest training points | $N_3(x)=\{7,19,4\}$ in the toy figure |
| majority vote | the label that most neighbours carry | 2 blue, 1 red: blue |
| tie | equal votes (possible only for even $k$ with two classes) | $k=2$, one of each |
| lazy learner | no work at training time | k-NN |
| hyperparameter | a 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$.
$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$.
Euclidean is straight; Manhattan adds the gaps.
4. The k-NN algorithm and how to run it
Intuition
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
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.
$$\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
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.
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.
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.
Common mistakes
- Using the distance to the wrong point (always subtract the test point from each training point).
- Forgetting that a point can be its own neighbour when the test point is a training point.
- Ties: when two points are at the same distance, check whether the tie affects the vote; often it does not (see the Mar 2025 PYQ).
A full run on a picture [ADDED]
Squared distances to the test point (all computed by the code, five smallest shown):
| Rank | Training point | Label | Squared distance |
|---|---|---|---|
| 1 | (4, 3.5) | blue | 0.45 |
| 2 | (3, 3) | red | 2.60 |
| 3 | (3, 4) | blue | 3.20 |
| 4 | (4, 1.5) | blue | 3.25 |
| 5 | (6, 2) | red | 3.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]
| Situation | What happens | What to do in an exam |
|---|---|---|
| Even $k$, two classes | a 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 place | more than $k$ points qualify | use the rule given in the question; otherwise say which neighbours you took and why |
| $k>n$ | not defined | use $k\le n$ |
| $k=n$ | every point is a neighbour, so the prediction is the overall majority | the same label for every test point |
| Duplicate training points with different labels | they tie as neighbours | count both votes |
| A test point equal to a training point | distance $0$, nearest neighbour is that point | for $k=1$ the prediction is its label |
Common mistakes, as a table [ADDED]
| Mistake | Why it is wrong | Fix |
|---|---|---|
| Comparing first coordinates only | distance uses all coordinates | compute the full distance for every point |
| Skipping a training point | it might be the nearest | list all $n$ distances before sorting |
| Taking the $k$ largest distances | the neighbours are the nearest | sort ascending |
| Square-rooting then comparing squared and unsquared values | mixing the two gives a wrong order | stay in squared distances for the ranking |
| Voting in a regression problem | regression predicts a number | take 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.
- Compare squared Euclidean distances to avoid square roots.
- Stop sorting once you have the $k$ nearest.
Distance, sort, take $k$, vote.
5. Choosing k: smooth boundary, overfitting and training error
Intuition
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$ | Boundary | Sensitive to outliers? | Risk |
|---|---|---|---|
| small (e.g. $1$) | jagged, follows every point | yes | overfit (low bias, high variance) |
| large | smooth, nearly straight or flat | no | underfit (high bias, low variance) |
| $k=n$ | predicts the overall majority everywhere | no | maximum underfit |
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.
- For $k=1$: every training point's only neighbour is itself, so the training error is $0$ (as long as no two identical points carry different labels).
- For $k=3$: a point is misclassified only if its two other neighbours both have the opposite label, so the votes are $1$ (itself) against $2$. The minimum possible number of training mistakes is $0$ (when each class forms tight clusters of at least two points).
- The maximum can be large when classes are mixed, so "what is the minimum" and "what is the maximum" have different answers.
Worked examples
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.
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.
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]
Error against $k$ [ADDED]
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 |
|---|---|---|
| 1 | it differs from itself (impossible, unless two identical points have different labels) | 0 |
| 3 | its 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 label | 0 |
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$ | Variance | Bias | Training error | LOOCV error |
|---|---|---|---|---|
| very small | high | low | lowest (0 at $k=1$) | can be high (noise) |
| moderate | medium | medium | small but non-zero | usually lowest |
| very large | low | high | high | high |
How to choose $k$ [ADDED]
- Try several odd values of $k$.
- For each, compute the cross-validation (or LOOCV) error, never the training error.
- Take the $k$ with the smallest validation error. If several tie, many practitioners prefer the larger $k$ (smoother, cheaper to defend), but follow any rule in the question.
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).
- With $k=1$ the training error is 0, unless identical points carry different labels.
- With $k=n$ every prediction is the overall majority class.
Small $k$ wiggles, large $k$ smooths.
6. Properties and cost: lazy, non-parametric, counting distances
A student who does no revision and looks everything up during the exam.
Properties (true / false list)
| Statement | True? | Reason |
|---|---|---|
| k-NN is a lazy learner | True | it does no work at training time; it just stores the data |
| k-NN needs the training data at prediction time | True | neighbours come from the stored data |
| k-NN is non-parametric | True | no fixed set of weights; the data itself is the model |
| $k$ is the number of features | False | $k$ is the number of neighbours |
| k-NN estimates probability distributions | False | it just votes, no distribution is fitted |
| The distance metric can change the prediction | True | different metrics give different nearest points |
| Prediction cost grows with the training-set size | True | more distances to compute |
| $k$ is a hyperparameter chosen by cross-validation | True | it is not learned by minimising training error |
Counting distance computations
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$.
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.
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.
A very common wrong option: "$k$ is the number of features used". $k$ counts neighbours.
Compare the cost with numbers [ADDED]
| Quantity | k-NN | Linear regression |
|---|---|---|
| Training work | none (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$ |
| Memory | all $n$ points, $nd$ numbers | $d$ weights |
| Depends on $k$? | only to pick the $k$ smallest of the $n$ distances | no |
| $n$ | $d$ | k-NN prediction (about $nd$) | Linear prediction (about $d$) |
|---|---|---|---|
| 100 | 2 | 200 | 2 |
| 10,000 | 2 | 20,000 | 2 |
| 10,000 | 50 | 500,000 | 50 |
Doubling $n$ doubles the cost of every k-NN prediction. That is the practical weakness of k-NN.
True-false drill [ADDED]
| Statement | True? | Reason |
|---|---|---|
| Once trained, k-NN makes predictions without referring to the training data | False | the neighbours are found in the stored data |
| Every prediction does not require computing distances to all training points (basic algorithm) | False | the basic algorithm computes all $n$ distances |
| The cost of prediction generally increases with the training-set size | True | more points, more distances |
| The distance metric can affect the predicted class | True | see the Euclidean and Manhattan picture |
| k-NN fits a probability model | False | it only counts votes |
| A larger $k$ always improves accuracy | False | too 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$.
- 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.
7. k-NN regression: averaging the neighbours
Intuition
Estimating the price of a house by looking at the prices of the three most similar houses nearby and taking their average.
$$\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
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.
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.
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.
k-NN regression draws a staircase [ADDED]
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]
| Classification | Regression | |
|---|---|---|
| Output | a label | a real number |
| Combine neighbours by | majority vote | average |
| Even $k$ a problem? | can tie | no (an average always exists) |
| Boundary / curve | region boundaries | staircase of flat pieces |
| Typical error | fraction wrong | squared error or absolute error |
Common mistakes, as a table [ADDED]
| Mistake | Fix |
|---|---|
| Voting in regression | average |
| Dividing by $n$ instead of $k$ | divide the sum of the $k$ neighbour labels by $k$ |
| Ignoring a tie at the $k$-th place | read 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.
- Average the neighbours' target values; do not take a vote.
- A prediction can never leave the range of the neighbours' values.
Average the neighbours.
8. Leave-one-out cross-validation with k-NN, and changing labels
Intuition
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.
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
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.
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.
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 out | True label | 3 nearest others (position, label) | Vote | Correct? |
|---|---|---|---|---|
| 0 | 0 | (1, 0) (2, 0) (10, 1) | 0 | yes |
| 1 | 0 | (0, 0) (2, 0) (10, 1) | 0 | yes |
| 2 | 0 | (1, 0) (0, 0) (10, 1) | 0 | yes |
| 10 | 1 | (11, 1) (12, 1) (2, 0) | 1 | yes |
| 11 | 1 | (10, 1) (12, 1) (2, 0) | 1 | yes |
| 12 | 1 | (11, 1) (10, 1) (2, 0) | 1 | yes |
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 out | True label | Votes among the 5 others | Vote | Correct? |
|---|---|---|---|---|
| 0 | 0 | 2 zeros, 3 ones | 1 | no |
| 1 | 0 | 2 zeros, 3 ones | 1 | no |
| 2 | 0 | 2 zeros, 3 ones | 1 | no |
| 10 | 1 | 3 zeros, 2 ones | 0 | no |
| 11 | 1 | 3 zeros, 2 ones | 0 | no |
| 12 | 1 | 3 zeros, 2 ones | 0 | no |
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 error | LOOCV 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]
| Mistake | Why it is wrong | Fix |
|---|---|---|
| Keeping the left-out point among the neighbours | it would predict itself | delete it first |
| Dividing the mistakes by $k$ | LOOCV divides by $n$ | errors over the number of points |
| Using only some points | LOOCV uses every point once | loop over all $n$ |
| Computing distances to the left-out point itself | distance $0$ to itself | skip 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$.
- Remove the point itself before looking for its neighbours.
- When a label changes, recheck only the points that count it among their neighbours.
Hide the point, then ask its neighbours.