Visualized ML
Topics

C · Classic ML

k-Nearest Neighbours

No training at all: label a new point by a vote of the k training points closest to it.

Try it: C1 · k-Nearest Neighbours

Intuition

k-nearest neighbours (k-NN) may be the simplest learning method there is: to predict a new point, find the \(k\) training points closest to it and let them vote. There is no training step at all, only remembering the data. All the work happens at prediction time, and all the assumptions sit in two choices: which distance defines "closest", and how many neighbours \(k\) to ask.

The idea behind it is that similar inputs have similar outputs. That is the assumption every learning method makes in some form; k-NN just makes it directly, without fitting a formula.

A query point wanders over two classes. Lines join it to its \(k\) nearest neighbours, the dashed ring reaches the furthest of them, and the query takes the majority colour. The shaded background is the prediction at every point. With \(k = 1\) the boundary follows every stray point; with \(k = 15\) it is smooth.

The algorithm

Given training points \((\mathbf{x}_i, y_i)\) and a query \(\mathbf{x}\):

  1. Compute the distance \(d(\mathbf{x}, \mathbf{x}_i)\) to every training point.
  2. Take the \(k\) with the smallest distances: the neighbourhood \(N_k(\mathbf{x})\).
  3. Classification: predict the most common class among them, \(\hat y = \arg\max_c \sum_{i \in N_k} [y_i = c]\). Regression: predict their average, \(\hat y = \frac1k\sum_{i \in N_k} y_i\).

The fraction of neighbours in each class, such as 4 of 5, is a rough probability estimate.

Weighted voting

Closer neighbours can count more, typically with weight \(1/d\): \(\hat y = \arg\max_c \sum_{i \in N_k} [y_i = c]/d(\mathbf{x}, \mathbf{x}_i)\). This softens the jump when a neighbour enters or leaves the ring, and breaks ties.

Choosing k

\(k\) controls flexibility. \(k = 1\) memorizes: training error is zero, and the boundary bends around every mislabeled point. Large \(k\) averages over a wide area, smoothing out the noise but also real detail; at \(k = n\), every query gets the overall majority class. This is the bias-variance trade-off of regularization, with \(k\) as the knob. Pick it by cross-validation; for two classes an odd \(k\) avoids tied votes.

Worked example. Query \((2, 2)\). Training points: blue \((1, 2)\) and \((0, 0)\); orange \((3, 3)\), \((2, 4)\) and \((5, 2)\).

Distances: blue 1 and 2.83; orange 1.41, 2 and 3.

\(k = 1\): the nearest is blue \((1, 2)\), so blue. \(k = 3\): distances 1, 1.41 and 2, one blue and two orange, so orange. Weighted with \(1/d\): blue \(1\), orange \(0.71 + 0.5 = 1.21\), still orange.

Cost and speed

A naive prediction compares the query with all \(n\) training points in \(d\) dimensions: \(O(nd)\) per query, which is slow for millions of points. Space-partitioning trees (k-d trees, ball trees) skip whole regions that cannot contain a neighbour, which works well up to about 20 dimensions. Beyond that, approximate nearest-neighbour indexes (locality-sensitive hashing, graph-based HNSW) trade a little accuracy for great speed; they power vector databases and the retrieval step of many AI assistants.

Pitfalls

  • Unscaled features. The distance adds up raw differences, so a feature in thousands drowns one in single digits. Standardize first.
  • Irrelevant features. Every feature counts in the distance, useful or not; noise features scramble the neighbourhoods. Select features, or learn the distance.
  • High dimensions. As dimensions grow, all points become almost equally far apart and "nearest" stops meaning much (see Distance).
  • Imbalanced classes. A common class can outvote a rare one even close to the rare examples. Weighted votes or class weights help.
  • Memory. The whole training set is the model, and it must be kept and searched forever.

History

Evelyn Fix and Joseph Hodges described the nearest-neighbour rule in a 1951 US Air Force report. Thomas Cover and Peter Hart proved in 1967 that, with unlimited data, the 1-NN error rate is at most twice the best possible error rate, a striking guarantee for a method with no training. Jon Bentley invented the k-d tree in 1975.

Connections

Builds on

Further reading