k nearest neighbours
k nearest neighbours computed live: decision regions as k changes, each test point with its neighbours and distance ball, accuracy against k, and a 20,000-point decision grid on the GPU.
Updated
- Instance-based learning
- Distance metrics
- Choosing k: bias and variance
- Weighted voting
- Why k = 1 overfits
Intuition
Ask the neighbours
To guess which class a new point belongs to, look around it: if its surroundings are mostly blue, it is probably blue too. That is all KNN does — no model and no parameters to learn; the training data are the model.
The three small labs below really classify 120 test points one by one. The background is the prediction at each grid position (darker = more certain), small dots are training data, squares are test points already classified (red outline = wrong), the black circle is the latest test point and thin lines join it to its neighbours. All three use the same noisy data.
With every training point claims a patch around itself, including noisy points stranded inside another cluster; the boundary is fragmented and test accuracy is only 76.7% — while training accuracy is 100% (each point's nearest neighbour is itself). With isolated noisy points are outvoted, the boundary smooths out, and test accuracy reaches 90.8%. At it overshoots slightly: the boundary drifts towards the larger majority, 89.2%.
Math
The algorithm
Training data . For a query point :
- compute the distance from to every training point, ;
- take the smallest (ties broken by index) as ;
- vote: each neighbour adds votes to its class; the probability is , and the class with most votes is predicted.
Equal votes use ; distance weighting uses (if some neighbours are at distance 0, only they vote).
Distances
Points at equal distance from form a circle, a diamond and a square respectively — the "distance ball" drawn around the query in the lab. On the three clusters with they score 94.2%, 95.0% and 94.2% on the test set, little difference; with inconsistent feature scales the difference can be large, so features are usually standardised first.
Choosing k: bias and variance
A classifier has low bias (it can draw any boundary) and high variance (a different sample moves the boundary a lot); larger is smoother, trading variance for bias. The best on the three clusters at different noise levels:
| Noise | Best | Best accuracy | |
|---|---|---|---|
| 0.3 (default) | 89.2% | 7 | 95.8% |
| 0.6 | 76.7% | 20 | 90.8% |
| 1.0 | 66.7% | 48 | 84.2% |
The noisier the data, the more neighbours are needed to average the noise away. In practice is chosen by cross-validation — the lab's "Accuracy vs k" tab plots the whole curve for = 1 to 50.
Cost
KNN's "training" just stores the data; prediction computes distances to all training points, per query. For large data, use KD-trees, ball trees or approximate nearest-neighbour indexes. This page's "20k points" data computes the whole decision map on the GPU and spot-checks it against the CPU.
How it is computed, with real numbers
Once the lab above has loaded, this panel works through the same formulas with its current numbers.
Experiment
Follow the lesson
Course
Lesson 1: neighbours, votes and k
5 steps · each one: set up and run → look → answer
1. The first test point
Default three clusters with k = 5, one step. Look at the query, its 5 neighbours and the votes on the right.
2. k = 1
Noise 0.6, k = 1; classify all 120 test points.
3. Ask more neighbours
Set k to 20.
4. Accuracy versus k
Look at the two curves in the "Accuracy vs k" tab.
5. A different distance
Noise back at 0.3, distance set to Chebyshev. Look at the "distance ball" around the query.
Try these settings
The spiral makes the point vividly: test accuracy is 100% for and drops to 90.8% at — fifty nearest neighbours already include points from the adjacent arm.
Exercises
Exercises
Exercise 1: find a good k in the noise
Noise 0.6. Classify all test points and reach at least 90% test accuracy.
Hint
Look at the "Accuracy vs k" curve: k = 20 gives 90.8%. k = 1 gives only 76.7%.
- Test accuracy ≥ 90.0%
Exercise 2: squeeze out the last bit on clean data
The defaults reach 94.2%. Change k, the distance or the voting to reach 95% or more.
Hint
k = 7: 95.8%. Or keep k = 5 with Manhattan distance: 95.0%.
- Test accuracy ≥ 95.0%
Quiz
Further reading
Frequently asked questions
How do I choose k in k-nearest neighbours?
Use a validation set or cross-validation and pick the k with the best test accuracy; training accuracy is always 100% at k = 1 and cannot be used. Noisier data favour larger k. For two classes, an odd k avoids ties.
What are the strengths and weaknesses of KNN?
Strengths: simple, no training, boundaries of any shape, multi-class for free. Weaknesses: slow prediction (distances to every training point each time), sensitivity to feature scale and irrelevant features, and in high dimensions distances lose their contrast (the curse of dimensionality).
What is the difference between KNN and K-means?
KNN is supervised classification (or regression) and k is the number of neighbours; K-means is unsupervised clustering and k is the number of clusters. Similar names, unrelated methods.
What is distance-weighted voting for?
Closer neighbours are more trustworthy, so each votes 1/d. It helps with larger k near class boundaries, but also makes the result lean on individual close points. On this page's three clusters with k = 5, weighting actually scores slightly lower (92.5% against 94.2%).
Can KNN do regression?
Yes: predict the average (or distance-weighted average) of the k neighbours' targets.
Further reading
- Fix, Hodges, Discriminatory analysis. Nonparametric discrimination: consistency properties, 1951: the origin of the nearest-neighbour rule.
- Cover, Hart, Nearest neighbor pattern classification, 1967: 1-NN's error is at most twice the Bayes error.
- Hastie, Tibshirani, Friedman, The Elements of Statistical Learning, section 13.3: k-nearest-neighbour classifiers.
- scikit-learn, Nearest Neighbors user guide: this page's reference implementation.