k-Nearest-Neighbors and Local Regression
Anchor (Master): Hastie, Tibshirani & Friedman 2009 The Elements of Statistical Learning 2e §6.1-6.6 and §2.5 (local methods, the curse of dimensionality); Cover & Hart 1967 (asymptotic 1-NN risk ); Stone 1977 Ann. Statist. 5 (universal consistency of nearest-neighbour and local-average rules); Fan & Gijbels 1996 Ch. 3 (minimax efficiency and design adaptation of local polynomial fits)
Intuition Beginner
Some prediction methods study the data once, distil it into a formula, and then throw the data away. Memory-based methods do the opposite: they keep all the training cases and answer each new question by looking up the cases most similar to it. To guess a new house's price, find the handful of past sales whose size and location are closest, and report their average price. To guess whether an email is spam, look at the nearest few emails you have already labelled and take a vote. There is no formula learned in advance; the data itself is the model.
The number of neighbours you consult is the one dial that matters most. Ask only the single closest case and your answer follows it exactly, jumping around as you move from query to query. Ask many neighbours and the answer is a smooth average, steadier but blurrier, because some of those neighbours are not really that close. Few neighbours means a jumpy, detailed fit; many neighbours means a smooth, coarse one. This is the same tension between detail and stability that runs through all of model fitting.
A cousin idea improves the plain average. Instead of giving every neighbour an equal say, weight the close ones more than the far ones, with the weights fading smoothly with distance. This is kernel-weighted prediction, and a refinement fits a small tilted line through the nearby points rather than a flat average, which behaves much better at the edges of the data where one-sided neighbours would otherwise drag the answer.
The catch is that "close" gets hard to define when each case carries many measurements. In a high-dimensional space, even your nearest neighbours are surprisingly far away, so the neighbourhood you trust is no longer local. That failure of locality is the price these otherwise simple methods pay.
Visual Beginner
Picture points scattered on a plane, each a training case, and a new query marked with a star. Draw a circle around the star just large enough to enclose its closest points; the prediction is the average of those points' values. Shrink and the circle tightens onto one or two points; grow and the circle swells to take in distant, less relevant cases.
| Number of neighbours | Fit shape | Bias | Variance |
|---|---|---|---|
| Very small (1-3) | Ragged, follows every point | Low | High |
| Moderate | Smooth with local detail | Medium | Medium |
| Very large | Nearly a flat global average | High | Low |
Reading the table and the picture together: the circle's size is the smoothness knob. A tiny circle trusts only the most similar cases and pays for it with a jumpy answer; a large circle is calm but reaches for cases that are not truly alike.
Worked example Beginner
Five past house sales, each with a lot size (in thousands of square feet) and a sale price (in thousands of dollars). We predict the price of a new house with lot size , using nearest neighbours.
| House | Lot size | Price |
|---|---|---|
| 1 | 2 | 150 |
| 2 | 4 | 200 |
| 3 | 6 | 280 |
| 4 | 7 | 330 |
| 5 | 9 | 360 |
Step 1. Measure distance from the query lot size to each house: house 1 is away, house 2 is , house 3 is , house 4 is , house 5 is .
Step 2. The 1-nearest neighbour. The closest distance is , tied between houses 2 and 4 — sorry, between houses 2 and 3 (both at distance ). Taking house 2, the 1-NN prediction is its price, . Taking house 3 instead gives . The single-neighbour answer is unstable: a tie or a tiny shift flips it.
Step 3. The 3-nearest neighbours. The three smallest distances are (house 2), (house 3), and (house 4). Their prices are , , , averaging .
Step 4. Distance weighting. Give each of the three neighbours a weight that fades with distance, say : house 2 and house 3 get , house 4 gets . The weighted average is .
What this tells us: the 3-neighbour average of is steadier than either single-neighbour answer, and weighting pulls it slightly toward the two closest sales, giving . Consulting more neighbours trades a little accuracy near the query for a lot of stability.
Check your understanding Beginner
Formal definition Intermediate+
Let have a joint law on with equipped with a metric , and let be an i.i.d. training sample. Write for the regression function (for classification with , ). For a query , let denote the training cases reindexed so that , and let be the -nearest-neighbour set.
-nearest-neighbour estimators. The -NN regressor is the local average over ,
The -NN classifier predicts the plurality label among ; for two classes this is with the local fraction of class- neighbours. The single-nearest-neighbour rule is the case .
Kernel-weighted (Nadaraya-Watson) regression. With a kernel and bandwidth , write . The Nadaraya-Watson estimator is the kernel-weighted average
the solution of the locally weighted constant fit . The kernel-density estimator is the companion object of 26.08.01.
Local polynomial regression. Fix a degree . The local polynomial fit solves, for each query ,
and reports . The case recovers Nadaraya-Watson; is local linear regression. In matrix form, with the design matrix of monomials and , the fit is , a linear smoother whose weights form the equivalent kernel.
Risk. For classification the risk is the misclassification probability , minimised by the Bayes rule at the Bayes risk . All three estimators are linear smoothers differing only in the weight scheme; the notation , , , , , is recorded in _meta/NOTATION.md.
Counterexamples to common slips Intermediate+
"The 1-NN rule is consistent because it always uses the closest point." Using a single neighbour keeps the variance from vanishing: even as the nearest label is one noisy draw, so the 1-NN risk converges to a limit above the Bayes risk (the Cover-Hart limit), not to it. Consistency needs as well as .
"Nadaraya-Watson and local linear differ only cosmetically." They differ exactly where it matters: at the boundary of the design and at peaks of , the local-constant fit has bias of order (one-sided neighbours pull the average), whereas local linear cancels that leading term and keeps bias of order throughout. The fix costs nothing in rate but removes the boundary penalty.
"Euclidean distance is the natural metric, so feature scaling is a detail." A nearest-neighbour rule is only as good as its metric: rescaling one coordinate by a factor makes it dominate every distance, silently changing which points are "near". Standardising features, or learning an adaptive metric, is part of the method, not a preprocessing afterthought.
Key theorem with proof Intermediate+
The signature theorem of memory-based learning is that the simplest possible classifier — predict the label of the single nearest stored case — is, with unlimited data, never worse than twice the best achievable error. This is the result that made nearest-neighbour methods respectable: an assumption-free rule with a hard performance guarantee.
Theorem (Cover-Hart asymptotic nearest-neighbour risk). Consider two-class classification with continuous at -almost every . Let be the risk of the single-nearest-neighbour rule trained on i.i.d. samples and its asymptotic risk. Then
where is the Bayes risk. [Cover 1967]
Proof. Fix a query and let be its nearest neighbour in the sample, with label . Because the samples are i.i.d. with in the support, almost surely as , so by continuity . The 1-NN rule predicts , and it errs at when the query's own label (drawn from ) differs from (drawn from , independent given the locations). The conditional probability of disagreement is
Letting and using gives the limiting conditional error . Taking expectation over yields .
For the lower bound, the pointwise Bayes error is , and for all (write ; then since ), so . For the upper bound, set , so the pointwise 1-NN error is . The function is concave on , so by Jensen's inequality
the last step because .
Bridge. This bound is the foundational reason nearest-neighbour methods are taken seriously: with no model of the class boundary at all, the crudest rule captures at least half the available classification information, and the factor shows the penalty is small exactly when the problem is easy ( near ). The result builds toward the consistency theory of the Advanced results, where allowing removes the residual gap entirely and the local average converges to itself; the bridge is that 1-NN pays a variance tax for using a single neighbour, and -NN with is exactly the move that drives that tax to zero. The factor-of-two ceiling generalises: for the -NN rule the asymptotic risk tightens toward as grows, and putting these together with the bias-variance reading of 45.06.02 identifies as a smoothing parameter, the same role the bandwidth plays for kernel methods. This appears again in the partition view shared with 45.08.04, where a tree leaf is an adaptive neighbourhood and the leaf average is a -NN-like local mean.
Exercises Intermediate+
Advanced results Master
The Cover-Hart bound is the corner of a fuller theory in which allowing to grow recovers the Bayes rule exactly, kernel and local-polynomial smoothers attain optimal nonparametric rates, and the whole family is undone by dimension.
Theorem 1 (universal consistency of -NN; Stone). Let with -nearest-neighbour weights . If and , then is universally consistent: for every distribution of with , and the induced -NN classifier is risk-consistent, [Stone 1977]. The proof verifies Stone's three weight conditions: kills the variance, the -th nearest-neighbour radius vanishing under kills the bias, and the covering condition holds for nearest-neighbour weights by a geometric argument bounding how many query balls a fixed training point can be the neighbour of. The dual conditions for kernel weights are and , giving consistency of Nadaraya-Watson and local polynomial estimators.
Theorem 2 (bias-variance and the optimal bandwidth of local linear regression). For a one-dimensional interior point with twice-differentiable , design density , noise variance , symmetric kernel with and , the local linear estimator has, to leading order,
Minimising the asymptotic mean squared error over gives the optimal bandwidth and the optimal rate [Fan 1996]. The bias is free of and , so local linear is design-adaptive and corrects boundary bias automatically; Nadaraya-Watson carries the additional term and degrades at the edges (Exercise 6). Local polynomials of odd degree extend the principle, removing the next boundary term.
Theorem 3 (the equivalent kernel). Every linear smoother — -NN, Nadaraya-Watson, local polynomial, and the smoothing spline — has weights that act as an effective, query-dependent kernel. For local linear regression the equivalent kernel converges, as , to a fixed shape independent of the design density , the Epanechnikov-type effective kernel, which is why two smoothers with very different formulations (local linear and the cubic smoothing spline) produce nearly identical fits [Hastie 2009]. The effective degrees of freedom index the smoother's complexity continuously, the same complexity measure that governs the optimism of 45.06.02.
Theorem 4 (the curse of dimensionality for local methods). Let the design be uniform on . To capture a fraction of the data a neighbourhood needs edge length , so for fixed the neighbourhood spans almost the whole range as grows, and conversely a genuinely local neighbourhood of fixed radius captures an exponentially small fraction of the data. The expected distance to the nearest of points grows toward the diameter, and almost all sample points lie near the boundary [Hastie 2009]. Consequently the local-averaging bias cannot be controlled without either an exponential sample size or strong structural assumptions; the nonparametric MSE rate degrades from () to , vanishingly slow for large . Structured kernels, additive and projection-pursuit models, and learned (adaptive) metrics that stretch the relevant directions are the standard escapes, trading universality for a usable rate.
Synthesis. The foundational reason this family coheres is that -NN, kernel smoothing, local polynomials, and even tree leaves are one object — a local weighted average of the responses — read with different weights, and the central insight of Stone's theorem is that any such estimator is universally consistent precisely when its weights satisfy two conditions: no single neighbour dominates (driving variance to zero) and the weight concentrates on shrinking neighbourhoods (driving bias to zero). The Cover-Hart ceiling is exactly the price of violating the first condition by keeping a single neighbour: -NN never shrinks its variance, so its risk floors at rather than , and putting these together with the bias-variance decomposition of 45.06.02 identifies and the bandwidth as the same smoothing dial that trades the two error sources. Local linear regression is dual to Nadaraya-Watson through the equivalent kernel: both are weighted averages, but the linear fit's design-adaptivity removes the boundary term, which is the bridge that makes a memory-based method behave well at the edges where it is needed most. The curse of dimensionality is the structural fact that defeats the whole programme in high , and it generalises the same neighbourhood geometry that powers consistency in low dimension into an obstruction in high dimension — the adaptive neighbourhoods of 45.08.04 and the decorrelated forests downstream are exactly the response, building data-driven metrics that keep neighbourhoods local where a fixed Euclidean ball cannot.
Full proof set Master
Proposition 1 (asymptotic 1-NN error equals and the factor-of-two bound). Under the Cover-Hart hypotheses the limiting single-nearest-neighbour risk is , and .
Proof. Fix ; the nearest neighbour satisfies a.s. (in the support, the minimum of i.i.d. distances vanishes), so by continuity. Conditioned on the locations, the query label and the neighbour label are independent, and disagreement has probability , which tends to . Bounded convergence over gives . With , the pointwise error is ; since we have , so . The map is concave, so Jensen gives , and closes the chain.
Proposition 2 (variance and bias of the -NN regressor). With neighbour locations fixed and independent homoscedastic noise of variance , and .
Proof. with . Linearity of expectation gives , so the bias is the displayed difference. Independence of the gives . The variance falls as and the bias grows as the neighbours reach farther from , so is the smoothing parameter trading the two; the effective number of parameters is , matching the linear-smoother degrees of freedom .
Proposition 3 (Nadaraya-Watson is the local constant fit; equivalent-kernel weights sum to one). The Nadaraya-Watson estimator minimises over , and every local polynomial smoother reproduces constants, .
Proof. For the first claim, at , with positive second derivative . For the second, the local polynomial fit solves a weighted least-squares problem whose design matrix has first column the all-ones vector (the intercept monomial ). The fitted intercept is , so is the corresponding row functional. Applying the smoother to the constant response : weighted least squares fits this exactly with and higher coefficients zero (a constant is in the polynomial span), so . Reproduction of constants is what makes the leading bias depend on curvature rather than level, and for degree reproduction of linear functions removes the design-density term.
Proposition 4 (curse-of-dimensionality neighbourhood geometry). For points uniform on , the side length of an axis-aligned subcube containing in expectation a fraction of the data is , and as for every fixed .
Proof. A subcube of side has volume ; under the uniform law the expected fraction of points it contains equals its volume, . Setting gives . For fixed , , so . Hence to capture any fixed positive fraction of the data the neighbourhood must, in high dimension, span essentially the full range of every coordinate, which is the precise sense in which "local" neighbourhoods cease to be local and local-averaging bias becomes uncontrollable without structural assumptions.
Connections Master
-NN and local regression are the explicit local-averaging instances of the bias-variance trade-off anatomised in
45.06.02: the variance of Proposition 2 is the -NN special case of the variance term there, the neighbour count (and the bandwidth ) plays the role of the complexity dial, and the effective degrees of freedom of the equivalent-kernel smoother is the same complexity measure that governs the optimism and the U-shaped test curve of that unit.The kernel-weighted average and the kernel-density estimator of this unit are the regression and density faces of the nonparametric smoothing developed in
26.08.01: the Nadaraya-Watson estimator is a ratio of a kernel-weighted response sum to the kernel-density estimate of the design, so the bandwidth bias-variance trade-off and the minimax rates established there for density estimation transfer directly to the local-regression rates proved here, the central insight being that both are local averages with vanishing-bandwidth bias and variance.Memory-based local methods and the tree-based partition methods of
45.08.04are two ways of choosing the neighbourhood weights in the common estimator : -NN fixes a Euclidean ball of points, a tree leaf is a data-adaptive axis-aligned rectangle, and the Lin-Jeon reading there casts a tree (and a forest) as an adaptive nearest-neighbour rule — so this unit supplies the fixed-neighbourhood baseline against which the adaptive, metric-learning, dimension-resistant partition methods are the response.The curse of dimensionality formalised in Theorem 4 is the obstruction whose subset-selection and sparsity remedies are developed in
45.06.05: where local methods fight high dimension by structured kernels, additive models, and learned metrics, that unit attacks the same exponential-neighbourhood problem by selecting a low-dimensional set of relevant predictors, and the two are dual strategies — restrict the metric versus restrict the feature set — for restoring a usable convergence rate.
Historical & philosophical context Master
The nearest-neighbour idea is old as a heuristic, but its theoretical standing dates to Evelyn Fix and Joseph Hodges' 1951 unpublished USAF technical report on discriminatory analysis, which introduced nonparametric nearest-neighbour density and classification rules. The decisive result is Thomas Cover and Peter Hart's 1967 paper Nearest neighbor pattern classification [Cover 1967], which proved that the single-nearest-neighbour rule, asymptotically, errs at most twice as often as the optimal Bayes classifier — a guarantee with no assumption on the class densities, establishing that "half the available information in an infinite sample is contained in the nearest neighbour." The kernel-weighted regression estimator was introduced independently by Élisbar Nadaraya (1964) and Geoffrey Watson (1964).
The consistency theory was unified by Charles Stone's 1977 Consistent nonparametric regression [Stone 1977], which gave distribution-free conditions on the weight sequence guaranteeing universal consistency of any local-averaging estimator and pinned the -NN requirement to , . The local-polynomial refinement — local linear regression's automatic boundary correction and design adaptivity — was developed and given its definitive minimax-efficiency treatment by Jianqing Fan and Irène Gijbels in Local Polynomial Modelling and Its Applications (1996) [Fan 1996]. The recasting of all these estimators within the bias-variance and effective-degrees-of-freedom framework, and the explicit diagnosis of the curse of dimensionality as the structural limit of local methods, is due to Hastie, Tibshirani and Friedman's Elements of Statistical Learning [Hastie 2009].
Bibliography Master
@article{coverhart1967,
author = {Cover, Thomas M. and Hart, Peter E.},
title = {Nearest Neighbor Pattern Classification},
journal = {IEEE Transactions on Information Theory},
volume = {13},
number = {1},
pages = {21--27},
year = {1967}
}
@article{stone1977,
author = {Stone, Charles J.},
title = {Consistent Nonparametric Regression},
journal = {The Annals of Statistics},
volume = {5},
number = {4},
pages = {595--645},
year = {1977}
}
@book{fangijbels1996,
author = {Fan, Jianqing and Gijbels, Ir{\`e}ne},
title = {Local Polynomial Modelling and Its Applications},
publisher = {Chapman \& Hall},
address = {London},
year = {1996}
}
@book{hastie2009esl,
author = {Hastie, Trevor and Tibshirani, Robert and Friedman, Jerome},
title = {The Elements of Statistical Learning: Data Mining, Inference, and Prediction},
edition = {2},
publisher = {Springer},
year = {2009}
}
@article{nadaraya1964,
author = {Nadaraya, {\'E}lizbar A.},
title = {On Estimating Regression},
journal = {Theory of Probability and Its Applications},
volume = {9},
number = {1},
pages = {141--142},
year = {1964}
}
@article{watson1964,
author = {Watson, Geoffrey S.},
title = {Smooth Regression Analysis},
journal = {Sankhy\=a: The Indian Journal of Statistics, Series A},
volume = {26},
number = {4},
pages = {359--372},
year = {1964}
}
@techreport{fixhodges1951,
author = {Fix, Evelyn and Hodges, Joseph L.},
title = {Discriminatory Analysis, Nonparametric Discrimination: Consistency Properties},
institution = {USAF School of Aviation Medicine, Randolph Field, Texas},
number = {Report No. 4},
year = {1951}
}