Deriving k-Nearest Neighbors (ML #5)
Your model’s accuracy is 62% and the ML lead says “just try k-NN, it’s simpler.” She’s right about the implementation — there’s no training step, about twenty lines of code — and catastrophically wrong about the outcome. The version you ship gets 51%, and the reason is pure geometry: in high dimensions, “nearest” stops meaning anything.
k-NN is the rare algorithm whose entire inductive bias is the shape of the distance function. So the algorithm can only be understood by deriving what distance actually measures, and — more usefully — by deriving exactly where that measure breaks. That failure has a name and a precise mechanism.
This chapter derives k-NN’s decision rule, proves the two regimes \(k\) lives in (bias vs variance), and quantifies the curse of dimensionality so you can recognize it in your own data.
The algorithm is trivial; the derivation is not
Given training set \((x_1, y_1), \dots, (x_n, y_n)\) and a query \(x_*\), k-NN predicts by majority vote among the \(k\) closest training points:
\[ \hat{y}_* = \arg\max_{c \in \mathcal{Y}} \sum_{i \in \mathcal{N}_k(x_*)} \mathbb{1}\left[ y_i = c \right] \]
That’s the whole rule. The substance is in the two implicit choices: what distance and what \(k\).
import numpy as np
def knn_predict(X_train, y_train, X_query, k=5):
"""Majority vote among the k nearest training rows."""
# squared euclidean distance via the ||a-b||^2 = |a|^2 - 2a.b + |b|^2 trick
d2 = ((X_query[:, None, :] - X_train[None, :, :]) ** 2).sum(-1)
idx = np.argsort(d2, axis=1)[:, :k]
votes = y_train[idx].mean(axis=1)
classes = np.unique(y_train)
return classes[votes.argmax(axis=1)] # majority class
No loss function, no gradient, no parameters — the training set is the model. This is the “lazy learner”: cost moves entirely to inference, where each prediction is \(O(nd)\) to sort the neighbors.
The distance choice is not free, and there is a derivation for preferring Euclidean. “Nearest” only means something relative to a notion of similarity, and Euclidean squared wins under the assumption that features are standardized and independent: minimizing \(\lVert x - x_i\rVert_2^2\) is then equivalent to maximizing the data’s own log-likelihood,
\[ \Pr(x \mid \text{data}) \propto \exp\!\left(-\tfrac{1}{2\sigma^2}\lVert x - \mu\rVert_2^2\right) \]
so nearest-neighbor classification is a generative model with spherical, equal-variance Gaussians centred on each training point. Where that assumption fails — correlated features, wildly different variances — a better metric exists, and no amount of tuning \(k\) fixes it. Chapter 9 reaches the same conclusion about the RBF kernel’s \(\gamma\), from the opposite direction.
What distance actually computes
Squared Euclidean distance between \(x\) and \(x_i\):
\[ \|x - x_i\|^2 = (x - x_i)^\top(x - x_i) = \|x\|^2 - 2x^\top x_i + \|x_i\|^2 \]
Expand the square and collect terms. The \(\lVert x\rVert^2\) term is constant across all \(i\) for a fixed query, so it doesn’t affect the ranking. That’s the whole justification for the matrix trick in the code above: you compute the full quadratic form but only the \(-2x^\top x_i + \lVert x_i\rVert^2\) part decides the ordering.
The decision boundary is the perpendicular bisector between the two nearest training points, which means k-NN’s boundaries are piecewise linear. With \(k=1\) the classifier is the union of Voronoi cells:
\begin{tikzpicture}[font=\rmfamily, >=stealth,
b/.style={draw, thick, rounded corners=4pt, minimum width=1.15cm, minimum height=1.15cm, align=center, font=\rmfamily\scriptsize}]
\fill[blue!10] (0,0) -- (3.6,0) -- (3.6,1.8) -- (0,1.8) -- cycle;
\fill[orange!16] (0,1.8) -- (3.6,1.8) -- (3.6,3.6) -- (0,3.6) -- cycle;
\fill[green!10] (3.6,0) -- (6.0,0) -- (6.0,3.6) -- (3.6,3.6) -- cycle;
\foreach \x/\y in {0.7/0.6,1.5/1.0,2.2/0.5,2.9/1.3,1.1/2.6,2.4/2.9,3.0/2.2}
\fill[blue!70!black] (\x,\y) circle (2pt);
\foreach \x/\y in {0.8/2.9,1.9/2.3,2.9/3.1,0.5/2.0}
\fill[orange!90!black] (\x,\y) circle (2pt);
\fill[green!45!black] (4.3,1.4) circle (2pt); \fill[green!45!black] (5.1,2.4) circle (2pt);
\draw[very thick] (3.6,0) -- (3.6,3.6);
\node[b, fill=blue!10] at (1.5,0.28) {class A};
\node[b, fill=orange!16] at (1.5,3.32) {class B};
\node[b, fill=green!10] at (4.8,0.28) {class C};
\node[font=\rmfamily\scriptsize, text=black!60] at (3,-0.55) {Voronoi cells: each training point owns its region};
\end{tikzpicture}
Note what this buys and costs. Boundaries can be arbitrarily complex — as wiggly as the data demands, unlike logistic regression’s single hyperplane (Chapter 3). But every cell is anchored to exactly one noisy training point, so \(k=1\) will happily build a lobe around a mislabeled outlier.
Deriving the bias–variance tradeoff in k
The one knob \(k\) controls variance and bias in opposite directions, and you can see it from the boundary structure alone.
\(k=1\) (maximum variance). Each prediction depends on a single training point. Change one label and that point’s entire Voronoi cell flips class. The classifier is a memorized lookup table: variance is maximal, training accuracy is 100%, and generalization error is high.
\(k \to \infty\) (maximum bias). Every prediction approaches the global majority class. The model collapses to a constant, losing all local structure: bias maximal, variance zero.
Intermediate \(k\) is the only useful setting, and its optimum is a smoothing bandwidth. This is a direct parallel to Chapter 4: \(k\) is to k-NN what \(1/\eta\) is to gradient descent, a smoothing scale with an underfitting/overfitting dial. On a well-conditioned problem (2,000 training points, 5 real features), accuracy does behave as the bias–variance story predicts:
| \(k\) | test accuracy | what’s happening |
|---|---|---|
| 1 | 0.821 | memorization, noisy boundary |
| 3 | 0.841 | |
| 5 | 0.853 | variance finally paying off |
| 11 | 0.880 | sweet spot: local detail + smoothing |
| 51 | 0.875 | over-smoothing, boundary flattening |
| 101 | 0.879 | plateau toward the global majority |
The optimum is broad and data-dependent, which is why people say “start with \(k = \sqrt{n}\)” — a rule of thumb, not a law. Always tune \(k\) by cross-validation (Chapter 13).
Deriving the curse of dimensionality
Here is the part that bites, and it’s worth deriving rather than memorizing.
In one dimension, a query point’s nearest neighbor is dramatically closer than a typical point — most of the interval around it is empty. Now ask what happens in 100 dimensions. Distance concentration: all pairwise distances in high dimensions converge toward each other, because the law of large numbers makes \(\sum_i (x_i - y_i)^2\) dominated by its large terms rather than concentrated in a few small ones.
The measurable signature is the ratio of mean nearest-neighbor distance to mean pairwise distance. If neighbors were genuinely special, the ratio would stay small:
| dimension \(d\) | mean 1-NN distance | mean pairwise distance | ratio |
|---|---|---|---|
| 1 | 0.0220 | 1.1573 | 0.019 |
| 2 | 0.1646 | 1.7674 | 0.093 |
| 3 | 0.4023 | 2.1939 | 0.183 |
| 5 | 0.9573 | 3.0363 | 0.315 |
| 10 | 2.1874 | 4.4063 | 0.496 |
| 20 | 3.4447 | 6.2515 | 0.551 |
| 50 | 7.1219 | 9.9656 | 0.715 |
| 100 | 11.1847 | 14.0641 | 0.795 |
Read the ratio column. In 1-D the nearest neighbor sits at 2% of the typical distance — “nearest” is a meaningful notion. By 100 dimensions the nearest neighbor is at 80% of it — everything is nearly equidistant, so the ranking that drives the whole algorithm is dominated by noise. There is no such thing as a near neighbor.
The consequence is measurable degradation on the same learning problem, adding only pure-noise features that carry zero signal:
| dimensions (5 signal + noise) | test accuracy (\(k=5\)) |
|---|---|
| 5 + 0 | 0.853 |
| 5 + 10 | 0.783 |
| 5 + 50 | 0.678 |
| 5 + 200 | 0.613 |
| 5 + 505 | 0.572 |
Monotone collapse toward chance (0.5) from features that are definitionally random. Linear and tree models are completely immune to this — a useless feature gets weight ~0 or an ignored split — but k-NN has no such mechanism, because it never learns that a feature is useless. It just lets the feature distort the distance.
The practical diagnosis. Compute your dataset’s \(d\). If \(d\) exceeds the number of training points, or if \(d \gtrsim 50\), plain k-NN will underperform and no choice of \(k\) will fix it. Three legitimate responses: reduce \(d\) first (PCA, Chapter 12; feature selection), use a distance metric that knows which dimensions matter (learned metrics, or per-feature scaling after removing noise features), or switch to an algorithm with an inductive bias that doesn’t depend on all dimensions being comparable (trees, Chapter 6).
# Diagnose before you deploy: does distance concentrate in your data?
def distance_concentration(X):
D = np.sqrt(((X[:, None, :] - X[None, :, :]) ** 2).sum(-1))
np.fill_diagonal(D, np.inf)
pairwise = D[np.isfinite(D)]
return D.min(axis=1).mean() / pairwise.mean()
print(round(distance_concentration(rng.normal(size=(400, 2))), 4)) # ~0.07, fine
print(round(distance_concentration(rng.normal(size=(400, 200))), 4)) # ~0.87, dead
The subtler failure: feature scaling
Since distance is a sum of per-feature contributions, any feature measured in larger units dominates. Income in dollars (~50,000) and age in years (~40) means the query’s nearest neighbor is chosen almost entirely by income; age contributes 0.08% of the squared distance. This is the same scale problem as Chapter 1, but for k-NN it is catastrophic rather than merely slow, because there is no gradient step to be slowed.
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier
knn = KNeighborsClassifier(n_neighbors=5)
knn.fit(StandardScaler().fit_transform(X_train), y_train) # never skip this
Skipping the scaler is the single most common k-NN bug. There is no accuracy warning; you just get a quietly worse model.
Pitfalls
- Skipping standardization. Large-unit features dominate the distance; the model looks merely mediocre rather than broken, so it’s easy to miss.
- High-dimensional input. Above ~50 dimensions, or \(d > n\), k-NN is near-useless by the argument above. Reduce dimension first.
- \(k=1\) in production. Training accuracy 100%, test accuracy whatever. The memorization trap.
- \(k\) too large. You converge to predicting the majority class and wonder why your “sophisticated” model matches a baseline.
- Treating it as a training algorithm. Training is \(O(1)\); inference is \(O(nd)\). On large \(n\) this dominates latency — use approximate nearest neighbors (ANN) or a tree index (
KDTree,BallTree, HNSW) before you optimize anything else. - High-cardinality categorical features. One-hot encoding 10,000 categories adds 10,000 dimensions of mostly-zero columns. k-NN has no native way to handle this.
Why does adding pure-noise features degrade k-NN so severely while leaving linear regression roughly unaffected? Derive the stability condition for gradient descent and explain why \(k\) is the analogous quantity for k-NN. Your 200-feature dataset gives k-NN 54% accuracy at \(k=5\); name two principled fixes and explain which is safer when you must serve a prediction for a specific known customer.
ASolution
k-NN never learns that a feature is uninformative — the feature enters directly through \(\|x - x_i\|^2\), so a pure-noise dimension adds \(d\) terms of variance to every pairwise distance and dilutes the signal terms; as the noise count grows the nearest-neighbor ratio tends to 1 (distance concentration) and the vote is effectively random, so accuracy falls toward chance. A linear model assigns the noise coefficient \(\approx 0\) by least squares and a tree simply never splits on it, which is why both are robust to this. On stability: gradient descent on a quadratic converges iff \(|1-\eta\lambda| < 1\), i.e. \(0 < \eta < 2/\lambda_{\max}\); \(k\) plays the same role as a smoothing bandwidth, with \(k=1\) the maximum-variance limit and \(k \to \infty\) the maximum-bias (constant-prediction) limit, so the bias–variance tradeoff is literally the same dial in a different parameterization. For the 200-feature case: PCA or supervised feature selection reduces \(d\) before distance is ever computed (safe and principled), and dropping the known-irrelevant features entirely is safer still for a specific-customer query — a query you can attribute to an individual should use a model whose per-prediction path you can audit, and shrinking the input space reduces the chance of an unlucky neighbor match rather than relying on the model to have learned to ignore noise. A third option, a learned or feature-weighted metric, is legitimate but needs its own validation since it reintroduces learned parameters.
Next: Deriving Decision Trees (ML #6) — where impurity functions come from, and why greedy splitting is the algorithm it is.