The nearest labelled students vote
k-nearest neighbours predicts a class for a new point from the labelled points closest to it. Quiz score and project score are the two features. Pass and Needs support are the two classes. The eight students are the training examples: each one already has a class. Ari does not.
The stored students are the model. A prediction does three things:
- Measure the straight-line distance from Ari to every labelled student:
√((quiz difference)² + (project difference)²). - Keep the k nearest.
kis how many neighbours vote. - Take a majority vote. Ari gets the class that most of those neighbours have.
Ari starts at quiz 4 and project 5. With k = 3, Pat (Pass, distance 1.41), Mei (Needs support, 2.83), and Jo (Needs support, 3.16) vote. Needs support has 2 votes and Pass has 1, so the prediction is Needs support.
Set k to 1 and only Pat votes, so the prediction becomes Pass. A small k follows one neighbour, including a neighbour who sits away from the rest of their class. With k = 7 the prediction is Pass again: four of those seven students passed, and the far students outvote the ones nearby. When the two classes have the same number of votes, the vote is a tie, and the nearest neighbour’s class is used. k = 2 and k = 6 are ties for this start, and both resolve to Pass because Pat is nearest.
Go deeper
k-nearest neighbours is a lazy learner. Nothing is fitted in advance. Every new student is compared with every stored student, so prediction slows down as the training set grows. With two classes, an odd k cannot tie. If one feature were out of 100 and the other out of 10, the larger scale would decide almost every neighbour, so the features would need to be put on a similar range first.
| Student | Quiz | Project | Class |
|---|---|---|---|
| Mei | 2 | 3 | Needs support |
| Ali | 3 | 1 | Needs support |
| Jo | 1 | 4 | Needs support |
| Pat | 5 | 6 | Pass |
| Kai | 6 | 9 | Pass |
| Lee | 7 | 8 | Pass |
| Noor | 9 | 7 | Pass |
| Sam | 8 | 9 | Pass |
Ari is the new student, at quiz 4 and project 5. Pat passed, and Pat’s scores sit near students who need support.
Let the neighbours vote
Drag Ari, or change k. Before you move the slider, guess whether k = 1 gives the same class as k = 3.
Distance, then a vote
The class comes from the neighbours, and the choice of k changes who those neighbours are.
Distance
The distance is the straight line between two points. Square each feature gap, add them, then take the square root.
Majority vote
Each of the k nearest students votes for their own class. The class with more votes is the prediction.
Choice of k
A small k follows one nearby student. A large k lets distant students outvote the ones close to Ari.