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
0 / 71 / 72 / 73 / 74 / 75 / 76 / 77 / 7vote 0 : 2 : 5k = 7
Preparing the lab…

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 kk neighbours. All three use the same noisy data.

k = 1Preparing…
k = 20Preparing…
k = 50Preparing…

With k=1k = 1 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 k=20k = 20 isolated noisy points are outvoted, the boundary smooths out, and test accuracy reaches 90.8%. At k=50k = 50 it overshoots slightly: the boundary drifts towards the larger majority, 89.2%.

Math

The algorithm

Training data {(xi,yi)}\{(x_i, y_i)\}. For a query point qq:

  1. compute the distance from qq to every training point, di=d(q,xi)d_i = d(q, x_i);
  2. take the kk smallest (ties broken by index) as Nk(q)N_k(q);
  3. vote: each neighbour adds wiw_i votes to its class; the probability is p^c=∑i∈Nk,yi=cwi/∑i∈Nkwi\hat p_c = \sum_{i\in N_k, y_i = c} w_i \big/ \sum_{i\in N_k} w_i, and the class with most votes is predicted.

Equal votes use wi=1w_i = 1; distance weighting uses wi=1/diw_i = 1/d_i (if some neighbours are at distance 0, only they vote).

Distances

Euclidean ∑j(qj−xj)2,Manhattan ∑j∣qj−xj∣,Chebyshev max⁡j∣qj−xj∣\text{Euclidean}\ \sqrt{\textstyle\sum_j (q_j - x_j)^2},\qquad \text{Manhattan}\ \textstyle\sum_j |q_j - x_j|,\qquad \text{Chebyshev}\ \max_j |q_j - x_j|

Points at equal distance from qq form a circle, a diamond and a square respectively — the "distance ball" drawn around the query in the lab. On the three clusters with k=5k = 5 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 k=1k = 1 classifier has low bias (it can draw any boundary) and high variance (a different sample moves the boundary a lot); larger kk is smoother, trading variance for bias. The best kk on the three clusters at different noise levels:

Noisek=1k = 1Best kkBest accuracy
0.3 (default)89.2%795.8%
0.676.7%2090.8%
1.066.7%4884.2%

The noisier the data, the more neighbours are needed to average the noise away. In practice kk is chosen by cross-validation — the lab's "Accuracy vs k" tab plots the whole curve for kk = 1 to 50.

Cost

KNN's "training" just stores the data; prediction computes distances to all nn training points, O(nd)O(nd) 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. 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.

    Why is this point classified as class A?
  2. 2. k = 1

    Noise 0.6, k = 1; classify all 120 test points.

    With k = 1 training accuracy is 100% but test accuracy only 76.7%. Why?
  3. 3. Ask more neighbours

    Set k to 20.

    Why does accuracy rise to 90.8%?
  4. 4. Accuracy versus k

    Look at the two curves in the "Accuracy vs k" tab.

    The training curve falls from 100% at k = 1 while the test curve rises then falls. Where is the best k?
  5. 5. A different distance

    Noise back at 0.3, distance set to Chebyshev. Look at the "distance ball" around the query.

    What shape is a Chebyshev ball?

Try these settings

The spiral makes the point vividly: test accuracy is 100% for k≤15k \le 15 and drops to 90.8% at k=50k = 50 — 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

What does KNN do in its “training” phase?
As the data get noisier, the best k usually…
One feature is in metres (0–2), another in millimetres (0–2000). What happens if you leave them as they are?

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