Foundations
Nearest Neighbor Pattern Classification
The 1967 paper by Cover and Hart that proved the large-sample error of the nearest-neighbour rule is at most about twice the Bayes error for any number of classes, with the assumptions behind the bound, its k-NN extension, the paper's worked examples, what it does not claim, and the slips found in it since.
advanced
“Nearest Neighbor Pattern Classification” is a paper by Thomas M. Cover of Stanford University’s Department of Electrical Engineering and Peter E. Hart of the Stanford Research Institute in Menlo Park, published on pages 21–27 of IEEE Transactions on Information Theory in January 1967 (the manuscript was received in February 1966 and revised that April). It analysed the simplest nonparametric classifier, which gives a new observation the label of the closest stored example, and proved that when the number of stored examples grows without limit its probability of error satisfies
for categories, where is the Bayes error, the lowest error any rule can reach with full knowledge of the distribution. The upper bound never exceeds , and the paper shows that both bounds are as tight as possible. The paper also showed that the one-neighbour rule is admissible among -neighbour rules for every sample size, and extended the large-sample bounds to the -neighbour vote. The method as used today, including the choice of , distances, cost and its uses in vision, is the subject of the k-nearest neighbors article; this article covers the paper. Section, equation and figure numbers below are those of the printed journal version, read in the scan of the printed pages that Cover’s Stanford web page hosts.
Problem
The paper opens with two extremes of knowledge. A statistician who knows the joint distribution of an observation and its category can apply the Bayes rule and reach the minimum error . One who knows only correctly classified samples , drawn independently from that distribution, faces a nonparametric problem for which, the authors note, no classification procedure is optimal against every distribution. A natural heuristic is that observations close together in some metric have the same category, or at least nearly the same posterior probabilities, so the evidence of nearby samples should weigh most; the nearest-neighbour (NN) rule is the simplest procedure of that kind.
Cover and Hart credit the first formulation of a nearest-neighbour type rule, and the main earlier analysis of one, to Evelyn Fix and J. L. Hodges Jr., in two reports for the US Air Force School of Aviation Medicine at Randolph Field, Texas: one of February 1951 and one of August 1952. Fix and Hodges studied what the paper calls the -NN rule, which assigns a point to the class most represented among its nearest neighbours, and established its consistency for sequences with and ; Cover’s 1968 follow-up adds that they did so under conditions on the underlying distributions, with the risk approaching the Bayes risk. The 1952 report studied numerically the small-sample performance of the rule under normal distributions. The first report was reprinted in 1989 in the International Statistical Review.
The paper lists other earlier uses. Johns had used the NN rule as an example of an empirical Bayes rule; Kanal, Sebestyen, who called it the proximity algorithm, and Nilsson had pointed out its intuitive appeal and suggested it for pattern recognition. Kanal’s 1963 report, the reference list notes, had first appeared in a Philco study titled “Semi-automatic imagery screening research study and experimental investigation”. Loftsgaarden and Quesenberry had shown that a modification of the -NN rule gives a consistent density estimate. In none of these papers, Cover and Hart write, had analytical results been obtained in the nonparametric case for a finite sample size or for a finite number of neighbours. Fix and Hodges’ consistency result is analytical but lets the number of neighbours grow; whether “the above mentioned papers” is meant to include their reports is not clear from the text. The paper set out to analyse the rule that uses a single neighbour.
Contribution
- Admissibility of 1-NN (§III). For every sample size there is a distribution on which the one-neighbour rule has strictly lower error than every -neighbour majority rule with , so no such rule is better than 1-NN against all distributions.
- Convergence of the nearest neighbour (§V). In any separable metric space the nearest of independent samples converges to the query with probability one, for any probability distribution.
- The two-class bound (§VI). , eq. (13), under mild conditions on the class densities, with both bounds as tight as possible and an exact expression for the slack.
- The -class bound (§VI). , eq. (29), again tight.
- A worked example (§VII). What the paper presents as an exact expression for the error of 1-NN at every finite in one simple problem; the printed formula is wrong for (see the slips below).
- The -NN rule (§VIII). For two classes and odd , the tightest upper bound on the large-sample -NN error, which decreases with toward .
The authors read the main result as a statement about information: since any rule based on the infinite sample set can at best halve the NN error, in the abstract’s words “half the classification information in an infinite sample set” is contained in the nearest neighbour.
Method
Setting and the rule
Section II takes the in a metric space with metric and the categories in . A new pair arrives, with only observed. The sample is a nearest neighbour of if , eq. (1), and the NN rule assigns to the category of , ignoring the other labels. A footnote handles ties: the rule may decide the most popular category among tied points, and where ties occur with nonzero probability the results hold trivially. The paper’s notation differs from the subject article’s: are the prior probabilities of the categories, their densities with respect to a measure , and , eq. (4), the posterior probabilities. With the 0–1 loss the conditional Bayes risk is and the Bayes risk is , eqs. (6)–(7) and (32). The -sample NN risk is the expected loss of the rule, eq. (10), and the large-sample NN risk is its limit , eq. (11). All pairs are assumed independent and identically distributed.
Admissibility
Section III first gives the case for a vote over neighbours: a large lowers the chance of a non-Bayes decision while a small keeps the neighbours close, and then shows that 1-NN is nevertheless never dominated. In its example (Fig. 1) two equally likely classes are uniform on unit disks centred at and . A query from one disk has its nearest neighbour in the other disk only if all samples lie there, so 1-NN errs with probability . With the vote errs whenever or fewer samples lie in the query’s disk, with probability
eq. (2), larger than for every . The same example works for every . The formula covers odd only; the paper does not discuss vote ties for even .
Convergence of the nearest neighbour
The large-sample analysis rests on a lemma in Section V: if are independent and identically distributed in a separable metric space, then with probability one. The proof first shows convergence for any whose every surrounding ball has positive probability, then uses a countable dense subset to cover the remaining points by countably many balls of probability zero, so that such points occur with probability zero. The authors prove it in this generality, they say, to cover pathological candidates such as the Cantor distribution on the real line. They add that, because this convergence does not depend on the metric, the bounds on the NN risk do not either.
The two-class theorem
For and the 0–1 loss, the theorem of Section VI assumes a separable metric space and densities such that, with probability one, is either a continuity point of both or a point of nonzero probability. The remarks note that any mixture of point masses and piecewise continuous densities on Euclidean space qualifies. Conditioning on and , the labels and are independent, so the conditional risk is , eq. (15). The continuity assumption, together with the lemma, makes ; at an atom the neighbour simply equals from some on. The conditional risk therefore tends to , eq. (21), and dominated convergence carries the limit through the expectation. Writing gives the exact large-sample risk
eq. (25). The upper bound , eq. (26), is reached exactly when is constant, which the paper turns into the condition that equal or its reciprocal almost everywhere, eq. (27). Rewriting the risk as , eq. (28), gives the lower bound, reached exactly when is 0 or almost everywhere. At the extremes the two rules agree: if and only if , and if and only if .
The M-class theorem
With more than two classes the substitution of eq. (21) no longer applies. The theorem’s assumptions are the same, with densities with respect to a probability measure , and the limit of the conditional risk is
eq. (31). The Cauchy–Schwarz inequality applied to the non-maximal posteriors, eqs. (33)–(35), gives , eq. (36), and taking expectations gives eq. (29). The upper bound is attained by a “no-information” experiment in which all classes have the same density and the priors are for one class and for each of the others; the lower bound is attained, for example, by equal priors and uniform densities that overlap completely on one interval and are disjoint elsewhere, eq. (39). Hastie and colleagues (2009, §13.3, eq. 13.5 and Exercise 13.3) state the same conditional inequality and the same bound.
Results
The paper’s only numerical example, in Section VII, is one-dimensional. Two equally likely classes have triangular densities on , and (Fig. 2), so that the mixture is uniform and the posterior of class 1 is simply . The Bayes error is , eq. (43). The paper writes the -sample 1-NN risk as , eq. (40), and after what it calls a lengthy but straightforward calculation gives
eq. (41), with limit , eq. (42), so that the bounds read , eq. (44). The paper observes that , in agreement with simpler considerations, and that approaches its limit approximately as .
The example below reproduces Section VII with images: each sample is a uniform grey patch whose brightness is drawn from the two triangular densities, a lit and a shadowed class, and the classifier compares the 16 pixel values. Because the patches are noise-free, the Euclidean distance between two of them is , so the nearest patch is the one of closest brightness and the problem is exactly the paper’s. The block estimates the 1-NN error by simulation for several and prints it beside eq. (41) and beside an exact expression we derived for the same quantity. It then evaluates the paper’s large-sample formulas for this example: , the 1-NN risk of eq. (24), and, applying Section VIII to Section VII (a computation the paper does not make), the large-sample 3-NN risk and its tightest bound, checked by a simulation at . It takes about 5 seconds; the output came from NumPy 2.3.5 and SciPy 1.16.3.
import numpy as np
from scipy.integrate import quad
# Section VII of Cover & Hart, as images: every sample is a uniform 4x4 grey patch whose
# brightness x in [0, 1] has density f1(x) = 2x for class 1 (lit) and f2(x) = 2 - 2x for
# class 2 (shadow), with equal priors, so the posterior of class 1 is eta1(x) = x.
PIX = 16
def patches(m, rng):
"""m patches, one row each; brightness drawn from the triangular class densities."""
y = rng.integers(1, 3, m)
u = np.sqrt(rng.uniform(size=m))
x = np.where(y == 1, u, 1 - u)
return np.repeat(x[:, None], PIX, axis=1), y
def knn_error(n, k, trials, rng, chunk=2000):
"""Monte Carlo error of the k-NN vote (Euclidean distance on the 16 pixel values),
each trial with its own n training patches and one query patch."""
errs = 0
for _ in range(trials // chunk):
X, y = patches(chunk * n, rng)
X, y = X.reshape(chunk, n, PIX), y.reshape(chunk, n)
q, yq = patches(chunk, rng)
d = ((X - q[:, None, :]) ** 2).sum(-1) # chunk x n squared distances
nn = np.argsort(d, axis=1)[:, :k]
votes1 = (np.take_along_axis(y, nn, 1) == 1).sum(1)
errs += np.sum(np.where(votes1 * 2 > k, 1, 2) != yq)
return errs / trials
rng = np.random.default_rng(0)
print(" n 1-NN error, 200,000 trials printed eq. (41) exact (our derivation)")
for n in (1, 2, 5, 20, 100):
printed = 1/3 + 1/((n + 1) * (n + 2))
exact = 1/3 + (3*n + 5) / (2 * (n + 1) * (n + 2) * (n + 3))
print(f"{n:>4} {knn_error(n, 1, 200_000, rng):>13.4f}{printed:>27.4f}{exact:>21.4f}")
# Large-sample risks from the paper's formulas, with r*(x) = min(x, 1 - x) and x uniform.
R_star = quad(lambda x: min(x, 1 - x), 0, 1, points=[0.5])[0] # eq. (43)
R_1 = quad(lambda x: 2 * x * (1 - x), 0, 1)[0] # eq. (24)
rho3 = lambda r: r + 3 * r**2 - 8 * r**3 + 4 * r**4 # eq. (46), k = 3
R_3 = quad(lambda x: rho3(min(x, 1 - x)), 0, 1, points=[0.5])[0]
# least concave majorant of rho3 on [0, 1/2] at r = R*, from the upper hull of a fine grid
r = np.linspace(0, 0.5, 5001); v = rho3(r)
hull = [0]
for i in range(1, len(r)):
while len(hull) > 1 and ((v[hull[-1]] - v[hull[-2]]) * (r[i] - r[hull[-2]])
<= (v[i] - v[hull[-2]]) * (r[hull[-1]] - r[hull[-2]])):
hull.pop()
hull.append(i)
rho3_tilde = np.interp(R_star, r[hull], v[hull])
print(f"\nR* = {R_star:.4f} R (1-NN) = {R_1:.4f} bound 2R*(1 - R*) = {2*R_star*(1-R_star):.4f}")
print(f"R_3 (3-NN) = {R_3:.4f} bound rho3~(R*) = {rho3_tilde:.4f}")
print(f"3-NN error at n = 1,000 (40,000 trials): {knn_error(1000, 3, 40_000, rng):.4f}")
Output:
n 1-NN error, 200,000 trials printed eq. (41) exact (our derivation)
1 0.5007 0.5000 0.5000
2 0.4253 0.4167 0.4250
5 0.3645 0.3571 0.3631
20 0.3367 0.3355 0.3364
100 0.3339 0.3334 0.3335
R* = 0.2500 R (1-NN) = 0.3333 bound 2R*(1 - R*) = 0.3750
R_3 (3-NN) = 0.3000 bound rho3~(R*) = 0.3281
3-NN error at n = 1,000 (40,000 trials): 0.2981
The simulation agrees with the paper at and approaches the limit , but it does not match the printed eq. (41) in between: at and the simulated error exceeds the formula by 0.009 and 0.007, many times the sampling error of 200,000 trials (a standard deviation of about 0.001, by our calculation). Our own calculation of the risk defined by eq. (40) gives
which matches the simulation at every shown, agrees with eq. (41) at , and has the same decay, with a leading constant of instead of 1. The reasoning behind it, which is ours: for a query of brightness , a neighbour closer than is equally likely to lie on either side, so it contributes no systematic error; the excess over the limit comes only from queries near the ends of the interval, whose nearest neighbour must lie on the inside when no sample is closer to the query than the edge is. This discrepancy is our finding; we know of no published correction. The large-sample numbers illustrate the paper’s chain of bounds for this example: 1-NN at is below the two-class bound , and three neighbours lower the large-sample error to , below their own tightest bound and above ; a simulation with 1,000 patches is already close to that value.
The k-NN rule
Section VIII extends the analysis to neighbours. With fixed, the -th nearest neighbour also converges to (from §V), and the neighbours cast conditionally independent votes. For two classes and odd , the large-sample conditional -NN risk is a binomial expression in , eq. (45): the probability that the majority of independent labels disagrees with . The paper notes that decreases monotonically in toward , and that since is symmetric in and it can be written as a function of the conditional Bayes risk alone, eq. (46). With the least concave function above , Jensen’s inequality gives
eqs. (47)–(48). The authors state that simple distributions attain , so that it is the least upper bound, without exhibiting them, and conclude with the chain
eq. (49), with the upper and lower bounds on as tight as possible. Large-sample -NN error can therefore only improve on 1-NN as grows, while Section III shows that at a fixed sample size it need not: the two results together state the trade-off in the choice of that the k-nearest neighbors article treats in practice.
Impact
Hastie, Tibshirani and Friedman (2009, §13.3) describe the bound as famous and present its argument, the asymptotic error of a random rule that draws both the label and the test point’s class from the posterior, together with the -class inequality. The paper itself is not about images and contains no experiments on data. The rule it analysed is the one behind descriptor matching, image retrieval, face identification against a gallery and the evaluation of learned embeddings, uses the k-nearest neighbors article describes.
Limitations
The results are asymptotic. Apart from the admissibility example and the triangular example, every bound concerns the limit . The paper gives no rate at which approaches in general and no bound on the error at a finite sample size; the behaviour it reports belongs to one example. How slowly the limit is reached in high dimensions is shown by the 16-pixel experiment in the k-nearest neighbors article.
Metric independence is a large-sample statement. It follows from eq. (31) that the limit depends only on the posteriors at , so any metric for which the lemma and the continuity assumption hold gives the same large-sample error. The error at finite does depend on the metric, which is why distance choice, feature scaling and metric learning matter in practice. The continuity assumption is itself tied to the metric’s topology (our observation): a metric under which the class densities are discontinuous almost everywhere would fall outside the theorems.
Scope of the assumptions. The theorems assume independent, identically distributed pairs, the 0–1 loss, and densities that are continuous at almost every point that is not an atom. The -NN bounds cover two classes and odd only. The admissibility result is a statement about undominated rules among -NN rules, not a claim that 1-NN is a good choice: in the same section the paper shows that on its disk example the error rises toward as grows for fixed , and falls to zero as grows for any fixed , eq. (3).
The bound concerns 1-NN against Bayes, not the best . Letting grow with removes the factor of two altogether, as Fix and Hodges’ consistency result already showed under their conditions; the Cover–Hart bound describes what is lost by insisting on a single neighbour.
Slips in the printed paper
- The lemma’s proof. Below eq. (9) the proof in §V appeals to the monotone decrease in of , the distance of the -th sample. Cover (1968, footnote 1) corrected this as a misprint for , the distance of the nearest of the first samples, whose monotonicity turns convergence in probability into convergence with probability one.
- Admissibility. The last sentence before Fig. 1 states that 1-NN is strictly better than other -NN rules when each in-class distance is greater than any between-class distance. In the disk example the reverse holds (distances within a class are at most 2, between classes at least 4), so in our reading the sentence has the inequality inverted.
- Correct versus incorrect. After eq. (21) the text says a randomly chosen will be “correctly classified” with probability ; by eq. (21) that is the probability of misclassification (our reading).
- The M-class risk. Eq. (37) is printed as an equality, but it follows from the inequality (36) by taking expectations, so for it holds as (our reading; for it is an equality and matches eq. 25). For the same reason the statement after eq. (38) that equality holds if and only if needs, for , also equality in the Cauchy–Schwarz step, that is, equal non-maximal posteriors almost everywhere; the paper’s no-information example satisfies both.
- The triangular example. As the code above shows, eq. (41) does not match the risk defined by eq. (40) for , although its value at , its limit and its decay are right (our finding).
In our reading, none of these affects the main theorems, eqs. (13) and (29): eq. (29) still follows from eq. (36).
What Came After
Both authors returned to the rule in the same journal the next year. Cover (1968) extended the analysis from classification to estimation, where the label is a parameter in an arbitrary space and the losses can be unbounded. Under conditions that allow limit and expectation to be exchanged, to which part of that paper is devoted, he showed that the large-sample NN risk is at most for metric loss functions and equal to for squared-error loss, and that a simple estimator using neighbours has risk under squared error; he read these as saying that at least half the information in an infinite training set is contained in the nearest neighbour. That paper also cites, beside the 1967 paper, a May 1966 Stanford Electronics Laboratories technical report by Hart, “An asymptotic analysis of the nearest-neighbor decision rule”, for the classification bound.
Hart then turned to the practical cost of storing every sample: his condensed nearest-neighbour rule of 1968, described in the k-nearest neighbors article, keeps only a subset of the training set for the nearest-neighbour decisions (Hastie et al., 2009, §13.5).
Hastie and colleagues (2009, §13.3 and the chapter’s bibliographic notes) write that many additional results of the Cover–Hart kind have been derived, point to Chapter 6 of Ripley (1996) for a summary, and to Dasarathy (1991) for a review of the extensive literature on nearest-neighbour methods. For the large image collections of computer vision, finding the neighbours quickly is the separate subject of approximate nearest neighbor search.
Related
- k-Nearest Neighbors
The classifier and regressor that predict from the k most similar stored examples, with no training step; how the vote, the number of neighbours, the distance and the feature scaling decide its accuracy, the Cover–Hart bound on its error, why it struggles in high dimensions, and where nearest-neighbour methods are used in computer vision.
- Probability and Statistics
The mathematics of uncertainty that vision uses everywhere, from noisy pixels to classifier outputs; random variables, distributions, conditional probability and Bayes' rule, expectation and covariance, sums and averages, and estimation from samples.
- Machine Learning
How a program learns a task such as recognizing objects from examples instead of hand-written rules, why doing well on the training images is not the goal, and how features, models, data and evaluation fit together in computer vision.
- Similarity and Distance Measures
The functions that score how alike two feature vectors, histograms or binary codes are (Euclidean and other ℓp distances, cosine similarity and the dot product, Mahalanobis, Hamming, histogram measures such as χ², intersection and Hellinger, and the earth mover's distance), which of them are true metrics, and where each is used in descriptor matching, histogram comparison and embedding retrieval.
- Metric Learning
Learning a distance function from examples of what should count as similar, from Mahalanobis metrics learned with convex programs (Xing et al., LMNN, ITML) and NCA to deep siamese networks trained with pair, ranking and proxy losses, with the sampling problem, the open-set evaluation protocol and what a fair comparison of the losses found.
- Approximate Nearest Neighbor Search
Finding the database vectors closest to a query without comparing it with every one, by accepting an occasional wrong answer; why exact search stops paying off in high dimensions, the four families of indexes (randomized k-d trees with best-bin-first search, locality-sensitive hashing, inverted files with product quantization, and navigable small-world graphs), how their recall, speed and memory are measured, and the libraries that implement them.
References
- Cover, T. M. & Hart, P. E. (1967). Nearest Neighbor Pattern Classification. IEEE Transactions on Information Theory, 13(1), 21–27.
- Cover, T. M. (1968). Estimation by the Nearest Neighbor Rule. IEEE Transactions on Information Theory, 14(1), 50–55.
- Fix, E. & Hodges, J. L. (1989). Discriminatory Analysis. Nonparametric Discrimination: Consistency Properties. International Statistical Review, 57(3). Reprint of the 1951 report of the USAF School of Aviation Medicine, Randolph Field, Texas.
- Hastie, T., Tibshirani, R. & Friedman, J. (2009). The Elements of Statistical Learning: Data Mining, Inference, and Prediction (2nd ed.). Springer. Section numbers cited from the authors' free PDF.