Nearest Neighbors
Predict like your neighbors: k-NN, distances and scaling.
k-nearest neighbors has no training phase and essentially one setting. Yet with enough data its error is within a factor of two of the best possible classifier, and with a slowly growing it reaches that optimum on every problem. This lesson makes the method precise: the rule and its ties, the choice of distance, as a bias–variance knob, the cost of a query, and the Cover–Hart bound.
What you’ll learn
- State the k-NN classification and regression rules, with tie-breaking and distance-weighted votes.
- Compare Euclidean, Manhattan, Chebyshev, cosine and Mahalanobis distances, and standardize features without leaking test data.
- Derive the variance of k-NN regression and its effective degrees of freedom , and choose by cross-validation.
- Analyze the cost of a query, run a k-d tree search with pruning, and explain why trees fail in high dimensions.
- Derive the Cover–Hart bound .
The rule, precisely
Take a training set and a distance on the inputs. For a query , sort the training inputs by their distance to it, , and let hold the indices of the first . The k-nearest-neighbor rules are
KNN-PREDICT(query x, training set D, k, distance ρ)
for i = 1..n: dist[i] = ρ(x, x_i)
N = indices of the k smallest dist # quickselect: O(n), or a heap: O(n log k)
if classification:
count votes y_i for i in N
if several classes tie: drop the farthest of N and recount # or weight by distance
return the winning class
else:
return mean of y_i for i in NTwo kinds of tie need a rule. Distance ties (two training points equally far away) are broken at random or by index. Vote ties cannot happen with two classes and odd , but they can with three or more classes; shrinking the vote to the nearer neighbors, or weighting votes by distance, resolves them.
With the rule partitions the input space into Voronoi cells: each training point owns the region closer to it than to any other. Under Euclidean distance the cells are convex polytopes, so the 1-NN decision boundary is built from pieces of the perpendicular bisectors between differently labeled points. Larger coarsens this mosaic.
A useful variant weights each neighbor's vote by a decreasing function of its distance, , so the nearest neighbors count most; with all points weighted this way, the regression version becomes the Nadaraya–Watson estimator. (This is a smoothing window, not the positive-definite kernel of The Kernel Trick.)
Why is an odd the usual choice for two-class k-NN, and does the same trick work with three classes?
- Odd is faster to compute, for any number of classes
- With two classes an odd number of votes cannot split evenly; with three classes ties are still possible, for example 2–2–1 with
- Odd makes the decision boundary smooth
- It works for any number of classes: an odd count of votes can never tie
Show the answer
B. With two classes an odd number of votes cannot split evenly; with three classes ties are still possible, for example 2–2–1 with
With two classes the votes split as and , which are unequal when is odd. With three classes, can split 2–2–1, so a tie-breaking rule is still needed.
Choosing the distance
k-NN is only as good as its notion of distance. The common choices, evaluated on and :
| Distance | Formula | Value on the example | Notes |
|---|---|---|---|
| Euclidean | the default; rotation-invariant | ||
| Manhattan | less dominated by one large coordinate difference | ||
| Chebyshev | only the worst coordinate counts | ||
| Cosine distance | ignores length: text, embeddings | ||
| Mahalanobis | , | depends on | whitens correlated features; a learned is metric learning |
Scale every vector to unit length, , and expand the squared Euclidean distance:
This is an increasing function of the cosine distance , so both rank all candidates in the same order: Euclidean k-NN on normalized vectors is cosine k-NN. On the example, . This is why vector search engines often normalize embeddings and use fast Euclidean or inner-product search.
Scale. Every distance above adds up differences measured in each feature's own units, so a feature with a large numeric range dominates. Standardize each feature, , with the mean and standard deviation estimated on the training data only and inside every cross-validation fold; computing them on all the data leaks information from the test set.
Relevance. Standardizing makes every feature count equally, which is wrong when some features are irrelevant: each irrelevant feature adds noise to every distance. A Mahalanobis distance with is the Euclidean distance after the linear map , so learning from labels, to pull same-class neighbors together and push others away, is a principled fix. That is metric learning, the subject of Metric Learning & Fast Neighbor Search.
k as a bias–variance knob
Consider regression with fixed training inputs and , where the noise has mean and variance . Fix a query and its neighbors . Only the noise is random.
The prediction averages noisy labels, so its mean and variance are
A new label at carries its own independent noise, so the expected squared error splits into noise, squared bias and variance:
Larger divides the variance by but reaches for farther neighbors, whose values drift from : the bias grows. With more data, neighbors at fixed move closer, so the bias shrinks while the variance stays .
k-NN regression is a linear smoother: , where row of puts weight on each of the neighbors of . Each training point is its own nearest neighbor, so and the effective degrees of freedom are . With and , k-NN behaves roughly like a model with 100 parameters; with , like one parameter per data point.
You keep fixed and double the number of training points. Which part of k-NN regression's error changes, according to the derivation?
- The variance halves, because there is twice as much data
- Both bias and variance stay the same, because did not change
- The squared bias shrinks, because the 15 neighbors now lie closer to the query; the variance stays
- The noise halves
Show the answer
C. The squared bias shrinks, because the 15 neighbors now lie closer to the query; the variance stays
The variance is whatever is. More data packs the training inputs more densely, so the same number of neighbors covers a smaller region, where varies less: the bias falls. That is why the best grows with .
In practice, choose (and the weighting) by cross-validation. Theory says how should scale: for consistency, but . For a Lipschitz regression function in dimensions, the squared bias is of order ; balancing it against gives and an error of order . The exponent's dependence on is the curse of dimensionality, made precise in The Curse of Dimensionality.
Making queries fast
A brute-force query computes distances in dimensions, work, then selects the smallest in time (quickselect) or (a heap). Memory is : the whole training set. For a million points with 100 features that is multiply-adds for every single query, a cost that adds up quickly when queries arrive by the thousands.
A k-d tree (Bentley, 1975) organizes the points in advance. Each internal node splits its points at the median of one coordinate, cycling through the coordinates or choosing the one with the largest spread, until the leaves hold a few points each. Building it takes time.
KD-SEARCH(node, query x, k) # best = max-heap of the k nearest found so far
if node is a leaf:
update best with the points in the leaf; return
j, s = node.split_coordinate, node.split_value
near, far = (node.left, node.right) if x[j] <= s else (node.right, node.left)
KD-SEARCH(near, x, k)
r = distance to the k-th best so far (infinity if fewer than k found)
if |x[j] - s| < r: # the ball around x crosses the splitting plane
KD-SEARCH(far, x, k) # otherwise the whole far side is prunedDescend to the query's leaf, then backtrack, opening the other side of a split only when the current -th-nearest distance reaches across the splitting plane. The result is exact, not approximate.
A k-d tree is built over points by median splits until each leaf holds a single point. About how deep is it?
Show the answer
20 levels
Each median split halves the points, so the depth is . Reaching the query's leaf costs only 20 comparisons; the real cost is the backtracking, which depends on the dimension.
In low dimensions the ball around the query rarely crosses a splitting plane, so most of the tree is pruned, and Friedman, Bentley and Finkel (1977) showed that the expected search time grows only logarithmically in for a fixed dimension, with constants that grow exponentially in . In high dimensions the ball of radius around the query crosses most splitting planes, the far side can almost never be pruned, and the search degenerates toward a linear scan. Weber, Schek and Blott (1998) found that, for data spread uniformly, tree and partitioning indexes were beaten by a plain sequential scan once the dimension exceeded about 10. Ball trees and cover trees adapt better to data with low intrinsic dimension; beyond that, practical systems give up exactness and use approximate search.
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import GridSearchCV
pipe = make_pipeline(StandardScaler(), KNeighborsClassifier(algorithm='kd_tree'))
grid = {
'kneighborsclassifier__n_neighbors': [1, 3, 5, 9, 15, 25, 45],
'kneighborsclassifier__weights': ['uniform', 'distance'],
}
search = GridSearchCV(pipe, grid, cv=5) # the scaler is refit inside every fold
search.fit(X_train, y_train)
print(search.best_params_)
print(search.score(X_test, y_test)) # the test set is used once, at the endPutting the scaler inside the pipeline is what keeps cross-validation honest: each fold standardizes with its own training statistics. weights='distance' gives each neighbor a vote proportional to the inverse of its distance.
How good can nearest neighbors get?
Take two classes, , and let . The Bayes classifier predicts the likelier class and errs with probability at , so the Bayes error is . No classifier does better. How close does the humble 1-NN rule come?
Let be the nearest training input to the query , with label . Given the inputs, and are independent, and the rule errs exactly when they differ:
As grows, . If is continuous, , and since :
Lower bound. Because , we have , so pointwise; take expectations to get .
Upper bound. Expand and use Jensen's inequality, . Equality holds when is constant, for example when labels are flipped with the same probability everywhere, so the bound is tight.
A two-class problem has Bayes error . With unlimited data, at most what error can the 1-NN rule have?
Show the answer
18 %
. In the worst case the nearest neighbor's label is itself noisy, so two coin flips must agree. One way to read the result: a single neighbor already delivers at least half of what an infinite sample could, in the sense that it at most doubles the unavoidable error.
Fixed cannot close the remaining gap: a vote of noisy labels stays noisy however much data arrives. Letting grow with does close it. Stone (1977) proved that k-NN is universally consistent: if and , its error converges to for every distribution on . There is a catch: no rule, k-NN included, converges at a guaranteed rate for every distribution, and in high dimensions the convergence can be very slow.
Key takeaways
- k-NN predicts by a majority vote (classification) or an average (regression) of the nearest training points; ties need explicit rules, and distance weighting is a common refinement.
- The distance is the model: standardize features using training statistics only, prefer cosine (or normalized Euclidean) for embeddings, and consider a learned Mahalanobis metric when features differ in relevance.
- At fixed inputs, k-NN regression has variance and effective degrees of freedom ; bias grows with and shrinks with , so the best grows with .
- Brute-force search costs per query. k-d trees prune by splitting planes and are fast in low dimensions, but on data that fill the space they degrade toward a linear scan beyond roughly ten dimensions.
- With unlimited data, 1-NN's error lies between and ; letting with reaches for every distribution (Stone, 1977).
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
You standardize every feature with the mean and standard deviation of the whole dataset, then split it into training and test sets for k-NN. What is wrong?
- Nothing: standardization uses no labels, so it cannot leak
- The test set's statistics have shaped the training features, a mild form of data leakage; fit the scaler on the training data only
- k-NN should never be used with standardized features
- The test set must be standardized with its own mean and standard deviation instead
Show the answer
B. The test set's statistics have shaped the training features, a mild form of data leakage; fit the scaler on the training data only
Any statistic computed from the test set and used in training lets it influence the model, so the test score is no longer measured on truly unseen data. Fit the scaler on the training set (inside every cross-validation fold) and apply the same transformation to new points. With large datasets the effect is usually small, but it is a leak, and with small or shifted datasets it can matter.
All vectors are scaled to unit length. How do the neighbors found by Euclidean distance compare with those found by cosine similarity?
- They are identical, because
- They differ, because Euclidean distance also measures length
- They are identical only in two dimensions
- They are opposite: the Euclidean nearest is the cosine farthest
Show the answer
A. They are identical, because
For unit vectors the squared distance is a decreasing function of the cosine, so both orderings agree for every query.
k-NN regression is fitted to points with . What are its effective degrees of freedom ?
- 12
- 600
- 50
- 7,200
Show the answer
C. 50
Each training point is its own nearest neighbor, so every diagonal entry of the smoother matrix is , and . Smaller means more effective parameters.
A k-d tree answers exact 3-NN queries on 2-D data almost instantly, but on 200-dimensional embeddings it is barely faster than brute force. Why?
- Building the tree takes longer in high dimensions
- The tree has too few levels to hold 200 coordinates
- In high dimensions the search ball around the query crosses most splitting planes, so few branches can be pruned
- k-d trees only support Manhattan distance
Show the answer
C. In high dimensions the search ball around the query crosses most splitting planes, so few branches can be pruned
The speed-up comes entirely from pruning: skipping a subtree whose region lies farther than the current -th-nearest distance. In high dimensions even the nearest neighbors are far away and the region boundaries are close in at least some coordinates, so the pruning test almost always fails and the search visits most leaves.
A two-class problem has Bayes error 5%. What does the Cover–Hart bound say about the 1-NN rule with unlimited data?
- Its error will be exactly 5%
- Its error is between 5% and 9.5%
- Its error is at most 2.5%
- Nothing, because the bound needs the distribution to be Gaussian
Show the answer
B. Its error is between 5% and 9.5%
. The lower bound holds for every classifier; the upper bound says the neighbor's own label noise at most roughly doubles the error.
Go deeper
- Consistency of Nearest Neighbors · Cover and Hart’s 2× Bayes bound and Stone’s theorem.
- The Curse of Dimensionality · Concentrating distances, empty space and minimax rates.
- Metric Learning & Fast Neighbor Search · Learned distances, trees, hashing and graph-based search.
Further reading
- T. M. Cover & P. E. Hart, "Nearest neighbor pattern classification," IEEE Transactions on Information Theory 13(1), 21–27 (1967).
- J. H. Friedman, J. L. Bentley & R. A. Finkel, "An algorithm for finding best matches in logarithmic expected time," ACM Transactions on Mathematical Software 3(3), 209–226 (1977).
- T. Hastie, R. Tibshirani & J. Friedman, The Elements of Statistical Learning, 2nd ed. (Springer, 2009), sections 2.3, 7.6 and chapter 13.
- G. Biau & L. Devroye, Lectures on the Nearest Neighbor Method (Springer, 2015).