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
- 11Statistical functional elicited by a lossk-fold cross-validationPreprocessing and model pipelinesValidation curveCentering, standardization and the intercept
- 04Concentration of the normWeak law of large numbersMahalanobis distance
- 08Binary search treeAsymptotic notation for running time
- 02Vector norm
Motivation: learning without training
Every model you have seen in this topic compresses data into a few parameters: a vector 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 nearest neighbors rule (k-NN) formalizes that idea. It has no training phase: “training” means storing and . 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 , 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 points, k-NN is an algorithms problem: brute force costs per query. KD trees and ball trees reduce this to something close to 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 in the input space (for now, Euclidean distance). For a query point , sort the training examples by distance to ,
where is the -th neighbor of and its label, and break distance ties using a fixed rule (for example, the lower index). Call the set of indices of the first 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 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 . And distance ties, common with discrete variables, make the set depend on data order: two correct implementations can produce different predictions.
Voronoi and the role of k
With , the prediction at is the label of the nearest example, so space is partitioned into the examples’ Voronoi cells, , 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 the regions where the set of neighbors is constant form the order- Voronoi diagram, with broader regions and votes averaging more labels. Try it.
Three things you should have seen. With , the mislabeled point creates a class B island inside region A: 1-NN does not distinguish signal from noise, it memorizes both. As increases the island disappears and the boundary smooths. But if 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 , leave-one-out voting classifies all 36 B points as A. The curve below diagnoses this: the training error at 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 , a minimum of 11.3% at and 50.7% from onward, the error of always predicting A. Enable distance weights and look at the training error: it is 0 for every , because the point itself has weight . With distance weights, training error tells you nothing.
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 with , , and fix the training points (fixed design). The prediction at is the average of responses, , with independent noise, so the expected error for a new observed at is
The first term is irreducible. The third, variance, decreases as . The second, squared bias, grows with because neighbors move away from and 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 , row of equals in the columns of the neighbors of , including itself if there are no duplicate points. Thus and the effective degrees of freedom are
With you have as many “parameters” as data points; with , just one (the global mean). This is the same scale on which you measured ridge: a rule with degrees of freedom behaves like a model with parameters.
From scratch, without loops
The expensive operation is the distance matrix between the queries and examples. Computing it with two nested Python loops is slow; NumPy broadcasting, ((A[:, None] - B[None]) ** 2).sum(-1), materializes a tensor of numbers. The solution is the identity
which turns the work into a matrix product plus two vectors of norms: memory and computation delegated to the best-optimized operation in any numerical library. This is what sklearn.metrics.pairwise.euclidean_distances does.
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 is exactly : 300, 60 and 15. The last part is a warning worth knowing. If the data are far from the origin (shifted with a spread of ), and are numbers of order whose difference is of order : 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 neighbors has two visible flaws. It is discontinuous: when moves and a neighbor enters or leaves , the prediction jumps. And it weights the nearest neighbor equally with the -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 (the Gaussian , or the tricube on ) and a bandwidth , write .
These estimators form the family of local regression and kernel smoothing, and k-NN is one member: the mean of the neighbors is Nadaraya–Watson with the uniform kernel and an adaptive bandwidth, . Where there are many data points the window narrows; where there are few it widens. The bandwidth is the continuous counterpart of : it controls the same bias–variance tradeoff. With effective data points in the window, variance is of order and, in the interior and for twice differentiable , bias is of order ; balancing them gives and squared error decreasing as , 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 using a Taylor expansion of at :
Proof
A weighted least-squares fit with a line exactly reproduces any line: if for every , the sum of squares vanishes at , the unique minimum by invertibility, and . By linearity, for all . With we obtain the first equality and with the second. For Nadaraya–Watson, sums to 1, but is the center of mass of the weights relative to , which vanishes only if the data are distributed symmetrically around .
∎In the interior, with dense data, the center of mass of the Nadaraya–Watson weights is nearly and the term nearly cancels. At the left boundary of , however, all data lie to the right: with the Gaussian kernel and uniform data, for , and bias is of order , not . This is boundary bias. In the interior there is a weaker version of the same phenomenon: if the density of the is nonuniform, the center of mass of the weights shifts toward more data, and Nadaraya–Watson has a design bias (with a Gaussian kernel) added to the 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.
With at the left boundary, Nadaraya–Watson places all weights to the right of , where grows rapidly (), and its mean remains well above . Switch to local linear: the 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.
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 and with , Nadaraya–Watson has bias , close to the first-order prediction , and local linear . With , versus . At , where , both have the same bias, and with , as predicted by (with , and versus : higher-order terms already matter there). The cost is in the standard deviation column: at the boundary local linear has versus , 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 everywhere, paid for with variance only where unavoidable.
What it means to be close: metrics and scaling
Everything above depends on , and is not supplied by the data: you choose it. The most common choices are these.
- Minkowski , with : the norm of the difference. is Euclidean, is Manhattan (sum of absolute differences, less sensitive to a coordinate with an extreme value), and is Chebyshev, . With the triangle inequality fails and it is no longer a metric.
- Cosine, : compares directions and ignores norms, natural for text (frequency vectors) and embeddings. It is not a metric, but for unit vectors , so cosine distance orders neighbors just like Euclidean distance on normalized vectors: normalize and use any Euclidean search structure.
- Mahalanobis, , with the data covariance: the Mahalanobis distance. If (Cholesky), : it is Euclidean distance after whitening the data, so it is invariant under any invertible affine transformation of the variables (provided 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, : 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 , as is its contribution to distance. The other variables disappear from the neighborhood.
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.
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, , and write . No rule can improve on the Bayes rule , which errs with probability at each . Its error,
is the Bayes error, the part no amount of data can eliminate because it belongs to the law of itself. In learning theory you will formalize it as irreducible error. The error of a rule trained on data points, , always satisfies .
Consistency. Stone (1977) proved that if and , the -neighbor rule is universally consistent: for any distribution of in (with Euclidean norm and distance ties broken randomly). This is remarkable: no assumptions on , neither continuity nor density. The two conditions have a direct interpretation: makes vote variance vanish, and makes the neighbors increasingly close to , so bias vanishes too. You will study this in detail, along with the absence of universal convergence rates, in universal consistency.
What if 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 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 is continuous; the general case approximates by continuous functions.
Step 1: the neighbor converges to the query. Let be the law of and a point in its support, so for every . The nearest neighbor is farther than only if the data points fall outside the ball, so
and since does not grow with , convergence is almost sure. The support has measure 1, so almost surely.
Step 2: conditional error. Condition on and the training inputs. The neighbor is fixed; its label is Bernoulli with parameter and independent of the query label , which is Bernoulli with parameter . The rule errs if they differ:
Step 3: limit. By step 1 and continuity of , that probability tends to almost surely. It is bounded by 1, so dominated convergence gives .
Step 4: the bounds. Since , we have . Lower bound: because ; integrating, . Upper bound: is concave, so Jensen’s inequality gives , that is, . Equivalently, .
∎The last equality says exactly when each extreme is reached. The upper bound holds if and only if : noise is the same everywhere. The lower bound holds if and only if almost surely, that is, : 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 is intermediate: is maximal at .
The same idea gives the asymptotic error for fixed odd . The neighbors converge to , their labels are independent Bernoulli variables with parameter , and the rule fails if the majority does not match :
For each , the probability that the majority of votes (odd) is correct increases with (Condorcet’s jury theorem), so decreases with toward , without reaching it for any fixed except in the extreme cases.
Explore the four families. With constant , the blue point travels along the red curve: 1-NN reaches the bound. With 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 is far from 0 and , around , where is large. The aqua points, 3-NN and 5-NN, approach : with , excess over falls from for 1-NN to for 3-NN and 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 , with , and priors , the density ratio gives : only the first coordinate matters, and asymptotic errors reduce to one-dimensional integrals.
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 and the Cover–Hart bound is . 1-NN converges to , within the band and well below the ceiling, and does so quickly in two dimensions: from onward estimates are already around and do not improve when multiplying data by 100, because with more data do not reduce vote variance. By contrast, 15-NN approaches its limit , already very close to . With , 15-NN is worse than 1-NN: 15 neighbors out of 20 data points are no longer local.
We still need to choose 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.
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 and is nearly flat thereafter: here varies slowly (the Bayes boundary is a straight line), so averaging many neighbors adds little bias. Cross-validation chooses , with CV error , and on the independent test set that model errs , matching 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 is , so the correct statement is that it is indistinguishable from at that resolution. No rule can have true error below , but an estimate can fall below it due to noise (with 2000 CV points the standard deviation is of order ) 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 neighbors of are close to . Stone’s theorem guarantees this when , 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 in has volume . The ball inscribed in the cube has radius , so it contains a fraction
of the cube: in the plane, in space, and in . The rest is in the corners, farther than 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 data points are uniform in and you want a cubic neighborhood containing a fraction of them (for example, neighbors). Its side must be . For 1% of the data, , , and ; for 10%, (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 uniform points in the unit ball of , the median distance from the origin to the nearest point is
which with and equals : 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 and points uniform in . Each is a sum of independent bounded terms, so by the law of large numbers it concentrates around its mean, which grows as , with fluctuations of order . If is also uniform, the mean per coordinate is and the conditional variance per coordinate, averaged over , is . A first-order expansion of the square root gives the distance’s coefficient of variation:
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 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 . Replacing Euclidean with Manhattan does not fix it: the theorem’s hypothesis holds for any with independent coordinates. Aggarwal, Hinneburg and Keim (2001) observed that norms with small retain more contrast than those with large , but all lose it.
In the farthest is tens of times farther than the nearest; in 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 , with mean and variance , and the coefficient of variation becomes . Also switch to Manhattan: with 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 has bounded derivatives up to order , the best squared error achievable by any nonparametric regression estimator with data points in decreases as , and local methods (k-NN with well-chosen for , local regression for larger ) attain it. With , the rate is : in one dimension and in ten. To reach error requires on the order of data points, an amount which, with fixed , grows exponentially with . 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 (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.
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: of volume in the inscribed ball in and in , sides of and for 1% and 10% in , and median to the nearest neighbor. The second confirms the law: the product stays between and in every dimension, while relative contrast falls from in to in and in . The third is the practical lesson. With the signal in two coordinates, adding 100 noise variables reduces 5-NN accuracy from to , over 40% of the way toward chance (): noise dominates the distances. But if the same signal is embedded in 102 dimensions via an isometry, accuracy does not change (), 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 per query: with vectors of dimension 100, 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 . A KD tree (Bentley, 1975) generalizes that idea to dimensions.
Searching for the nearest neighbor of in a KD tree is a depth-first search with pruning:
- Descend on the side of the split containing to a leaf and compute distances to its points. The best so far, , is an upper bound on the answer.
- On returning through each node, look at the other side. If , prune it entirely: none of its points can improve on . Otherwise, explore it the same way.
Pruning is correct by a one-line inequality: every point on the other side has on the other side of , so . Serious implementations use a stronger version, the distance from to the box enclosing the node’s points, which is never less than . In a ball tree the bound follows from the triangle inequality: every point in the ball is at distance at least , and the ball is pruned if that is . Because it uses only the triangle inequality, a ball tree works for any metric, not only axis-aligned norms.
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 and 0.7% in , but the fraction grows with : 17% in , 87% in and 99% in , already indistinguishable from brute force. There are two reasons. First, a root-to-leaf path has around cuts: with 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 to the best candidate is comparable to the distance to almost any point, whereas separation 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 for fixed , but with a constant that grows exponentially with ; the rule of thumb is that a KD tree pays off only when .
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 to over 90% in and 100% in , 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 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 ), 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 , 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.
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
Step 1 of 4. Why does for almost every ?
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 ; 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 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])Summary
- The rule votes (classification) or averages (regression) the labels of the closest examples, with uniform or weights. With the boundary is that of Voronoi cells; controls smoothness, with effective degrees of freedom, and is chosen by cross-validation because training error for is always 0.
- k-NN is Nadaraya–Watson with a uniform kernel and adaptive bandwidth. Nadaraya–Watson has bias of order at the boundary; local linear regression reduces it to order because its weights satisfy .
- 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 and , k-NN is universally consistent (Stone, 1977). With , its asymptotic error is , between and (Cover and Hart, 1967); in the lesson’s Gaussian problem, versus .
- In high dimensions distances concentrate (coefficient of variation for uniform data), neighborhoods cease to be local (), and rates degrade as . 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 ; in high dimensions they degenerate to brute force, and scikit-learn stops using them above 15 columns. For embeddings, approximate search (HNSW) takes over.