Simple Algorithm
Machine Learning · Descent · 20 min

Nearest Neighbors

Predict like your neighbors: k-NN, distances and scaling.

k-nearest neighbors has no training phase and essentially one setting. Yet with enough data its error is within a factor of two of the best possible classifier, and with a slowly growing kk it reaches that optimum on every problem. This lesson makes the method precise: the rule and its ties, the choice of distance, kk as a bias–variance knob, the cost of a query, and the Cover–Hart bound.

What you’ll learn

  • State the k-NN classification and regression rules, with tie-breaking and distance-weighted votes.
  • Compare Euclidean, Manhattan, Chebyshev, cosine and Mahalanobis distances, and standardize features without leaking test data.
  • Derive the variance σ2/k\sigma^2/k of k-NN regression and its effective degrees of freedom n/kn/k, and choose kk by cross-validation.
  • Analyze the cost of a query, run a k-d tree search with pruning, and explain why trees fail in high dimensions.
  • Derive the Cover–Hart bound R⋆≤R1NN≤2R⋆(1−R⋆)R^\star \le R_{\mathrm{1NN}} \le 2R^\star(1 - R^\star).

The rule, precisely

Take a training set D={(xi,yi)}i=1n\data = \{(\mathbf x_i, y_i)\}_{i=1}^n and a distance ρ\rho on the inputs. For a query x\mathbf x, sort the training inputs by their distance to it, ρ(x,x(1))≤ρ(x,x(2))≤…\rho(\mathbf x, \mathbf x_{(1)}) \le \rho(\mathbf x, \mathbf x_{(2)}) \le \dots, and let Nk(x)N_k(\mathbf x) hold the indices of the first kk. The k-nearest-neighbor rules are

h^(x)=arg max⁡c ∑i∈Nk(x)1{yi=c}andf^(x)=1k∑i∈Nk(x)yi\hat h(\mathbf x) = \argmax_{c}\ \sum_{i \in N_k(\mathbf x)} \mathbf 1\{y_i = c\}\qquad\text{and}\qquad \hat f(\mathbf x) = \frac1k \sum_{i \in N_k(\mathbf x)} y_i
Classification by majority vote; regression by averaging. "Training" only stores D\data, so k-NN is the archetypal nonparametric method: the size of the model grows with the data.
text
KNN-PREDICT(query x, training set D, k, distance ρ)
  for i = 1..n:  dist[i] = ρ(x, x_i)
  N = indices of the k smallest dist      # quickselect: O(n), or a heap: O(n log k)
  if classification:
      count votes y_i for i in N
      if several classes tie: drop the farthest of N and recount   # or weight by distance
      return the winning class
  else:
      return mean of y_i for i in N

Two kinds of tie need a rule. Distance ties (two training points equally far away) are broken at random or by index. Vote ties cannot happen with two classes and odd kk, but they can with three or more classes; shrinking the vote to the nearer neighbors, or weighting votes by distance, resolves them.

With k=1k = 1 the rule partitions the input space into Voronoi cells: each training point owns the region closer to it than to any other. Under Euclidean distance the cells are convex polytopes, so the 1-NN decision boundary is built from pieces of the perpendicular bisectors between differently labeled points. Larger kk coarsens this mosaic.

A useful variant weights each neighbor's vote by a decreasing function of its distance, wi=K(ρ(x,xi)/h)w_i = K(\rho(\mathbf x, \mathbf x_i)/h), so the nearest neighbors count most; with all nn points weighted this way, the regression version becomes the Nadaraya–Watson estimator. (This KK is a smoothing window, not the positive-definite kernel of The Kernel Trick.)

Check your understanding

Why is an odd kk the usual choice for two-class k-NN, and does the same trick work with three classes?

  1. Odd kk is faster to compute, for any number of classes
  2. With two classes an odd number of votes cannot split evenly; with three classes ties are still possible, for example 2–2–1 with k=5k = 5
  3. Odd kk makes the decision boundary smooth
  4. It works for any number of classes: an odd count of votes can never tie
Show the answer

B. With two classes an odd number of votes cannot split evenly; with three classes ties are still possible, for example 2–2–1 with k=5k = 5

With two classes the votes split as jj and k−jk - j, which are unequal when kk is odd. With three classes, k=5k = 5 can split 2–2–1, so a tie-breaking rule is still needed.

Choosing the distance

k-NN is only as good as its notion of distance. The common choices, evaluated on x=(1,2,3)\mathbf x = (1, 2, 3) and z=(2,0,3)\mathbf z = (2, 0, 3):

DistanceFormulaValue on the exampleNotes
Euclidean ℓ2\ell_2∑j(xj−zj)2\sqrt{\sum_j (x_j - z_j)^2}5≈2.24\sqrt5 \approx 2.24the default; rotation-invariant
Manhattan ℓ1\ell_1∑j∣xj−zj∣\sum_j \lvert x_j - z_j\rvert33less dominated by one large coordinate difference
Chebyshev ℓ∞\ell_\inftymax⁡j∣xj−zj∣\max_j \lvert x_j - z_j\rvert22only the worst coordinate counts
Cosine distance1−x⊤z∥x∥∥z∥1 - \dfrac{\mathbf x^\top\mathbf z}{\norm{\mathbf x}\norm{\mathbf z}}1−111413≈0.1851 - \tfrac{11}{\sqrt{14}\sqrt{13}} \approx 0.185ignores length: text, embeddings
Mahalanobis(x−z)⊤M(x−z)\sqrt{(\mathbf x - \mathbf z)^\top M(\mathbf x - \mathbf z)}, M⪰0M \succeq 0depends on MMM=Σ−1M = \Sigma^{-1} whitens correlated features; a learned MM is metric learning
Cosine "distance" violates the triangle inequality, so it is not a metric in the strict sense; for ranking neighbors that rarely matters.
DerivationCosine neighbors are Euclidean neighbors of normalized vectors
  1. ∥x^−z^∥2=∥x^∥2+∥z^∥2−2 x^⊤z^=2−2cos⁡θ(x,z)\lVert\hat{\mathbf x} - \hat{\mathbf z}\rVert^2 = \lVert\hat{\mathbf x}\rVert^2 + \lVert\hat{\mathbf z}\rVert^2 - 2\,\hat{\mathbf x}^\top\hat{\mathbf z} = 2 - 2\cos\theta(\mathbf x, \mathbf z)

    Scale every vector to unit length, x^=x/∥x∥\hat{\mathbf x} = \mathbf x/\norm{\mathbf x}, and expand the squared Euclidean distance:

  2. cos⁡θ(x,z)≥cos⁡θ(x,z′)  ⟺  ∥x^−z^∥≤∥x^−z^′∥\cos\theta(\mathbf x, \mathbf z) \ge \cos\theta(\mathbf x, \mathbf z') \iff \lVert\hat{\mathbf x} - \hat{\mathbf z}\rVert \le \lVert\hat{\mathbf x} - \hat{\mathbf z}'\rVert

    This is an increasing function of the cosine distance 1−cos⁡θ1 - \cos\theta, so both rank all candidates in the same order: Euclidean k-NN on normalized vectors is cosine k-NN. On the example, 2−2(0.815)≈0.3692 - 2(0.815) \approx 0.369. This is why vector search engines often normalize embeddings and use fast Euclidean or inner-product search.

Scale. Every distance above adds up differences measured in each feature's own units, so a feature with a large numeric range dominates. Standardize each feature, xj↦(xj−μj)/sjx_j \mapsto (x_j - \mu_j)/s_j, with the mean μj\mu_j and standard deviation sjs_j estimated on the training data only and inside every cross-validation fold; computing them on all the data leaks information from the test set.

Relevance. Standardizing makes every feature count equally, which is wrong when some features are irrelevant: each irrelevant feature adds noise to every distance. A Mahalanobis distance with M=L⊤LM = L^\top L is the Euclidean distance after the linear map LL, so learning LL from labels, to pull same-class neighbors together and push others away, is a principled fix. That is metric learning, the subject of Metric Learning & Fast Neighbor Search.

k as a bias–variance knob

Consider regression with fixed training inputs and yi=f(xi)+εiy_i = f(\mathbf x_i) + \varepsilon_i, where the noise has mean 00 and variance σ2\sigma^2. Fix a query x0\mathbf x_0 and its neighbors x(1),…,x(k)\mathbf x_{(1)}, \dots, \mathbf x_{(k)}. Only the noise is random.

DerivationThe error of k-NN regression at a point
  1. E f^(x0)=1k∑ℓ=1kf(x(ℓ)),Var⁡ f^(x0)=1k2∑ℓ=1kVar⁡(ε(ℓ))=σ2k\E\,\hat f(\mathbf x_0) = \frac1k\sum_{\ell=1}^k f(\mathbf x_{(\ell)}),\qquad \Var\,\hat f(\mathbf x_0) = \frac1{k^2}\sum_{\ell=1}^k \Var(\varepsilon_{(\ell)}) = \frac{\sigma^2}{k}

    The prediction averages kk noisy labels, so its mean and variance are

  2. E[(y0−f^(x0))2]=σ2+[f(x0)−1k∑ℓ=1kf(x(ℓ))]2+σ2k\E\big[(y_0 - \hat f(\mathbf x_0))^2\big] = \sigma^2 + \Big[f(\mathbf x_0) - \frac1k\sum_{\ell=1}^k f(\mathbf x_{(\ell)})\Big]^2 + \frac{\sigma^2}{k}

    A new label at x0\mathbf x_0 carries its own independent noise, so the expected squared error splits into noise, squared bias and variance:

  3. Larger kk divides the variance by kk but reaches for farther neighbors, whose ff values drift from f(x0)f(\mathbf x_0): the bias grows. With more data, neighbors at fixed kk move closer, so the bias shrinks while the variance stays σ2/k\sigma^2/k.

k-NN regression is a linear smoother: y^=Sy\hat{\mathbf y} = S\mathbf y, where row ii of SS puts weight 1/k1/k on each of the kk neighbors of xi\mathbf x_i. Each training point is its own nearest neighbor, so Sii=1/kS_{ii} = 1/k and the effective degrees of freedom are tr⁡S=n/k\operatorname{tr}S = n/k. With n=1,000n = 1{,}000 and k=10k = 10, k-NN behaves roughly like a model with 100 parameters; with k=1k = 1, like one parameter per data point.

Check your understanding

You keep k=15k = 15 fixed and double the number of training points. Which part of k-NN regression's error changes, according to the derivation?

  1. The variance halves, because there is twice as much data
  2. Both bias and variance stay the same, because kk did not change
  3. The squared bias shrinks, because the 15 neighbors now lie closer to the query; the variance stays σ2/15\sigma^2/15
  4. The noise σ2\sigma^2 halves
Show the answer

C. The squared bias shrinks, because the 15 neighbors now lie closer to the query; the variance stays σ2/15\sigma^2/15

The variance is σ2/k\sigma^2/k whatever nn is. More data packs the training inputs more densely, so the same number of neighbors covers a smaller region, where ff varies less: the bias falls. That is why the best kk grows with nn.

In practice, choose kk (and the weighting) by cross-validation. Theory says how kk should scale: for consistency, k→∞k \to \infty but k/n→0k/n \to 0. For a Lipschitz regression function in d≥3d \ge 3 dimensions, the squared bias is of order (k/n)2/d(k/n)^{2/d}; balancing it against σ2/k\sigma^2/k gives k∝n2/(d+2)k \propto n^{2/(d+2)} and an error of order n−2/(d+2)n^{-2/(d+2)}. The exponent's dependence on dd is the curse of dimensionality, made precise in The Curse of Dimensionality.

Making queries fast

A brute-force query computes nn distances in dd dimensions, O(nd)\order{nd} work, then selects the kk smallest in O(n)\order{n} time (quickselect) or O(nlog⁡k)\order{n\log k} (a heap). Memory is O(nd)\order{nd}: the whole training set. For a million points with 100 features that is 10810^8 multiply-adds for every single query, a cost that adds up quickly when queries arrive by the thousands.

A k-d tree (Bentley, 1975) organizes the points in advance. Each internal node splits its points at the median of one coordinate, cycling through the coordinates or choosing the one with the largest spread, until the leaves hold a few points each. Building it takes O(nlog⁡n)\order{n\log n} time.

text
KD-SEARCH(node, query x, k)          # best = max-heap of the k nearest found so far
  if node is a leaf:
      update best with the points in the leaf;  return
  j, s = node.split_coordinate, node.split_value
  near, far = (node.left, node.right) if x[j] <= s else (node.right, node.left)
  KD-SEARCH(near, x, k)
  r = distance to the k-th best so far (infinity if fewer than k found)
  if |x[j] - s| < r:                # the ball around x crosses the splitting plane
      KD-SEARCH(far, x, k)           # otherwise the whole far side is pruned

Descend to the query's leaf, then backtrack, opening the other side of a split only when the current kk-th-nearest distance reaches across the splitting plane. The result is exact, not approximate.

Predict before you look

A k-d tree is built over n=106n = 10^6 points by median splits until each leaf holds a single point. About how deep is it?

Show the answer

20 levels

Each median split halves the points, so the depth is ⌈log⁡2106⌉=20\lceil\log_2 10^6\rceil = 20. Reaching the query's leaf costs only 20 comparisons; the real cost is the backtracking, which depends on the dimension.

In low dimensions the ball around the query rarely crosses a splitting plane, so most of the tree is pruned, and Friedman, Bentley and Finkel (1977) showed that the expected search time grows only logarithmically in nn for a fixed dimension, with constants that grow exponentially in dd. In high dimensions the ball of radius rr around the query crosses most splitting planes, the far side can almost never be pruned, and the search degenerates toward a linear scan. Weber, Schek and Blott (1998) found that, for data spread uniformly, tree and partitioning indexes were beaten by a plain sequential scan once the dimension exceeded about 10. Ball trees and cover trees adapt better to data with low intrinsic dimension; beyond that, practical systems give up exactness and use approximate search.

python
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import GridSearchCV

pipe = make_pipeline(StandardScaler(), KNeighborsClassifier(algorithm='kd_tree'))
grid = {
    'kneighborsclassifier__n_neighbors': [1, 3, 5, 9, 15, 25, 45],
    'kneighborsclassifier__weights': ['uniform', 'distance'],
}
search = GridSearchCV(pipe, grid, cv=5)   # the scaler is refit inside every fold
search.fit(X_train, y_train)
print(search.best_params_)
print(search.score(X_test, y_test))       # the test set is used once, at the end

Putting the scaler inside the pipeline is what keeps cross-validation honest: each fold standardizes with its own training statistics. weights='distance' gives each neighbor a vote proportional to the inverse of its distance.

How good can nearest neighbors get?

Take two classes, y∈{0,1}y \in \{0, 1\}, and let η(x)=P(y=1∣x)\eta(\mathbf x) = P(y = 1 \mid \mathbf x). The Bayes classifier predicts the likelier class and errs with probability r(x)=min⁡{η(x),1−η(x)}r(\mathbf x) = \min\{\eta(\mathbf x), 1 - \eta(\mathbf x)\} at x\mathbf x, so the Bayes error is R⋆=E r(x)R^\star = \E\,r(\mathbf x). No classifier does better. How close does the humble 1-NN rule come?

DerivationWhy the nearest neighbor is worth half the information
  1. P(y≠y′∣x,x′)=η(x)(1−η(x′))+η(x′)(1−η(x))P(y \ne y' \mid \mathbf x, \mathbf x') = \eta(\mathbf x)\big(1 - \eta(\mathbf x')\big) + \eta(\mathbf x')\big(1 - \eta(\mathbf x)\big)

    Let x′\mathbf x' be the nearest training input to the query x\mathbf x, with label y′y'. Given the inputs, yy and y′y' are independent, and the rule errs exactly when they differ:

  2. P(y≠y′∣x,x′)  →  2η(x)(1−η(x))=2r(x)(1−r(x))P(y \ne y' \mid \mathbf x, \mathbf x') \;\to\; 2\eta(\mathbf x)\big(1 - \eta(\mathbf x)\big) = 2r(\mathbf x)\big(1 - r(\mathbf x)\big)

    As nn grows, x′→x\mathbf x' \to \mathbf x. If η\eta is continuous, η(x′)→η(x)\eta(\mathbf x') \to \eta(\mathbf x), and since η(1−η)=r(1−r)\eta(1-\eta) = r(1-r):

  3. 2r(1−r)≥r⟹R1NN≥E r=R⋆2r(1-r) \ge r \quad\Longrightarrow\quad R_{\mathrm{1NN}} \ge \E\,r = R^\star

    Lower bound. Because r≤12r \le \tfrac12, we have 1−r≥121 - r \ge \tfrac12, so 2r(1−r)≥r2r(1 - r) \ge r pointwise; take expectations to get R1NN≥R⋆R_{\mathrm{1NN}} \ge R^\star.

  4. R1NN=2E[r]−2E[r2]  ≤  2R⋆−2(R⋆)2=2R⋆(1−R⋆)R_{\mathrm{1NN}} = 2\E[r] - 2\E[r^2] \;\le\; 2R^\star - 2(R^\star)^2 = 2R^\star(1 - R^\star)

    Upper bound. Expand and use Jensen's inequality, E[r2]≥(Er)2=(R⋆)2\E[r^2] \ge (\E r)^2 = (R^\star)^2. Equality holds when r(x)r(\mathbf x) is constant, for example when labels are flipped with the same probability everywhere, so the bound is tight.

Predict before you look

A two-class problem has Bayes error R⋆=10%R^\star = 10\%. With unlimited data, at most what error can the 1-NN rule have?

Show the answer

18 %

2R⋆(1−R⋆)=2(0.1)(0.9)=0.182R^\star(1 - R^\star) = 2(0.1)(0.9) = 0.18. In the worst case the nearest neighbor's label is itself noisy, so two coin flips must agree. One way to read the result: a single neighbor already delivers at least half of what an infinite sample could, in the sense that it at most doubles the unavoidable error.

Fixed kk cannot close the remaining gap: a vote of kk noisy labels stays noisy however much data arrives. Letting kk grow with nn does close it. Stone (1977) proved that k-NN is universally consistent: if k→∞k \to \infty and k/n→0k/n \to 0, its error converges to R⋆R^\star for every distribution on Rd\R^d. There is a catch: no rule, k-NN included, converges at a guaranteed rate for every distribution, and in high dimensions the convergence can be very slow.

Key takeaways

  • k-NN predicts by a majority vote (classification) or an average (regression) of the kk nearest training points; ties need explicit rules, and distance weighting is a common refinement.
  • The distance is the model: standardize features using training statistics only, prefer cosine (or normalized Euclidean) for embeddings, and consider a learned Mahalanobis metric when features differ in relevance.
  • At fixed inputs, k-NN regression has variance σ2/k\sigma^2/k and effective degrees of freedom n/kn/k; bias grows with kk and shrinks with nn, so the best kk grows with nn.
  • Brute-force search costs O(nd)\order{nd} per query. k-d trees prune by splitting planes and are fast in low dimensions, but on data that fill the space they degrade toward a linear scan beyond roughly ten dimensions.
  • With unlimited data, 1-NN's error lies between R⋆R^\star and 2R⋆(1−R⋆)2R^\star(1 - R^\star); letting k→∞k \to \infty with k/n→0k/n \to 0 reaches R⋆R^\star for every distribution (Stone, 1977).

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

You standardize every feature with the mean and standard deviation of the whole dataset, then split it into training and test sets for k-NN. What is wrong?

  1. Nothing: standardization uses no labels, so it cannot leak
  2. The test set's statistics have shaped the training features, a mild form of data leakage; fit the scaler on the training data only
  3. k-NN should never be used with standardized features
  4. The test set must be standardized with its own mean and standard deviation instead
Show the answer

B. The test set's statistics have shaped the training features, a mild form of data leakage; fit the scaler on the training data only

Any statistic computed from the test set and used in training lets it influence the model, so the test score is no longer measured on truly unseen data. Fit the scaler on the training set (inside every cross-validation fold) and apply the same transformation to new points. With large datasets the effect is usually small, but it is a leak, and with small or shifted datasets it can matter.

Question 2

All vectors are scaled to unit length. How do the neighbors found by Euclidean distance compare with those found by cosine similarity?

  1. They are identical, because ∥x^−z^∥2=2−2cos⁡θ\lVert\hat{\mathbf x} - \hat{\mathbf z}\rVert^2 = 2 - 2\cos\theta
  2. They differ, because Euclidean distance also measures length
  3. They are identical only in two dimensions
  4. They are opposite: the Euclidean nearest is the cosine farthest
Show the answer

A. They are identical, because ∥x^−z^∥2=2−2cos⁡θ\lVert\hat{\mathbf x} - \hat{\mathbf z}\rVert^2 = 2 - 2\cos\theta

For unit vectors the squared distance is a decreasing function of the cosine, so both orderings agree for every query.

Question 3

k-NN regression is fitted to n=600n = 600 points with k=12k = 12. What are its effective degrees of freedom tr⁡S\operatorname{tr}S?

  1. 12
  2. 600
  3. 50
  4. 7,200
Show the answer

C. 50

Each training point is its own nearest neighbor, so every diagonal entry of the smoother matrix is 1/k1/k, and tr⁡S=n/k=600/12=50\operatorname{tr}S = n/k = 600/12 = 50. Smaller kk means more effective parameters.

Question 4

A k-d tree answers exact 3-NN queries on 2-D data almost instantly, but on 200-dimensional embeddings it is barely faster than brute force. Why?

  1. Building the tree takes longer in high dimensions
  2. The tree has too few levels to hold 200 coordinates
  3. In high dimensions the search ball around the query crosses most splitting planes, so few branches can be pruned
  4. k-d trees only support Manhattan distance
Show the answer

C. In high dimensions the search ball around the query crosses most splitting planes, so few branches can be pruned

The speed-up comes entirely from pruning: skipping a subtree whose region lies farther than the current kk-th-nearest distance. In high dimensions even the nearest neighbors are far away and the region boundaries are close in at least some coordinates, so the pruning test almost always fails and the search visits most leaves.

Question 5

A two-class problem has Bayes error 5%. What does the Cover–Hart bound say about the 1-NN rule with unlimited data?

  1. Its error will be exactly 5%
  2. Its error is between 5% and 9.5%
  3. Its error is at most 2.5%
  4. Nothing, because the bound needs the distribution to be Gaussian
Show the answer

B. Its error is between 5% and 9.5%

R⋆≤R1NN≤2R⋆(1−R⋆)=2(0.05)(0.95)=0.095R^\star \le R_{\mathrm{1NN}} \le 2R^\star(1 - R^\star) = 2(0.05)(0.95) = 0.095. The lower bound holds for every classifier; the upper bound says the neighbor's own label noise at most roughly doubles the error.

Go deeper

Further reading

  • T. M. Cover & P. E. Hart, "Nearest neighbor pattern classification," IEEE Transactions on Information Theory 13(1), 21–27 (1967).
  • J. H. Friedman, J. L. Bentley & R. A. Finkel, "An algorithm for finding best matches in logarithmic expected time," ACM Transactions on Mathematical Software 3(3), 209–226 (1977).
  • T. Hastie, R. Tibshirani & J. Friedman, The Elements of Statistical Learning, 2nd ed. (Springer, 2009), sections 2.3, 7.6 and chapter 13.
  • G. Biau & L. Devroye, Lectures on the Nearest Neighbor Method (Springer, 2015).