Module contents
Lesson 10 of 24Core 85 min

k-nearest neighbors and the curse of dimensionality

Introduces the simplest nonparametric method and uses it to explain the Cover–Hart bound (1-NN asymptotically has at most twice the Bayes error), the role of metric and scaling, and the curse of dimensionality as distance concentration. Implements efficient exact search with KD trees and ball trees and analyzes when they stop working.

After this lesson you can

  • Implement vectorized k-NN classification and regression with distance weights.
  • State and outline a proof of the asymptotic Cover–Hart bound.
  • Choose k as a smoothness control and diagnose it with validation curves.
  • Demonstrate distance concentration in high dimensions numerically and explain its consequences.
  • Build a KD tree and analyze when exact search no longer improves on brute force.

Before you start

Motivation: learning without training

Every model you have seen in this topic compresses data into a few parameters: a vector w\vb{w} in linear or logistic regression, or a few dozen coefficients in a polynomial. After training, you can discard the data. There is another, older and more literal way to learn: keep all the examples and, for a new case, find the most similar ones and copy what happened to them. This is what a doctor does when recalling similar patients, an appraiser comparing homes sold on the same street, or a recommendation system suggesting what users with a history like yours bought.

The kk nearest neighbors rule (k-NN) formalizes that idea. It has no training phase: “training” means storing X\mat{X} and y\vb{y}. All the work happens at prediction time and depends on one question: what does it mean for two examples to be close? It is both the simplest nonparametric method and an excellent lens for three ideas that recur throughout machine learning:

  • How far can a method go without assumptions? Cover and Hart (1967) proved that, with infinite data, the classifier that copies the nearest neighbor’s label makes at most twice as many errors as the best possible classifier. You will prove it yourself.
  • Geometry is everything. Changing a variable’s unit from meters to millimeters changes which examples are neighbors, and thus the predictions. The choice of metric and scaling is the real choice of model.
  • High dimensions break intuition. In R1000\R^{1000}, the nearest and farthest neighbors are almost equally distant. This curse of dimensionality explains why k-NN fails on raw high-dimensional data and why it works remarkably well on good learned representations: neighbor search over embeddings underpins retrieval in RAG, image search, and corpus deduplication.

Also, because prediction requires finding neighbors among nn points, k-NN is an algorithms problem: brute force costs O(nd)\bigO(nd) per query. KD trees and ball trees reduce this to something close to O(log⁡n)\bigO(\log n) in low dimensions, and stop helping in high dimensions for the same geometric reason as the curse. By the end of this lesson you will have built a KD tree and measured when it stops pruning.

The k-nearest neighbors rule

Fix a distance ρ\rho in the input space (for now, Euclidean distance). For a query point x\vb{x}, sort the training examples by distance to x\vb{x},

ρ(x,x(1))≤ρ(x,x(2))≤⋯≤ρ(x,x(n)),\rho(\vb{x}, \vb{x}_{(1)}) \le \rho(\vb{x}, \vb{x}_{(2)}) \le \dots \le \rho(\vb{x}, \vb{x}_{(n)}),

where x(j)=x(j)(x)\vb{x}_{(j)} = \vb{x}_{(j)}(\vb{x}) is the jj-th neighbor of x\vb{x} and y(j)y_{(j)} its label, and break distance ties using a fixed rule (for example, the lower index). Call Nk(x)N_k(\vb{x}) the set of indices of the first kk neighbors.

Each output is a functional of the empirical distribution of nearby labels, chosen to match the loss, as you saw when studying what each loss estimates: the local mean minimizes squared error, the local median would minimize absolute error, and the majority vote is the mode, which minimizes 0–1 loss. k-NN literally means “do what is optimal for your loss, but only using nearby examples.”

Two details of the definition matter in practice. Vote ties (common with even kk in binary classification) need a rule: scikit-learn chooses the lower class in its ordering, introducing a systematic bias toward that class; binary classification therefore often uses odd kk. And distance ties, common with discrete variables, make the set Nk(x)N_k(\vb{x}) depend on data order: two correct implementations can produce different predictions.

Voronoi and the role of k

With k=1k = 1, the prediction at x\vb{x} is the label of the nearest example, so space is partitioned into the examples’ Voronoi cells, Vi={x:ρ(x,xi)≤ρ(x,xj) ∀j}V_i = \{\vb{x} : \rho(\vb{x}, \vb{x}_i) \le \rho(\vb{x}, \vb{x}_j)\ \forall j\}, and the decision boundary is the union of faces between cells of different classes. With Euclidean distance these faces are pieces of perpendicular bisectors: the 1-NN boundary is polygonal and as irregular as the data. For k>1k > 1 the regions where the set of kk neighbors is constant form the order-kk Voronoi diagram, with broader regions and votes averaging more labels. Try it.

InteractiveThe boundary as k changes
Rule of the 11 nearest neighbors: winning-class color is stronger for a larger share of votes
  • class A
  • class B
  • decision boundary
  • mislabeled point (draggable)
Validation curve: training and LOO error on these data versus kk
  • training
  • LOO
1
On click
Data
Points nn and classes71 and 2
Effective degrees of freedom n/kn/k71.0
Training error0.0 %
Leave-one-out (LOO) error23.9 %
With k=1k = 1 each point correctly classifies itself: training error 0 %. The LOO error is 23.9 %. Minimum LOO occurs at k=21k = 21.
Data from an explicit model with a fixed seed: in ‘Two classes’, 35 class A points, Gaussian and centered at the origin with standard deviations 0.60.6 horizontally and 0.750.75 vertically, and 35 class B points split into two groups, centered at (±1.8,∓0.2)(\pm 1.8, \mp 0.2) with standard deviations 0.50.5 and 0.70.7; in ‘Three’, 25 per class. The ringed point belongs to class B but lies inside the A cloud: drag it. The background color is the class predicted by the rule at each point in the plane; its intensity is the winner's vote share. Below is the validation curve for these same data: training error (each point is classified with its own vote included) and leave-one-out (LOO) error for each kk.

Three things you should have seen. With k=1k = 1, the mislabeled point creates a class B island inside region A: 1-NN does not distinguish signal from noise, it memorizes both. As kk increases the island disappears and the boundary smooths. But if kk exceeds the size of each B group (17 or 18 points), the neighbors of a B point include more and more A points, and the rule eventually swallows the side groups: with k=36k = 36, leave-one-out voting classifies all 36 B points as A. The curve below diagnoses this: the training error at k=1k = 1 is exactly 0 (each point is its own neighbor), while LOO error, which does not let the point vote for itself, traces the familiar U-shaped curve: 23.9% with k=1k = 1, a minimum of 11.3% at k=21k = 21 and 50.7% from k=36k = 36 onward, the error of always predicting A. Enable distance weights and look at the training error: it is 0 for every kk, because the point itself has weight 1/0=∞1/0 = \infty. With distance weights, training error tells you nothing.

kk is therefore a smoothness parameter, chosen like any hyperparameter: using a validation curve computed by cross-validation, never by training error.

Bias, variance, and degrees of freedom

For regression we can quantify the tradeoff. Suppose Y=f(X)+εY = f(X) + \eps with Eε=0\E\eps = 0, Var⁡ε=σ2\Var\eps = \sigma^2, and fix the training points (fixed design). The prediction at x0\vb{x}_0 is the average of kk responses, f^(x0)=1k∑ℓ=1k(f(x(ℓ))+ε(ℓ))\hat f(\vb{x}_0) = \frac1k \sum_{\ell=1}^k \big(f(\vb{x}_{(\ell)}) + \eps_{(\ell)}\big), with independent noise, so the expected error for a new Y0Y_0 observed at x0\vb{x}_0 is

E[(Y0−f^(x0))2]=σ2+(f(x0)−1k∑ℓ=1kf(x(ℓ)))2+σ2k.\E\big[(Y_0 - \hat f(\vb{x}_0))^2\big] = \sigma^2 + \Big(f(\vb{x}_0) - \frac1k\sum_{\ell=1}^k f(\vb{x}_{(\ell)})\Big)^2 + \frac{\sigma^2}{k}.

The first term is irreducible. The third, variance, decreases as 1/k1/k. The second, squared bias, grows with kk because neighbors move away from x0\vb{x}_0 and ff changes across them. This is the Hastie, Tibshirani and Friedman decomposition (ESL, eq. 7.10), and has an interpretation in terms of complexity: if you write predictions at training points as y^=Sy\hat{\vb{y}} = \mat{S}\vb{y}, row ii of S\mat{S} equals 1/k1/k in the columns of the kk neighbors of xi\vb{x}_i, including xi\vb{x}_i itself if there are no duplicate points. Thus Sii=1/kS_{ii} = 1/k and the effective degrees of freedom are

df⁡(k)=tr⁡S=nk.\operatorname{df}(k) = \tr \mat{S} = \frac{n}{k}.

With k=1k = 1 you have as many “parameters” as data points; with k=nk = n, just one (the global mean). This is the same scale on which you measured ridge: a rule with n/kn/k degrees of freedom behaves like a model with n/kn/k parameters.

From scratch, without loops

The expensive operation is the distance matrix between the mm queries and nn examples. Computing it with two nested Python loops is slow; NumPy broadcasting, ((A[:, None] - B[None]) ** 2).sum(-1), materializes a tensor of m×n×dm \times n \times d numbers. The solution is the identity

∥a−b∥2=∥a∥2+∥b∥2−2 a⊤b,\norm{\vb{a} - \vb{b}}^2 = \norm{\vb{a}}^2 + \norm{\vb{b}}^2 - 2\,\vb{a}\T\vb{b},

which turns the work into a matrix product AB⊤\mat{A}\mat{B}\T plus two vectors of norms: O(mn)\bigO(mn) memory and computation delegated to the best-optimized operation in any numerical library. This is what sklearn.metrics.pairwise.euclidean_distances does.

[ ]Vectorized k-NN and its smoothing matrixBrowser
import numpy as np
from sklearn.neighbors import KNeighborsRegressor

def sq_dists(A, B):
    """Distancias euclídeas al cuadrado entre filas de A (m × d) y de B (n × d): ‖a‖² + ‖b‖² − 2aᵀb."""
    D = (A**2).sum(1)[:, None] + (B**2).sum(1)[None, :] - 2.0 * (A @ B.T)
    return np.maximum(D, 0.0)              # la cancelación puede dejar negativos minúsculos

def knn_regress(X_tr, y_tr, X_te, k, weights="uniform"):
    D = sq_dists(X_te, X_tr)
    idx = np.argsort(D, axis=1, kind="stable")[:, :k]      # empates de distancia: el índice menor
    dist = np.sqrt(np.take_along_axis(D, idx, axis=1))
    if weights == "uniform":
        W = np.ones_like(dist)
    else:                                                   # 1/ρ; si alguna distancia es 0, solo cuentan esas
        with np.errstate(divide="ignore"):
            W = 1.0 / dist
        inf = np.isinf(W)
        filas = inf.any(axis=1)
        W[filas] = inf[filas]
    return (W * y_tr[idx]).sum(1) / W.sum(1)

rng = np.random.default_rng(0)
n, d = 300, 3
X = rng.uniform(-1, 1, (n, d))
y = np.sin(3 * X[:, 0]) + X[:, 1] ** 2 + 0.1 * rng.standard_normal(n)
Xt = rng.uniform(-1, 1, (200, d))
for w in ("uniform", "distance"):
    mine = knn_regress(X, y, Xt, 7, w)
    ref = KNeighborsRegressor(7, weights=w).fit(X, y).predict(Xt)
    print(f"weights={w:9s} diferencia máxima con scikit-learn: {np.abs(mine - ref).max():.1e}")

# la matriz de suavizado en los propios datos: cada punto es su vecino más próximo, S_ii = 1/k
for k in (1, 5, 20):
    S = np.zeros((n, n))
    idx = np.argsort(sq_dists(X, X), axis=1, kind="stable")[:, :k]
    np.put_along_axis(S, idx, 1.0 / k, axis=1)
    print(f"k = {k:2d}:  tr(S) = {np.trace(S):6.1f}   n/k = {n / k:6.1f}   error de entrenamiento {np.mean((S @ y - y)**2):.4f}")

# la identidad pierde precisión lejos del origen: centrar lo arregla
Z = rng.standard_normal((50, d)) * 0.01
fuera = ~np.eye(50, dtype=bool)
exacta = ((Z[:, None, :] - Z[None, :, :]) ** 2).sum(-1)[fuera]
for off in (0.0, 1e3, 1e5):
    err = np.abs(sq_dists(Z + off, Z + off)[fuera] - exacta) / exacta
    print(f"desplazamiento {off:7.0e}: error relativo máximo de la identidad {err.max():.1e}")

The implementation agrees with KNeighborsRegressor up to rounding, and the trace of S\mat{S} is exactly n/kn/k: 300, 60 and 15. The last part is a warning worth knowing. If the data are far from the origin (shifted 10510^5 with a spread of 10−210^{-2}), ∥a∥2\norm{\vb{a}}^2 and 2a⊤b2\vb{a}\T\vb{b} are numbers of order 101010^{10} whose difference is of order 10−410^{-4}: subtraction cancels almost all significant digits of float64, and relative error reaches 73% for the closest pair. Those distances no longer work for ordering neighbors (and if cancellation leaves a negative value, np.maximum turns it into 0). Since Euclidean distance is translation invariant, centering first fixes this for free; and if you work in float32, as on GPUs, the problem appears much sooner.

From neighbors to kernels: local regression

The average of the kk neighbors has two visible flaws. It is discontinuous: when x\vb{x} moves and a neighbor enters or leaves Nk(x)N_k(\vb{x}), the prediction jumps. And it weights the nearest neighbor equally with the kk-th. Both are fixed by replacing the hard cutoff with a weight that decreases smoothly with distance. In one dimension, with a symmetric integrable kernel K≥0K \ge 0 (the Gaussian K(u)=e−u2/2K(u) = e^{-u^2/2}, or the tricube K(u)=(1−∣u∣3)3K(u) = (1 - \abs{u}^3)^3 on ∣u∣≤1\abs{u} \le 1) and a bandwidth h>0h > 0, write Kh(u)=K(u/h)K_h(u) = K(u/h).

These estimators form the family of local regression and kernel smoothing, and k-NN is one member: the mean of the kk neighbors is Nadaraya–Watson with the uniform kernel K(u)=1[∣u∣≤1]K(u) = \ind[\abs{u} \le 1] and an adaptive bandwidth, h(x0)=ρ(x0,x(k))h(x_0) = \rho(x_0, x_{(k)}). Where there are many data points the window narrows; where there are few it widens. The bandwidth hh is the continuous counterpart of kk: it controls the same bias–variance tradeoff. With nhn h effective data points in the window, variance is of order σ2/(nh)\sigma^2/(nh) and, in the interior and for twice differentiable ff, bias is of order h2h^2; balancing them gives h∝n−1/5h \propto n^{-1/5} and squared error decreasing as n−4/5n^{-4/5}, the same calculation that sets bandwidth in kernel density estimation.

The difference between the two estimators is at the boundary. Write the expectation conditional on the xix_i using a Taylor expansion of ff at x0x_0:

E[f^(x0)∣x1:n]=∑ili(x0)f(xi)=f(x0)∑ili(x0)+f′(x0)∑ili(x0)(xi−x0)+12∑ili(x0)f′′(ξi)(xi−x0)2.\E\big[\hat f(x_0) \given x_{1:n}\big] = \sum_i l_i(x_0) f(x_i) = f(x_0) \sum_i l_i(x_0) + f'(x_0)\sum_i l_i(x_0)(x_i - x_0) + \tfrac12 \sum_i l_i(x_0) f''(\xi_i)(x_i - x_0)^2 .
Proof

A weighted least-squares fit with a line exactly reproduces any line: if yi=a+b(xi−x0)y_i = a + b(x_i - x_0) for every ii, the sum of squares vanishes at (α,β)=(a,b)(\alpha, \beta) = (a, b), the unique minimum by invertibility, and f^LL(x0)=a\hat f_{\mathrm{LL}}(x_0) = a. By linearity, ∑ili(x0)(a+b(xi−x0))=a\sum_i l_i(x_0)\big(a + b(x_i - x_0)\big) = a for all a,ba, b. With (a,b)=(1,0)(a, b) = (1, 0) we obtain the first equality and with (a,b)=(0,1)(a, b) = (0, 1) the second. For Nadaraya–Watson, li=Kh(xi−x0)/∑jKh(xj−x0)l_i = K_h(x_i - x_0)/\sum_j K_h(x_j - x_0) sums to 1, but ∑ili(xi−x0)\sum_i l_i (x_i - x_0) is the center of mass of the weights relative to x0x_0, which vanishes only if the data are distributed symmetrically around x0x_0.

∎

In the interior, with dense data, the center of mass of the Nadaraya–Watson weights is nearly x0x_0 and the term f′(x0)∑ili(xi−x0)f'(x_0)\sum_i l_i(x_i - x_0) nearly cancels. At the left boundary of [0,1][0, 1], however, all data lie to the right: with the Gaussian kernel and uniform data, ∑ili(xi−x0)≈h E[U∣U≥0]=h2/π≈0.80 h\sum_i l_i (x_i - x_0) \approx h\,\E[U \given U \ge 0] = h\sqrt{2/\pi} \approx 0.80\,h for U∼N(0,1)U \sim \Normal(0, 1), and bias is of order hh, not h2h^2. This is boundary bias. In the interior there is a weaker version of the same phenomenon: if the density pp of the xix_i is nonuniform, the center of mass of the weights shifts toward more data, and Nadaraya–Watson has a design bias h2f′(x0)p′(x0)/p(x0)h^2 f'(x_0)p'(x_0)/p(x_0) (with a Gaussian kernel) added to the h2f′′(x0)/2h^2 f''(x_0)/2 term; Fan (1992) showed that local linear regression has neither. The local linear fit removes the first-order term by construction, at the cost of potentially negative weights and somewhat higher variance at the boundary.

InteractiveFrom neighbors to kernels
Nadaraya-Watson: estimate from this sample (blue), truth ff (gray) and weights li(x0)l_i(x_0) (point size)
x₀
  • truth f(x)=sin⁡2πx+xf(x) = \sin 2\pi x + x
  • estimate f^\hat f from this sample
  • mean E[f^]\E[\hat f] over 200 samples
  • data point, size by ∣li(x0)∣\lvert l_i(x_0)\rvert
  • kernel Kh(x−x0)K_h(x - x_0)
Estimator
0.080
f^(x0)\hat f(x_0) and f(x0)f(x_0)0.801 and 0.217
Bias at x0x_0, E[f^(x0)]−f(x0)\E[\hat f(x_0)] - f(x_0)0.294
∑ili(x0)\sum_i l_i(x_0)1.000
∑ili(x0)(xi−x0)\sum_i l_i(x_0)(x_i - x_0)0.0825
Degrees of freedom tr⁡S\operatorname{tr}\mat{S}5.1
Integrated squared error of this sample0.0604
The weights’ center of mass is 0.082 from x0x_0: the average looks to one side and inherits bias ≈f′(x0)∑ili(xi−x0)\approx f'(x_0)\sum_i l_i(x_i - x_0).
Explicit model, the same as in the next cell: xi∼Unif⁡[0,1]x_i \sim \Unif[0, 1], yi=f(xi)+εiy_i = f(x_i) + \eps_i with f(x)=sin⁡2πx+xf(x) = \sin 2\pi x + x and εi∼N(0,0.352)\eps_i \sim \Normal(0, 0.35^2), n=50n = 50, Gaussian kernel. Each point's size is its weight ∣li(x0)∣\abs{l_i(x_0)} in the prediction at x0x_0; red outlines are negative weights. The dashed magenta curve is E[f^(x)]\E[\hat f(x)], estimated from 200 independent samples from the same distribution: where it separates from the gray curve, the estimator is biased.

With x0x_0 at the left boundary, Nadaraya–Watson places all weights to the right of x0x_0, where ff grows rapidly (f′(0)=2π+1≈7.28f'(0) = 2\pi + 1 \approx 7.28), and its mean remains well above f(0)=0f(0) = 0. Switch to local linear: the ∑ili(x0)(xi−x0)\sum_i l_i(x_0)(x_i - x_0) reading becomes exactly 0, the magenta mean matches the truth at the boundary, and negative weights appear on the more distant points, which “tilt” the line. In k-NN mode the estimate has steps: that is the discontinuity we started with. The cell measures both biases using 4000 samples.

[ ]Boundary bias: Nadaraya–Watson versus local linearBrowser
import numpy as np

f = lambda x: np.sin(2 * np.pi * x) + x

def local_weights(x, x0, h, grado):
    """Pesos equivalentes l_i(x0) (una fila por muestra) de Nadaraya-Watson (grado 0) o lineal local (grado 1)."""
    u = x - x0
    K = np.exp(-0.5 * (u / h) ** 2)
    if grado == 0:
        return K / K.sum(-1, keepdims=True)
    s0, s1, s2 = K.sum(-1, keepdims=True), (K * u).sum(-1, keepdims=True), (K * u**2).sum(-1, keepdims=True)
    return K * (s2 - u * s1) / (s0 * s2 - s1**2)

R, n, sigma = 4000, 50, 0.35
rng = np.random.default_rng(1)
x = rng.uniform(0, 1, (R, n))
y = f(x) + sigma * rng.standard_normal((R, n))
print("  h     x0   estimador       sesgo   desv. típ.   media de sum l_i (x_i - x0)")
for h in (0.05, 0.1):
    for x0 in (0.0, 0.25):
        for g, nombre in ((0, "N-W"), (1, "lineal local")):
            L = local_weights(x, x0, h, g)
            est = (L * y).sum(-1)
            m1 = (L * (x - x0)).sum(-1).mean()
            print(f"{h:4.2f}  {x0:5.2f}   {nombre:12s} {est.mean() - f(x0):+8.3f}   {est.std():8.3f}   {m1:+12.4f}")
print(f"primer orden de N-W en x0 = 0:  sqrt(2/pi) f'(0) h = {np.sqrt(2 / np.pi) * (2 * np.pi + 1):.2f} h")
print(f"segundo orden en x0 = 0.25:     f''(0.25) h^2 / 2 = {-2 * np.pi**2:.2f} h^2")

The numbers confirm the theory. At x0=0x_0 = 0 and with h=0.05h = 0.05, Nadaraya–Watson has bias +0.312+0.312, close to the first-order prediction 5.81⋅0.05=0.295.81 \cdot 0.05 = 0.29, and local linear +0.018+0.018. With h=0.1h = 0.1, +0.538+0.538 versus +0.097+0.097. At x0=0.25x_0 = 0.25, where f′′=−4π2f'' = -4\pi^2, both have the same bias, −0.051-0.051 and −0.050-0.050 with h=0.05h = 0.05, as predicted by f′′h2/2=−0.049f''h^2/2 = -0.049 (with h=0.1h = 0.1, −0.174-0.174 and −0.173-0.173 versus −0.197-0.197: higher-order terms already matter there). The cost is in the standard deviation column: at the boundary local linear has 0.3920.392 versus 0.2070.207, almost twice as much, because it extrapolates the line from data on only one side. In the interior the two columns agree. That is why local linear regression (or LOESS) is the default smoother in statistics: the same interior behavior and bias of order h2h^2 everywhere, paid for with variance only where unavoidable.

What it means to be close: metrics and scaling

Everything above depends on ρ\rho, and ρ\rho is not supplied by the data: you choose it. The most common choices are these.

  • Minkowski LpL_p, ρp(x,z)=(∑j∣xj−zj∣p)1/p\rho_p(\vb{x}, \vb{z}) = \big(\sum_j \abs{x_j - z_j}^p\big)^{1/p} with p≥1p \ge 1: the pp norm of the difference. p=2p = 2 is Euclidean, p=1p = 1 is Manhattan (sum of absolute differences, less sensitive to a coordinate with an extreme value), and p=∞p = \infty is Chebyshev, max⁡j∣xj−zj∣\max_j \abs{x_j - z_j}. With p<1p < 1 the triangle inequality fails and it is no longer a metric.
  • Cosine, 1−cos⁡(x,z)=1−x⊤z/(∥x∥∥z∥)1 - \cos(\vb{x}, \vb{z}) = 1 - \vb{x}\T\vb{z}/(\norm{\vb{x}}\norm{\vb{z}}): compares directions and ignores norms, natural for text (frequency vectors) and embeddings. It is not a metric, but for unit vectors ∥u−v∥2=2−2cos⁡(u,v)\norm{\vb{u} - \vb{v}}^2 = 2 - 2\cos(\vb{u}, \vb{v}), so cosine distance orders neighbors just like Euclidean distance on normalized vectors: normalize and use any Euclidean search structure.
  • Mahalanobis, ρΣ(x,z)=(x−z)⊤Σ−1(x−z)\rho_{\mat{\Sigma}}(\vb{x}, \vb{z}) = \sqrt{(\vb{x} - \vb{z})\T\mat{\Sigma}\inv(\vb{x} - \vb{z})}, with Σ\mat{\Sigma} the data covariance: the Mahalanobis distance. If Σ=LL⊤\mat{\Sigma} = \mat{L}\mat{L}\T (Cholesky), ρΣ(x,z)=∥L−1x−L−1z∥2\rho_{\mat{\Sigma}}(\vb{x}, \vb{z}) = \norm{\mat{L}\inv\vb{x} - \mat{L}\inv\vb{z}}_2: it is Euclidean distance after whitening the data, so it is invariant under any invertible affine transformation of the variables (provided Σ\mat{\Sigma} is recomputed).

The most damaging practical problem is not choosing among these metrics, but units. Euclidean distance is invariant under translations, rotations, and equal scaling on every axis, but not under rescaling a single variable. For two independent examples from the same distribution, E∥X−X′∥2=2∑jVar⁡Xj\E\norm{X - X'}^2 = 2\sum_j \Var X_j: each variable contributes in proportion to its variance, which depends on its unit. If a length changes from meters to millimeters, its variance is multiplied by 10610^6, as is its contribution to distance. The other variables disappear from the neighborhood.

InteractiveWhat ‘close’ means
Length x1x_1 (m) horizontally and width x2x_2 (mm) vertically; the shaded region is the ball of 9 neighbors
  • class 0
  • class 1
  • ball of 9 neighbors (ring: neighbor)
  • query (draggable)
Metric
Scaling
Unit of x2x_2
9
Share of x2x_2 in expected squared distance100.0 %
Neighbors shared with standardized Euclidean distance2 of 9
LOO accuracy of 9-NN with this metric87.5 %
In these units x2x_2 contributes 100.0 % of expected squared distance: the ball is a strip and neighbors have the closest x2x_2, regardless of x1x_1.
Explicit model with a fixed seed: 80 points with (z1,z2)∼N(0,[10.60.61])(z_1, z_2) \sim \Normal\big(\vb{0}, \big[\begin{smallmatrix}1 & 0.6\\ 0.6 & 1\end{smallmatrix}\big]\big) and label y=1[z1+0.5z2+0.4ε>0]y = \ind[z_1 + 0.5 z_2 + 0.4\eps > 0]. The physical variables are a length x1=1.75+0.10z1x_1 = 1.75 + 0.10 z_1 m and a width x2=1.20+0.15z2x_2 = 1.20 + 0.15 z_2 m, which you can express in km, m or mm. The figure is always drawn in standardized coordinates so the cloud does not change: what changes is the ball {x:ρ(x,xq)≤rk}\{\vb{x} : \rho(\vb{x}, \vb{x}_q) \le r_k\} containing the query's kk neighbors. LOO accuracy is computed live on these 80 points.

With raw units and width in millimeters, the ball flattens into a horizontal strip: the “neighbors” are points with the most similar width, even if their length is opposite, and 9-NN LOO accuracy falls from 91.3% (standardized) to 87.5%. Change width to kilometers and the strip rotates: now only length counts, and accuracy drops to 83.8%. In meters, the two scales happen to be comparable (90.0%). Standardizing makes units irrelevant. The ball’s shape changes with the metric (circle, diamond, square), but the effect of units is much larger than the metric’s. Mahalanobis, which uses sample covariance, stretches the ball in the direction of correlation and also does not depend on units.

The next cell measures this with real data: the 178 wine samples from load_wine (13 chemical variables, 3 cultivars), where proline has standard deviation 314 and the smallest variable 0.124.

[ ]To scale or not to scale: the Wine datasetBrowser
import numpy as np
from sklearn.datasets import load_wine
from sklearn.model_selection import cross_val_score, StratifiedKFold
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler, MinMaxScaler
from sklearn.decomposition import PCA
from sklearn.neighbors import KNeighborsClassifier

datos = load_wine()
Xw, yw = datos.data, datos.target
sd = Xw.std(0)
orden = np.argsort(sd)[::-1]
print("desviaciones típicas:", ", ".join(f"{datos.feature_names[j]} {sd[j]:.3g}" for j in orden[[0, 1, -1]]))
dif = Xw[:, None, :] - Xw[None, :, :]
cuota = (dif**2).sum((0, 1)) / (dif**2).sum()
print(f"cuota de proline en la suma de distancias cuadráticas entre pares: {cuota[orden[0]]:.4f}")

cv = StratifiedKFold(5, shuffle=True, random_state=0)
modelos = {
    "sin escalar": (KNeighborsClassifier(5), Xw),
    "solo proline": (KNeighborsClassifier(5), Xw[:, [orden[0]]]),
    "StandardScaler": (make_pipeline(StandardScaler(), KNeighborsClassifier(5)), Xw),
    "MinMaxScaler": (make_pipeline(MinMaxScaler(), KNeighborsClassifier(5)), Xw),
    "blanqueo (Mahalanobis)": (make_pipeline(PCA(whiten=True), KNeighborsClassifier(5)), Xw),
}
for nombre, (modelo, X_) in modelos.items():
    acc = cross_val_score(modelo, X_, yw, cv=cv)
    print(f"{nombre:23s} exactitud CV {acc.mean():.3f} ± {acc.std():.3f}")

# Mahalanobis = euclídea tras blanquear con Σ = L Lᵀ
S = np.cov(Xw.T)
L = np.linalg.cholesky(S)
Zw = np.linalg.solve(L, Xw.T).T
a, b = Xw[0], Xw[100]
print(f"\nMahalanobis {np.sqrt((a - b) @ np.linalg.solve(S, a - b)):.6f}   euclídea tras blanquear {np.linalg.norm(Zw[0] - Zw[100]):.6f}")

# coseno: en vectores unitarios, ‖u − v‖² = 2 − 2 cos(u, v), así que ordenan igual
U = Xw / np.linalg.norm(Xw, axis=1, keepdims=True)
cosd = 1 - U @ U[0]
eu = np.linalg.norm(U - U[0], axis=1)
print("mismos 10 vecinos con coseno y con euclídea normalizada:",
      np.array_equal(np.argsort(cosd, kind="stable")[1:11], np.argsort(eu, kind="stable")[1:11]),
      f"  max |‖u − v‖² − 2(1 − cos)| = {np.abs(eu**2 - 2 * cosd).max():.1e}")

Without scaling, proline accounts for 99.77% of the sum of squared pairwise distances, and 5-NN accuracy (0.663) is practically the same as using only proline (0.657): the other 12 variables barely count. Standardizing raises it to 0.961, and with MinMaxScaler to 0.972. Full whitening, equivalent to Mahalanobis with each training fold’s covariance, reaches 0.910. Whitening gives equal weight to all principal directions, including those with tiny variance: if those directions do not separate the cultivars, they only add noise to the distance, and cross-validation says that here it performs worse than standardization. Mahalanobis is not “the correct metric” by default; it is another option to validate like any other. Notice also that all scalers are inside a pipeline: the mean, standard deviation and covariance are parameters estimated from data, and estimating them on the whole dataset before CV would be leakage (as you saw in the pipelines lesson).

Theory: how much is lost by looking only at the neighbor

To know whether k-NN is good, compare it to the best possible rule. Take binary classification, Y∈{0,1}Y \in \{0, 1\}, and write η(x)=P(Y=1∣X=x)\eta(\vb{x}) = \Pr(Y = 1 \given X = \vb{x}). No rule can improve on the Bayes rule g∗(x)=1[η(x)>1/2]g^*(\vb{x}) = \ind[\eta(\vb{x}) > 1/2], which errs with probability min⁡(η,1−η)\min(\eta, 1 - \eta) at each x\vb{x}. Its error,

R∗=E[r(X)],r(x)=min⁡(η(x),1−η(x))∈[0,12],R^* = \E\big[r(X)\big], \qquad r(\vb{x}) = \min\big(\eta(\vb{x}), 1 - \eta(\vb{x})\big) \in [0, \tfrac12],

is the Bayes error, the part no amount of data can eliminate because it belongs to the law of (X,Y)(X, Y) itself. In learning theory you will formalize it as irreducible error. The error of a rule trained on nn data points, Rn=P(gn(X)≠Y∣Dn)R_n = \Pr(g_n(X) \ne Y \given \Data_n), always satisfies Rn≥R∗R_n \ge R^*.

Consistency. Stone (1977) proved that if k→∞k \to \infty and k/n→0k/n \to 0, the kk-neighbor rule is universally consistent: ERn→R∗\E R_n \to R^* for any distribution of (X,Y)(X, Y) in Rd\R^d (with Euclidean norm and distance ties broken randomly). This is remarkable: no assumptions on η\eta, neither continuity nor density. The two conditions have a direct interpretation: k→∞k \to \infty makes vote variance vanish, and k/n→0k/n \to 0 makes the kk neighbors increasingly close to x\vb{x}, so bias vanishes too. You will study this in detail, along with the absence of universal convergence rates, in universal consistency.

What if kk stays fixed? Then the vote does not average and there is no consistency. What is surprising is how much is lost.

Cover and Hart proved this in a separable metric space assuming some continuity of the class densities; in Rd\R^d with the Euclidean norm the limit holds for any distribution (Devroye, Györfi and Lugosi, 1996, ch. 5). This statement is the Cover–Hart bound, and the paper itself interprets it in words: asymptotically, half the classification information in an infinite sample lies in its nearest neighbor.

Proof

We prove it assuming η\eta is continuous; the general case approximates η\eta by continuous functions.

Step 1: the neighbor converges to the query. Let μ\mu be the law of XX and x\vb{x} a point in its support, so μ(B(x,ε))>0\mu(B(\vb{x}, \eps)) > 0 for every ε>0\eps > 0. The nearest neighbor is farther than ε\eps only if the nn data points fall outside the ball, so

P(ρ(x,X(1)(x))>ε)=(1−μ(B(x,ε)))n→n→∞0,\Pr\big(\rho(\vb{x}, X_{(1)}(\vb{x})) > \eps\big) = \big(1 - \mu(B(\vb{x}, \eps))\big)^n \xrightarrow[n \to \infty]{} 0,

and since ρ(x,X(1)(x))\rho(\vb{x}, X_{(1)}(\vb{x})) does not grow with nn, convergence is almost sure. The support has measure 1, so X(1)(X)→XX_{(1)}(X) \to X almost surely.

Step 2: conditional error. Condition on X=xX = \vb{x} and the training inputs. The neighbor X(1)=x′X_{(1)} = \vb{x}' is fixed; its label is Bernoulli with parameter η(x′)\eta(\vb{x}') and independent of the query label YY, which is Bernoulli with parameter η(x)\eta(\vb{x}). The rule errs if they differ:

P(Y≠Y(1)∣x,x′)=η(x)(1−η(x′))+(1−η(x))η(x′).\Pr(Y \ne Y_{(1)} \given \vb{x}, \vb{x}') = \eta(\vb{x})\big(1 - \eta(\vb{x}')\big) + \big(1 - \eta(\vb{x})\big)\eta(\vb{x}').

Step 3: limit. By step 1 and continuity of η\eta, that probability tends to 2η(x)(1−η(x))2\eta(\vb{x})(1 - \eta(\vb{x})) almost surely. It is bounded by 1, so dominated convergence gives ERn→E[2η(X)(1−η(X))]\E R_n \to \E[2\eta(X)(1 - \eta(X))].

Step 4: the bounds. Since η(1−η)=r(1−r)\eta(1 - \eta) = r(1 - r), we have R1NN=E[2r(1−r)]R_{\mathrm{1NN}} = \E[2r(1 - r)]. Lower bound: 2r(1−r)−r=r(1−2r)≥02r(1 - r) - r = r(1 - 2r) \ge 0 because r∈[0,12]r \in [0, \tfrac12]; integrating, R1NN≥R∗R_{\mathrm{1NN}} \ge R^*. Upper bound: φ(r)=r(1−r)\varphi(r) = r(1 - r) is concave, so Jensen’s inequality gives Eφ(r)≤φ(Er)\E\varphi(r) \le \varphi(\E r), that is, R1NN≤2R∗(1−R∗)R_{\mathrm{1NN}} \le 2R^*(1 - R^*). Equivalently, E[2r(1−r)]=2R∗−2Er2=2R∗(1−R∗)−2Var⁡r\E[2r(1 - r)] = 2R^* - 2\E r^2 = 2R^*(1 - R^*) - 2\Var r.

∎

The last equality says exactly when each extreme is reached. The upper bound holds if and only if Var⁡r(X)=0\Var r(X) = 0: noise is the same everywhere. The lower bound holds if and only if r(1−2r)=0r(1 - 2r) = 0 almost surely, that is, r(X)∈{0,12}r(X) \in \{0, \tfrac12\}: in each region, either classes do not overlap (and the neighbor always gets it right) or they are perfectly mixed (and nobody can do better than chance). In between, 1-NN loses where rr is intermediate: r(1−2r)r(1 - 2r) is maximal at r=1/4r = 1/4.

The same idea gives the asymptotic error for fixed odd kk. The kk neighbors converge to x\vb{x}, their labels are kk independent Bernoulli variables with parameter η(x)\eta(\vb{x}), and the rule fails if the majority does not match YY:

RkNN=E[η(X)P(B<k2)+(1−η(X))P(B>k2)],B∣X∼Bin⁡(k,η(X)).R_{k\mathrm{NN}} = \E\Big[\eta(X)\Pr\big(B < \tfrac k2\big) + \big(1 - \eta(X)\big)\Pr\big(B > \tfrac k2\big)\Big], \qquad B \given X \sim \Bin\big(k, \eta(X)\big).

For each x\vb{x}, the probability that the majority of kk votes (odd) is correct increases with kk (Condorcet’s jury theorem), so RkNNR_{k\mathrm{NN}} decreases with kk toward R∗R^*, without reaching it for any fixed kk except in the extreme cases.

InteractiveWhere 1-NN falls within the band
Asymptotic error versus R∗R^*: Cover–Hart band
R*2R*(1 − R*)
Integrands: r(x)p(x)r(x)p(x) (Bayes) and 2η(1−η)p(x)2\eta(1-\eta)p(x) (1-NN)
  • Bayes error R∗R^* (line) and its integrand
  • Cover–Hart bound
  • asymptotic 1-NN (point) and its integrand
  • family trajectory
  • 3-NN and 5-NN
Problem
1.00
Bayes error R∗R^*0.1587
Asymptotic 1-NN E[2η(1−η)]\E[2\eta(1-\eta)]0.2248
Bound 2R∗(1−R∗)2R^*(1 - R^*)0.2670
Asymptotic 3-NN and 5-NN0.1915 and 0.1802
1-NN covers 61% of the distance between R∗R^* and the upper bound. Fixed k=3k = 3 and k=5k = 5 bring asymptotic error closer to R∗R^*.
Everything is exact, by numerical integration of the formulas above. Gaussians: X∣Y∼N(±a,1)X \given Y \sim \Normal(\pm a, 1) with priors 1/21/2, so η(x)=σ(2ax)\eta(x) = \sigma(2ax) and R∗=Φ(−a)R^* = \Phi(-a). Constant η\eta: XX carries no information. r∈{0,12}r \in \{0, \tfrac12\}: X∼Unif⁡[0,1]X \sim \Unif[0, 1], pure noise (η=12\eta = \tfrac12) in [0,q)[0, q) and separated classes (η=0\eta = 0 and then η=1\eta = 1) elsewhere. Linear η\eta: X∼Unif⁡[0,1]X \sim \Unif[0, 1] and η(x)=12+s(x−12)\eta(x) = \tfrac12 + s(x - \tfrac12). In the first panel, each problem is a point in the (R∗,error)(R^*, \text{error}) plane; the dashed line traces the family as its parameter moves. In the second, the integrands r(x)p(x)r(x)p(x) and 2η(1−η)p(x)2\eta(1-\eta)p(x): the difference in areas is the 1-NN excess.

Explore the four families. With constant η\eta, the blue point travels along the red curve: 1-NN reaches the bound. With r∈{0,12}r \in \{0, \tfrac12\} it travels along the diagonal: it is optimal. The Gaussians lie in between, and the right panel shows why: the 1-NN integrand exceeds Bayes’ mainly where rr is far from 0 and 12\tfrac12, around r=1/4r = 1/4, where r(1−2r)r(1 - 2r) is large. The aqua points, 3-NN and 5-NN, approach R∗R^*: with a=1a = 1, excess over R∗=0.1587R^* = 0.1587 falls from 0.0660.066 for 1-NN to 0.0330.033 for 3-NN and 0.0220.022 for 5-NN (the values in the next cell).

The laboratory: Cover and Hart, measured

The Gaussian problem is the perfect test bed because its Bayes error is known. In R2\R^2, with X∣Y=1∼N((a,0),I)X \given Y = 1 \sim \Normal((a, 0), \mat{I}), X∣Y=0∼N((−a,0),I)X \given Y = 0 \sim \Normal((-a, 0), \mat{I}) and priors 1/21/2, the density ratio gives η(x)=σ(2ax1)\eta(\vb{x}) = \sigma(2ax_1): only the first coordinate matters, R∗=Φ(−a)R^* = \Phi(-a) and asymptotic errors reduce to one-dimensional integrals.

[ ]1-NN and k-NN error versus Bayes errorBrowser
import numpy as np
from scipy import integrate, stats
from scipy.special import expit
from sklearn.neighbors import KNeighborsClassifier

a = 1.0                                                                  # medias (±a, 0), covarianza I, priors 1/2
dens = lambda t: 0.5 * stats.norm.pdf(t, a) + 0.5 * stats.norm.pdf(t, -a)     # ley de x₁
eta = lambda t: expit(2 * a * t)                                               # η(x) solo depende de x₁
E = lambda g: integrate.quad(lambda t: g(t) * dens(t), -12, 12)[0]
R_bayes = E(lambda t: np.minimum(eta(t), 1 - eta(t)))

def R_k(k):
    """Error asintótico de k-NN (k impar): la mayoría de k etiquetas Bernoulli(η) contra una más."""
    m = (k - 1) // 2
    return E(lambda t: eta(t) * stats.binom.cdf(m, k, eta(t)) + (1 - eta(t)) * stats.binom.sf(m, k, eta(t)))

print(f"R* = {R_bayes:.4f}  (Φ(−a) = {stats.norm.cdf(-a):.4f})   cota 2R*(1 − R*) = {2 * R_bayes * (1 - R_bayes):.4f}")
print("asintóticos:  " + "   ".join(f"R_{k}NN = {R_k(k):.4f}" for k in (1, 3, 5, 15)))

rng = np.random.default_rng(0)
def muestra(n):
    y = rng.integers(0, 2, n)
    X = rng.standard_normal((n, 2))
    X[:, 0] += np.where(y == 1, a, -a)
    return X, y

X_te, y_te = muestra(10_000)
print("\n     n   error 1-NN   error 15-NN   (media de 3 muestras de entrenamiento)")
for n in (20, 100, 1000, 10_000):
    e1, e15 = [], []
    for _ in range(3):
        X, y = muestra(n)
        e1.append(np.mean(KNeighborsClassifier(1).fit(X, y).predict(X_te) != y_te))
        e15.append(np.mean(KNeighborsClassifier(15).fit(X, y).predict(X_te) != y_te))
    print(f"{n:6d}   {np.mean(e1):9.4f}   {np.mean(e15):10.4f}")

Bayes error is R∗=0.1587R^* = 0.1587 and the Cover–Hart bound is 0.26700.2670. 1-NN converges to R1NN=0.2248R_{\mathrm{1NN}} = 0.2248, within the band and well below the ceiling, and does so quickly in two dimensions: from n=100n = 100 onward estimates are already around 0.220.22 and do not improve when multiplying data by 100, because with k=1k = 1 more data do not reduce vote variance. By contrast, 15-NN approaches its limit R15NN=0.1664R_{\mathrm{15NN}} = 0.1664, already very close to R∗R^*. With n=20n = 20, 15-NN is worse than 1-NN: 15 neighbors out of 20 data points are no longer local.

We still need to choose kk using the data. The correct method is a cross-validated search over a pipeline that includes scaling, so the mean and standard deviation are re-estimated in each fold.

[ ]Choosing k by cross-validation within a pipelineBrowser
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import GridSearchCV, StratifiedKFold

X, y = muestra(2000)
pipe = Pipeline([("escala", StandardScaler()), ("knn", KNeighborsClassifier())])
rejilla = {"knn__n_neighbors": [1, 3, 5, 9, 15, 25, 41, 65, 101, 151, 251]}
gs = GridSearchCV(pipe, rejilla, cv=StratifiedKFold(5, shuffle=True, random_state=0)).fit(X, y)
for k, s in zip(rejilla["knn__n_neighbors"], gs.cv_results_["mean_test_score"]):
    print(f"k = {k:3d}   error CV {1 - s:.4f}")
k_opt = gs.best_params_["knn__n_neighbors"]
print(f"k elegido {k_opt} (k/n = {k_opt / 2000:.3f})   error en test {np.mean(gs.predict(X_te) != y_te):.4f}   R* = {R_bayes:.4f}")

The validation curve falls rapidly until k≈15k \approx 15 and is nearly flat thereafter: here η\eta varies slowly (the Bayes boundary is a straight line), so averaging many neighbors adds little bias. Cross-validation chooses k=101k = 101, with CV error 0.16150.1615, and on the independent test set that model errs 0.15870.1587, matching R∗R^* to the fourth decimal place. Do not read this as “k-NN reaches the exact optimum”: with 10,000 test points, the standard deviation of an error around 0.160.16 is 0.16⋅0.84/104≈0.004\sqrt{0.16 \cdot 0.84 / 10^4} \approx 0.004, so the correct statement is that it is indistinguishable from R∗R^* at that resolution. No rule can have true error below R∗R^*, but an estimate can fall below it due to noise (with 2000 CV points the standard deviation is of order 0.0080.008) and the optimistic bias of selecting the best of 11 candidates, the same validation overfitting from the previous lesson. That is why the reported error is the test-set error, not the minimum of the CV curve.

The curse of dimensionality

Everything above rests on a silent assumption: that the kk neighbors of x\vb{x} are close to x\vb{x}. Stone’s theorem guarantees this when n→∞n \to \infty, but says nothing about the rate, which depends drastically on dimension. Bellman coined “curse of dimensionality” in his books on dynamic programming (1957 and 1961; ESL cites 1961) for the exponential growth of grids; in learning it describes several mutually reinforcing geometric facts. You already saw them from a probability perspective in high-dimensional concentration; here their consequences for neighbors matter.

Volume moves to the corners

The ball of radius rr in Rd\R^d has volume Vd(r)=πd/2rd/Γ(d/2+1)V_d(r) = \pi^{d/2} r^d / \Gamma(d/2 + 1). The ball inscribed in the cube [0,1]d[0, 1]^d has radius 1/21/2, so it contains a fraction

Vd(1/2)1=πd/2Γ(d/2+1) 2d\frac{V_d(1/2)}{1} = \frac{\pi^{d/2}}{\Gamma(d/2 + 1)\, 2^d}

of the cube: π/4=0.785\pi/4 = 0.785 in the plane, π/6=0.524\pi/6 = 0.524 in space, and 0.00250.0025 in d=10d = 10. The rest is in the corners, farther than 1/21/2 from the center. A high-dimensional cube is almost all corners, and a uniform point in it is almost always far from the center.

Neighborhoods stop being local

Suppose nn data points are uniform in [0,1]d[0, 1]^d and you want a cubic neighborhood containing a fraction rr of them (for example, k=rnk = rn neighbors). Its side must be ed(r)=r1/de_d(r) = r^{1/d}. For 1% of the data, e1=0.01e_1 = 0.01, e2=0.1e_2 = 0.1, e10=0.631e_{10} = 0.631 and e100=0.955e_{100} = 0.955; for 10%, e10=0.794e_{10} = 0.794 (the example from ESL, sec. 2.5). In ten dimensions, the “neighborhood” containing 1% of the data covers 63% of each variable’s range: it is no longer local, and averaging over it introduces enormous bias. Another view: with NN uniform points in the unit ball of Rd\R^d, the median distance from the origin to the nearest point is

(1−(12)1/N)1/d,\Big(1 - \big(\tfrac12\big)^{1/N}\Big)^{1/d},

which with N=500N = 500 and d=10d = 10 equals 0.520.52: the center’s nearest neighbor is closer to the boundary than to the center.

All distances look alike

The most damaging effect for k-NN is distance concentration. Take a query q\vb{q} and nn points XiX_i uniform in [0,1]d[0, 1]^d. Each ∥Xi−q∥2=∑j=1d(Xij−qj)2\norm{X_i - \vb{q}}^2 = \sum_{j=1}^d (X_{ij} - q_j)^2 is a sum of dd independent bounded terms, so by the law of large numbers it concentrates around its mean, which grows as dd, with fluctuations of order d\sqrt d. If q\vb{q} is also uniform, the mean per coordinate is E(U−V)2=1/6\E(U - V)^2 = 1/6 and the conditional variance per coordinate, averaged over qjq_j, is E(U−V)4−E[(q2−q+13)2]=115−130=130\E(U - V)^4 - \E\big[(q^2 - q + \tfrac13)^2\big] = \tfrac1{15} - \tfrac1{30} = \tfrac1{30}. A first-order expansion of the square root gives the distance’s coefficient of variation:

σ(∥X−q∥)E∥X−q∥≈12⋅d/30d/6=330 d≈0.548d.\frac{\sigma\big(\norm{X - \vb{q}}\big)}{\E\norm{X - \vb{q}}} \approx \frac12 \cdot \frac{\sqrt{d/30}}{d/6} = \frac{3}{\sqrt{30\,d}} \approx \frac{0.548}{\sqrt d}.

Relative to their size, all distances are practically equal. Beyer, Goldstein, Ramakrishnan and Shaft (1999) turned this into a general theorem.

The hypothesis, that relative distance dispersion vanishes, holds for data with independent identically distributed coordinates and many others. The conclusion is that relative contrast (Dmax⁡−Dmin⁡)/Dmin⁡(D^{\max} - D^{\min})/D^{\min} tends to 0: “which is nearest?” no longer has a stable answer, because a small perturbation of the data or query reorders the neighbors. Together with the two previous facts, this is the curse of dimensionality: in high dimensions distances concentrate, neighborhoods cease to be local, and the number of data points needed for locality grows exponentially with dd. Replacing Euclidean with Manhattan does not fix it: the theorem’s hypothesis holds for any LpL_p with independent coordinates. Aggarwal, Hinneburg and Keim (2001) observed that norms with small pp retain more contrast than those with large pp, but all lose it.

InteractiveAll distances look alike
Histogram of the 500 distances ∥⋅∥2\lVert\cdot\rVert_2 from the query in [0,1]100[0, 1]^{100}, divided by their mean
minmax
  • distances to 500 points in d = 100
  • same distances at d = 2, for reference
  • nearest neighbor
  • farthest point
Fraction of [0,1]d[0, 1]^d volume inside the inscribed ball of radius 1/21/2 (log scale)
d = 100: 1.87e−70, off scale
100
Horizontal axis
Query
Metric
Mean and standard deviation of distance3.996 and 0.222
Coefficient of variation σ/μ\sigma/\mu0.0557
dmin⁡d_{\min} and dmax⁡d_{\max}3.161 and 4.594
Relative contrast (dmax⁡−dmin⁡)/dmin⁡(d_{\max} - d_{\min})/d_{\min}0.453
Cube volume within the inscribed ball1.87e−70
Side of subcube containing 1% of the data0.955
At d=100d = 100 the farthest point is only 45 % farther than the nearest: the “nearest neighbor” is barely distinguishable from the rest.
Explicit model: 500 uniform points in [0,1]d[0, 1]^d and a uniform query (or the center of the cube), generated with a fixed seed; increasing dd only adds coordinates to the same points. Above, the histogram of the 500 distances to the query, divided by their mean by default; vertical lines mark the nearest neighbor and the farthest point, and the dashed outline is the histogram of the same distances with d=2d = 2. Below, the exact fraction of cube volume within the inscribed ball, on a logarithmic scale.

In d=2d = 2 the farthest is tens of times farther than the nearest; in d=1000d = 1000 the relative histogram is a needle and contrast is around 10%. With the query at the cube’s center the needle is even thinner: each coordinate contributes (Xj−12)2(X_j - \tfrac12)^2, with mean 1/121/12 and variance 1/1801/180, and the coefficient of variation becomes 12d/180/(d/12)≈0.447/d\tfrac12\sqrt{d/180}/(d/12) \approx 0.447/\sqrt d. Also switch to Manhattan: with d=1000d = 1000 and a random query it retains 13% contrast versus Euclidean’s 9.5%. This is the effect described by Aggarwal, Hinneburg and Keim: somewhat more contrast, the same fall toward zero.

How much data is needed

Concentration is a stability problem; the statistical problem is the rate. Stone (1982) proved that, if ff has bounded derivatives up to order ss, the best squared error achievable by any nonparametric regression estimator with nn data points in Rd\R^d decreases as n−2s/(2s+d)n^{-2s/(2s + d)}, and local methods (k-NN with well-chosen kk for s=1s = 1, local regression for larger ss) attain it. With s=2s = 2, the rate is n−4/(4+d)n^{-4/(4 + d)}: n−0.8n^{-0.8} in one dimension and n−0.29n^{-0.29} in ten. To reach error ε\eps requires on the order of ε−(2s+d)/(2s)\eps^{-(2s + d)/(2s)} data points, an amount which, with fixed ε\eps, grows exponentially with dd. This is not a defect of k-NN: it is the price of assuming nothing beyond smoothness.

Why k-NN works despite everything

If this were the whole story, neighbors in R768\R^{768} (the typical dimension of a text embedding) would be useless, yet they underpin semantic search. The answer is that real data do not fill the space: their intrinsic dimension is much smaller than that of the space they inhabit, and that dimension, not the ambient one, governs concentration and rates. The cell measures both aspects: the exact figures in this section and an experiment with a two-dimensional signal augmented with irrelevant variables, versus the same signal embedded in the same space without adding noise.

[ ]The curse, in numbersBrowser
import numpy as np
from scipy.special import gammaln
from sklearn.neighbors import KNeighborsClassifier

print("  d   bola inscrita / cubo   lado para el 1 %   lado para el 10 %   mediana al más próximo (N = 500)")
for d in (1, 2, 3, 5, 10, 20, 50, 100):
    frac = np.exp(d / 2 * np.log(np.pi) - gammaln(d / 2 + 1) - d * np.log(2))
    med = (1 - 0.5 ** (1 / 500)) ** (1 / d)
    print(f"{d:3d}   {frac:20.3e}   {0.01 ** (1 / d):16.3f}   {0.1 ** (1 / d):17.3f}   {med:12.3f}")

rng = np.random.default_rng(0)
print("\n   d   media      σ/μ     σ/μ·√d   (d_max − d_min)/d_min     (500 puntos y una consulta uniformes)")
for d in (2, 10, 100, 1000):
    X = rng.uniform(size=(500, d))
    q = rng.uniform(size=d)
    D = np.sqrt(((X - q) ** 2).sum(1))
    print(f"{d:4d}   {D.mean():6.3f}   {D.std() / D.mean():.4f}   {D.std() / D.mean() * np.sqrt(d):.3f}   {(D.max() - D.min()) / D.min():10.3f}")

def problema(n, ruido):
    """Señal en 2 coordenadas (clases en (±1, 0)) más `ruido` coordenadas N(0, 1) irrelevantes."""
    y = rng.integers(0, 2, n)
    S = rng.standard_normal((n, 2))
    S[:, 0] += np.where(y == 1, 1.0, -1.0)
    return np.hstack([S, rng.standard_normal((n, ruido))]), y

print("\nvariables añadidas   exactitud 5-NN con ruido   misma señal girada a 2 + ruido dimensiones, sin ruido")
for ruido in (0, 2, 8, 30, 100):
    X, y = problema(500, ruido)
    Xt, yt = problema(5000, ruido)
    acc = np.mean(KNeighborsClassifier(5).fit(X, y).predict(Xt) == yt)
    Qm, _ = np.linalg.qr(rng.standard_normal((2 + ruido, 2 + ruido)))     # isometría de R² en R^(2 + ruido)
    acc_i = np.mean(KNeighborsClassifier(5).fit(X[:, :2] @ Qm[:2], y).predict(Xt[:, :2] @ Qm[:2]) == yt)
    print(f"{ruido:18d}   {acc:24.3f}   {acc_i:10.3f}")

The first table reproduces the figures in the text: 2.49×10−32.49 \times 10^{-3} of volume in the inscribed ball in d=10d = 10 and 1.87×10−701.87 \times 10^{-70} in d=100d = 100, sides of 0.6310.631 and 0.7940.794 for 1% and 10% in d=10d = 10, and median 0.5180.518 to the nearest neighbor. The second confirms the 0.548/d0.548/\sqrt d law: the product σ/μ⋅d\sigma/\mu \cdot \sqrt d stays between 0.540.54 and 0.590.59 in every dimension, while relative contrast falls from 40.740.7 in d=2d = 2 to 0.3570.357 in d=100d = 100 and 0.1060.106 in d=1000d = 1000. The third is the practical lesson. With the signal in two coordinates, adding 100 noise variables reduces 5-NN accuracy from 0.8260.826 to 0.6890.689, over 40% of the way toward chance (0.50.5): noise dominates the distances. But if the same signal is embedded in 102 dimensions via an isometry, accuracy does not change (0.8240.824), because distances are exactly the same. What hurts is not dimensions, but irrelevant dimensions that add variance to distance. That is why k-NN works after good feature selection, dimensionality reduction, or a learned representation concentrating information in few directions.

Efficient search: KD trees and ball trees

Brute-force prediction costs O(nd)\bigO(nd) per query: with n=107n = 10^7 vectors of dimension 100, 10910^9 operations per query. k-NN has moved all training cost to inference. The algorithmic question is whether points can be discarded without computing their distance. In one dimension, yes: sort the data and search a binary tree to find the neighbor in O(log⁡n)\bigO(\log n). A KD tree (Bentley, 1975) generalizes that idea to dd dimensions.

Searching for the nearest neighbor of q\vb{q} in a KD tree is a depth-first search with pruning:

  1. Descend on the side of the split containing q\vb{q} to a leaf and compute distances to its points. The best so far, δ\delta, is an upper bound on the answer.
  2. On returning through each node, look at the other side. If ∣qj−s∣≥δ\abs{q_j - s} \ge \delta, prune it entirely: none of its points can improve on δ\delta. Otherwise, explore it the same way.

Pruning is correct by a one-line inequality: every point z\vb{z} on the other side has zjz_j on the other side of ss, so ∥q−z∥≥∣qj−zj∣≥∣qj−s∣≥δ\norm{\vb{q} - \vb{z}} \ge \abs{q_j - z_j} \ge \abs{q_j - s} \ge \delta. Serious implementations use a stronger version, the distance from q\vb{q} to the box enclosing the node’s points, which is never less than ∣qj−s∣\abs{q_j - s}. In a ball tree the bound follows from the triangle inequality: every point in the ball (c,r)(\vb{c}, r) is at distance at least ρ(q,c)−r\rho(\vb{q}, \vb{c}) - r, and the ball is pruned if that is ≥δ\ge \delta. Because it uses only the triangle inequality, a ball tree works for any metric, not only axis-aligned norms.

InteractiveSearching a KD tree
Nearest-neighbor search: current best ball (magenta), calculated distances (blue) and pruned cells (gray)
step 18 of 18
  • xx split
  • yy split
  • distance computed
  • not computed (hollow)
  • best neighbor and its ball
  • pruned cell
The same algorithm with n=4000n = 4000 uniform points in [0,1]d[0, 1]^d: mean fraction of points whose distance is calculated (40 queries)
d = log₂ n
Phase
2
Distances computed11 of 40
Best distance so far0.054
Final total11 of 40 (28 %)
With d=2d = 2 and n=4000n = 4000: distances per query18 (0.5 %)
Splits per coordinate on a root-to-leaf path, log⁡2n/d\log_2 n / d5.98
On backtracking: the split is 0.244 ≥ 0.054 away (current best). Prune the cell with 9 points without checking them.
Above, 40 uniform points with a fixed seed and a Bentley KD tree (one point per node, alternating cuts on xx and yy at the cell median). In ‘Build’, cuts appear in breadth-first order, thicker the closer they are to the root. In ‘Search’, play the search step by step: the dashed ball is that of the best neighbor so far, and gray cells are pruned without computing any distance. Below, the same algorithm with 4000 uniform points in [0,1]d[0, 1]^d and 40 queries, computed in your browser: mean fraction of points whose distance must be computed.

In the plane, for the initial query, the search computes 11 of the 40 distances: after finding a good candidate early, distant cells are pruned with one comparison each. With 40 points the savings are modest because the tree has only 6 levels; what matters is how it scales. The lower panel shows this, and also the problem. With 4000 points, the algorithm computes 0.5% of distances in d=2d = 2 and 0.7% in d=3d = 3, but the fraction grows with dd: 17% in d=8d = 8, 87% in d=12d = 12 and 99% in d=15d = 15, already indistinguishable from brute force. There are two reasons. First, a root-to-leaf path has around log⁡2n≈12\log_2 n \approx 12 cuts: with dd larger than that, some coordinates are divided by no cut on that path, and cells are extremely long slabs in those directions. Second, because of concentration, distance δ\delta to the best candidate is comparable to the distance to almost any point, whereas separation ∣qj−s∣\abs{q_j - s} along one coordinate is a small fraction of it: the pruning condition almost never holds. Friedman, Bentley and Finkel (1977) proved expected search time is logarithmic in nn for fixed dd, but with a constant that grows exponentially with dd; the rule of thumb is that a KD tree pays off only when n≫2dn \gg 2^d.

[ ]A KD tree from scratch and its degradation with dimensionBrowser
import heapq
import numpy as np
from sklearn.neighbors import KDTree, BallTree

class ArbolKD:
    """Árbol KD con hojas de hasta `hoja` puntos: corte por la coordenada de mayor rango, en la mediana."""
    def __init__(self, X, hoja=16):
        self.X, self.hoja = X, hoja
        self.nodos = []                          # (lo, hi, idx, dim, corte, izq, der)
        self.raiz = self._construir(np.arange(len(X)))

    def _construir(self, idx):
        P = self.X[idx]
        lo, hi = P.min(0), P.max(0)              # caja que envuelve los puntos del nodo
        nodo = len(self.nodos)
        self.nodos.append(None)
        if len(idx) <= self.hoja:
            self.nodos[nodo] = (lo, hi, idx, -1, 0.0, -1, -1)
            return nodo
        dim = int(np.argmax(hi - lo))
        orden = idx[np.argsort(P[:, dim], kind="stable")]
        m = len(orden) // 2
        izq, der = self._construir(orden[:m]), self._construir(orden[m:])
        self.nodos[nodo] = (lo, hi, None, dim, self.X[orden[m], dim], izq, der)
        return nodo

    def consulta(self, q, k=1):
        """Los k vecinos de q (índices y distancias) y, en self.n_dist, las distancias punto a punto calculadas."""
        mejores = []                              # montículo de (−dist², índice): en la raíz, el peor de los k
        self.n_dist = 0
        def dist_caja(nodo):                      # distancia² de q a la caja del nodo (0 si q está dentro)
            lo, hi = self.nodos[nodo][:2]
            return float((np.maximum(lo - q, 0) ** 2 + np.maximum(q - hi, 0) ** 2).sum())
        def radio2():
            return -mejores[0][0] if len(mejores) == k else np.inf
        def visitar(nodo):
            lo, hi, idx, dim, corte, izq, der = self.nodos[nodo]
            if idx is not None:                   # hoja: distancias de verdad
                d2 = ((self.X[idx] - q) ** 2).sum(1)
                self.n_dist += len(idx)
                for i, v in zip(idx, d2):
                    if v < radio2():
                        heapq.heappush(mejores, (-v, i))
                        if len(mejores) > k:
                            heapq.heappop(mejores)
                return
            cerca, lejos = (izq, der) if q[dim] < corte else (der, izq)
            visitar(cerca)                        # primero el lado de la consulta
            if dist_caja(lejos) < radio2():       # poda: toda la caja está más lejos que el k-ésimo actual
                visitar(lejos)
        visitar(self.raiz)
        res = sorted((-v, i) for v, i in mejores)
        return np.array([i for _, i in res]), np.sqrt([v for v, _ in res])

rng = np.random.default_rng(0)
X = rng.uniform(size=(2000, 3))
q = rng.uniform(size=3)
arbol = ArbolKD(X)
idx, dist = arbol.consulta(q, k=5)
print("mismos 5 vecinos que la fuerza bruta:", np.array_equal(idx, np.argsort(((X - q) ** 2).sum(1))[:5]),
      f"  distancias calculadas: {arbol.n_dist} de {len(X)}")

print("\n  d   fracción de distancias calculadas por consulta (1-NN, n = 2000, 20 consultas)")
print("      desde cero   KDTree   BallTree")
for d in (2, 4, 8, 16, 32):
    X = rng.uniform(size=(2000, d))
    Q = rng.uniform(size=(20, d))
    arbol = ArbolKD(X, hoja=16)
    cuenta = []
    for q in Q:
        arbol.consulta(q)
        cuenta.append(arbol.n_dist)
    res = []
    for Arbol in (KDTree, BallTree):
        t = Arbol(X, leaf_size=16)
        t.reset_n_calls()
        t.query(Q, k=1)
        res.append(t.get_n_calls() / len(Q) / len(X))
    print(f"{d:3d}   {np.mean(cuenta) / len(X):10.3f}   {res[0]:6.3f}   {res[1]:8.3f}")

Our tree returns the same 5 neighbors as brute force while computing 47 distances out of 2000. The table measures degradation: the fraction of distances computed goes from around 1% in d=2d = 2 to over 90% in d=16d = 16 and 100% in d=32d = 32, where the tree only adds work. Scikit-learn’s trees, which count distances with get_n_calls, follow the same curve. In the ball tree the counter also includes distances from the query to ball centers, which is why it exceeds 100% in high dimensions: pruning does not even pay for checking it. On real data with low intrinsic dimension, a ball tree often degrades more slowly than a KD tree, because its balls adapt to the shape of the data rather than the axes.

When even trees fail, exactness is sacrificed: approximate search indexes, such as navigable proximity graphs (HNSW) or inverted files with quantization, find neighbors that are almost always the true ones in sublinear time even with dd in the hundreds. They power vector databases and you will see them when studying retrieval for RAG.

The scikit-learn version

Everything in this lesson is in sklearn.neighbors: KNeighborsClassifier and KNeighborsRegressor (with weights="uniform" or "distance" and any metric in metric), RadiusNeighborsClassifier (all neighbors within a radius instead of kk), NearestNeighbors for searching without predicting, and structures KDTree and BallTree. Parameter algorithm selects the search: "brute", "kd_tree", "ball_tree" or "auto". With "auto", scikit-learn uses brute force if data have more than 15 columns, if k≥n/2k \ge n/2, if data are sparse, or if the metric is unsupported by a tree; otherwise it uses a KD tree when the metric permits it, and a ball tree otherwise. This is the previous section’s rule written in code.

[ ]Which search scikit-learn choosesBrowser
from sklearn.neighbors import KNeighborsClassifier

rng = np.random.default_rng(0)
for d, metrica in ((3, "minkowski"), (15, "minkowski"), (16, "minkowski"), (3, "cosine"), (3, "haversine")):
    X = rng.uniform(size=(1000, 2 if metrica == "haversine" else d))
    modelo = KNeighborsClassifier(5, metric=metrica).fit(X, rng.integers(0, 2, 1000))
    print(f"d = {X.shape[1]:2d}, métrica {metrica:9s} -> {modelo._fit_method}")

The attribute _fit_method is internal, but shows the decision: KD tree up to 15 columns, brute force from 16 onward and also for cosine (which is not a metric, so no tree supports it), and ball tree for haversine distance on the sphere, which is a metric but does not decompose by axis.

Common mistakes

Exercises

QuizMeters and millimeters
You classify using k-NN with Euclidean distance and two variables with similar real-world ranges: a length measured in meters and another in millimeters. You do not scale. What happens?
QuizA perfect model
A colleague shows you a k-NN with k=1k = 1 and 0% training error, and concludes that this is the best value of kk. What do you say?
NumericThe ball inside the cube
What fraction of the volume of the unit cube [0,1]10[0, 1]^{10} lies inside the inscribed ball of radius 1/21/2?
NumericA neighborhood that is not local
You have uniform data in [0,1]10[0, 1]^{10} and want a subcube containing, on average, 1% of them. What side length does it need?
Numeric1-NN on a specific problem
Let X∼U[0,1]X \sim \mathrm{U}[0, 1] and P(Y=1∣X=x)=x2\Pr(Y = 1 \given X = x) = x^2. What is the asymptotic error of the nearest-neighbor rule as n→∞n \to \infty?
ProofThe Cover–Hart bound
Prove: In binary classification with continuous η(x)=P(Y=1∣X=x)\eta(\vb{x}) = \Pr(Y = 1 \given X = \vb{x}), the 1-NN rule's error satisfies ERn→E[2η(X)(1−η(X))]≤2R∗(1−R∗)\E R_n \to \E[2\eta(X)(1 - \eta(X))] \le 2R^*(1 - R^*), where R∗=E[min⁡(η(X),1−η(X))]R^* = \E[\min(\eta(X), 1 - \eta(X))].
0
Write r(x)=min⁡(η(x),1−η(x))r(\vb{x}) = \min(\eta(\vb{x}), 1 - \eta(\vb{x})) and X(1)X_{(1)} for the nearest neighbor of XX among nn iid points.

Step 1 of 4. Why does X(1)(x)→xX_{(1)}(\vb{x}) \to \vb{x} for almost every x\vb{x}?

QuizA tree for embeddings
You have n=106n = 10^6 embeddings of dimension d=100d = 100 and want each query's exact nearest neighbor. You build a KD tree with one-point leaves. What do you expect?
QuizThe boundary
You fit Nadaraya–Watson regression with a Gaussian kernel to uniform data in [0,1][0, 1], and at x0=0x_0 = 0 the estimate is systematically above the increasing truth. What change reduces this bias in order of magnitude?
QuizWhere the cost lies
You compare logistic regression and brute-force k-NN, both with n=106n = 10^6 examples of dimension d=50d = 50. Which statement is correct?
Codek-NN classification like scikit-learn
Implement knn_predict(X_train, y_train, X_test, k, weights) for classification with Euclidean distance, without Python loops over test points. weights is 'uniform' (majority vote) or 'distance' (each neighbor votes with weight 1/ρ1/\rho; if a query is at distance 0 from any neighbor, only neighbors at distance 0 vote, with weight 1). Labels may be arbitrary integers or strings. Vote ties go to the lowest class in order (the first in np.unique(y_train)), as in scikit-learn. Tests compare your output with KNeighborsClassifier on continuous data, including vote ties with even kk and queries coinciding with training points.
import numpy as np

def knn_predict(X_train, y_train, X_test, k, weights="uniform"):
  """Clase predicha para cada fila de X_test por los k vecinos más próximos (euclídea)."""
  X_train = np.asarray(X_train, dtype=float)
  X_test = np.asarray(X_test, dtype=float)
  y_train = np.asarray(y_train)
  # tu código: distancias con la identidad, índices de los k vecinos, votos (ponderados) y desempate
  return np.full(len(X_test), y_train[0])
Shift+Enter to run

Summary

Key idea
k-NN predicts by copying what happened to the most similar examples. Its behavior rests on two choices: kk (or bandwidth), which sets the bias–variance tradeoff, and the metric with scaling, which determines what similar means. It works when neighbors are truly local, which in high dimensions happens only if the data have low intrinsic dimension.
  • The rule votes (classification) or averages (regression) the labels of the kk closest examples, with uniform or 1/ρ1/\rho weights. With k=1k = 1 the boundary is that of Voronoi cells; kk controls smoothness, with n/kn/k effective degrees of freedom, and is chosen by cross-validation because training error for k=1k = 1 is always 0.
  • k-NN is Nadaraya–Watson with a uniform kernel and adaptive bandwidth. Nadaraya–Watson has bias of order hh at the boundary; local linear regression reduces it to order h2h^2 because its weights satisfy ∑ili(x0)(xi−x0)=0\sum_i l_i(x_0)(x_i - x_0) = 0.
  • Euclidean distance is not invariant to scaling a single variable: without scaling, the variable with greatest variance decides the neighbors. Standardize inside the pipeline; cosine distance is equivalent to Euclidean on normalized vectors and Mahalanobis to Euclidean after whitening.
  • With k→∞k \to \infty and k/n→0k/n \to 0, k-NN is universally consistent (Stone, 1977). With k=1k = 1, its asymptotic error is E[2η(1−η)]\E[2\eta(1 - \eta)], between R∗R^* and 2R∗(1−R∗)2R^*(1 - R^*) (Cover and Hart, 1967); in the lesson’s Gaussian problem, 0.22480.2248 versus R∗=0.1587R^* = 0.1587.
  • In high dimensions distances concentrate (coefficient of variation ≈0.548/d\approx 0.548/\sqrt d for uniform data), neighborhoods cease to be local (0.011/10=0.6310.01^{1/10} = 0.631), and rates degrade as n−4/(4+d)n^{-4/(4+d)}. Irrelevant variables hurt; dimensions that add no variance to distance do not.
  • KD trees and ball trees prune with a one-line inequality and search in nearly logarithmic time when n≫2dn \gg 2^d; in high dimensions they degenerate to brute force, and scikit-learn stops using them above 15 columns. For embeddings, approximate search (HNSW) takes over.