k-Nearest Neighbors

The k-nearest neighbors method (k-NN) predicts the output at a query from the training points closest to it. It stores the training set , , and fits no parameters. Let be the indices of the training inputs nearest to under a distance . Here counts neighbors, so classes are indexed by . Classification takes a majority vote, and regression takes an average:

Here is the predicted class and the predicted number. The vote fractions estimate the class probabilities. The vote is therefore a plug-in version of the Bayes classifier. A weighted variant gives neighbor the weight . Five distances are common:

  • Euclidean: , the default for continuous features.
  • Manhattan: , less sensitive to one large coordinate difference.
  • Minkowski: , which contains both as and (3.5b p-Norm).
  • Cosine: , for text and embeddings, where direction matters more than length.
  • Hamming: the number of coordinates that differ, for categorical or binary features.

The choice of sets the bias-variance tradeoff:

  • : zero training error when inputs are distinct, and high variance. Each training point decides every query in its own Voronoi cell.
  • Large : smoother predictions and higher bias. At every query gets the majority class or the global mean.
  • In practice: choose by cross-validation, and use odd in binary problems to avoid tied votes.

Features must be on comparable scales, so standardize them first. As , the 1-NN error rate satisfies , where is the Bayes error (Cover and Hart 1967). Training costs nothing, and a brute-force prediction costs per query.

Intuition

The method assumes that inputs close to each other tend to have similar outputs. To label a new patient, it finds the most similar past patients and lets them vote. Nothing is computed before a query arrives, so k-NN is called a lazy or instance-based learner. It is also nonparametric. The model is the training set itself, so its flexibility grows with .

With , each training point decides every query in its Voronoi cell. This cell is the region of inputs closer to that point than to any other training point. The 1-NN boundary consists of the cell faces that separate points of different classes. Larger averages over more points and smooths this boundary. ISLR ch. 2 and ESL ch. 2 and 13 treat the method in detail.

Properties

(k Sets Bias and Variance) In k-NN regression the variance falls as , while the bias tends to grow with .

Fix the training inputs and let with noise variance . Write for the -th nearest neighbor of a query . The expected squared error at splits into three terms (ESL eq. 7.10):

The first term is the irreducible noise. The second is the squared bias, which grows as farther neighbors with different values of enter the average. The third is the variance of an average of independent noise terms. The effective number of parameters of k-NN is about . With and , the method behaves like a model with parameters. 2.3.1. Bias-Variance Decomposition derives the general decomposition.

(Twice the Bayes Error) With unlimited data, 1-NN makes at most twice as many errors as the best possible classifier.

As , the nearest neighbor of converges to . Its label then behaves like an independent draw from the same conditional distribution. For two classes, write . The 1-NN rule errs when the query’s label and the neighbor’s label differ, with probability . The Bayes rule errs with probability . Since , averaging over gives the factor . The full result for classes is

(Cover and Hart 1967). If and , the k-NN error converges to for every distribution (Stone 1977). Both results are asymptotic. At finite in high dimensions, the nearest neighbor can be far from the query, and neither result applies.

(Scale and Irrelevant Features) The distance weighs every feature equally, so units and useless features change which points count as neighbors.

A feature measured in large units dominates the Euclidean distance. In the Medium example, floor area in square meters outweighs bedroom count until both are standardized. Irrelevant features add random differences to every distance. The nearest points in the full space then differ from the nearest points in the relevant features. With many useless features, k-NN needs far more data than a method that can ignore them. Remedies include feature selection and learning a Mahalanobis distance with positive semidefinite. Large-margin nearest neighbors (Weinberger and Saul 2009) learns from labeled data.

(Curse of Dimensionality) In high dimensions the nearest training points lie far from the query, and k-NN needs exponentially many samples.

Take uniform data in the unit cube. A cubical neighborhood that holds a fraction of the points needs edge length . In dimensions, capturing of the data needs of each feature’s range (ESL 2.5). The average over such a neighborhood mixes points with very different values of , so the bias term above grows. Distances also concentrate, so the nearest and the farthest training points lie at nearly the same distance. k-NN works in high dimensions only when the data lie near a low-dimensional set. Images and text embeddings often do. 7.2. Curse of Dimensionality treats these effects in full.

Each query computes distances in time and selects the smallest in time. The model also stores all training points. A KD-tree (Bentley 1975) cuts query time to about in low dimensions, but not beyond about dimensions. Large systems use approximate nearest-neighbor search, which returns close points that are not always the closest. Descriptor matching in computer vision uses such search. Leave-one-out cross-validation is cheap for k-NN. Removing a point only means excluding it from its own neighbor list, so no model is refit.

Examples

(Easy) Voting on a New Patient

A clinic records two standardized measurements per patient. Five past patients are sick at , and , and healthy at and . A new patient measures .

(Medium) House Prices Before and After Scaling

An agent predicts the price of a m², 3-bedroom house with 3-NN regression. Six recent sales, as (area, bedrooms, price), are , , , , and . Prices are in thousands of dollars.

(Hard) Asymptotic Error in a Noisy Region

A screening program classifies patients by a health profile. In one region of profiles, of patients are sick, so throughout the region. The training set is very large. The nearest neighbors of any query in the region are then independent patients with the same .

See Also