Algorithmcore
Nadaraya-Watson estimator
Also called kernel regression estimator, local constant regression.
Estimates a regression function at x by a weighted average of the responses, with kernel weights that fall with the distance of each x_i from x.
- Time
- O(n q) worstO(n + m log m) binned
- Space
- O(1) extra
- Where
- m = the number of grid points; n = the number of data points; q = the number of points where the estimate is wanted
- Model
- Real RAM
- Properties
- deterministicexactlinear smoothernot randomizedreproduces constantsnot reproduces lines
- Evidence
- Proof sketchCode in 1 languages
- Origin
- E. A. Nadaraya, Geoffrey S. Watson, 1964
The Nadaraya-Watson estimator estimates a regression function without a model for its shape. At each point , it takes a weighted average of the responses , and the weights come from a kernel: points with near count much, distant points little or not at all. The bandwidth sets how near is near. It is the regression form of kernel density estimation, and it is local polynomial regression of degree 0, a constant fitted by weighted least squares around each point. It reproduces a constant exactly, but not a line, so it has a bias of order at the ends of the data.
In plain words
To guess the value of a curve at some place, look at the data points with nearby positions and average their values. Give close points more say than far points: a point right at the place gets the most weight, a point at the edge of the window gets almost none, and points outside the window get none.
This works well in the middle of the data, where there are neighbours on both sides. At the ends, all the neighbours lie on one side. If the curve rises there, the neighbours are all higher (or all lower) than the curve at the end, and the average is pulled away. The wider the window, the larger this error.
The problem
The input is pairs , a kernel and a bandwidth . The model is with errors of mean 0. The output is the estimate
at each point where it is wanted. It is undefined where the denominator is 0, which happens with a compact kernel far from all the data. Equivalently, is the constant that minimizes , a weighted least squares fit of degree 0.
The algorithm
NADARAYA-WATSON(x, (x_1, y_1), ..., (x_n, y_n), h)- 1
num ← 0; den ← 0 - 2
for i ← 1 to n do w ← K((x − x_i)/h) - 3
num ← num + w · y_i; den ← den + w - 4
if den = 0 then return undefined ▷ no data within the kernel's reach - 5
return num / den
The numerator divided by estimates , and the denominator divided by is a kernel density estimate of , the density of the . Their ratio estimates . That is how Watson derived it.
For many points on a grid, both sums are discrete convolutions of binned data with the sampled kernel, so the FFT method of kernel density estimation computes the whole curve in time. To choose , the code minimizes the leave-one-out prediction error . The estimate without point is , where and are the full sums at , so each score costs and not .
Example
Seven points on the line , at , with the Epanechnikov kernel on and . At , the point 0 has and weight , the point 1 has and weight , and the point 2 is at the edge with weight 0. So
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | |
|---|---|---|---|---|---|---|---|
| true | 0 | 2 | 4 | 6 | 8 | 10 | 12 |
| , | 6/7 | 2 | 4 | 6 | 8 | 10 | 78/7 |
| , | 18/11 | 8/3 | 4 | 6 | 8 | 28/3 | 114/11 |
At with , the neighbours lie symmetrically on both sides, and the estimate is exact. At the two ends it is pulled toward the inside by . With the error at the ends grows to , and it reaches and as well. If all the were equal to one constant, the estimate would equal that constant everywhere. The test file checks these values in exact arithmetic.
Correctness
The weights are non-negative and sum to 1, so the estimate is a convex combination of the responses. If all , it is exactly , and it always lies between the smallest and the largest . For a line the error is , which is 0 only when the weighted mean of the is . At the end point 0 of an equally spaced design on , with twice differentiable, the bias is
which is for the Epanechnikov kernel: a bias of order , not . At interior design points the neighbours are symmetric, the linear term cancels, and the bias is . The full proofs are below; the bias and variance for a random design are cited.
Proof: The Nadaraya-Watson estimate reproduces a constant exactly, stays in the range of the responses, and has a boundary bias of order hfull
Setting. The data are pairs with , where the errors have mean 0. The kernel is symmetric, vanishes outside , and has ; the Epanechnikov kernel of the code is one. For and a point with , the estimate is
Lines L1 to L3 compute the numerator and the denominator , line L4 detects , and line L5 returns their ratio, which is .
Part 1. Exact properties
Lemma 1. The weights are non-negative and sum to 1.
Proof. Each , and the sum of the numerators of the is the denominator .
Theorem 2 (a constant is reproduced exactly). If for all , then at every where the estimate is defined.
Proof. by Lemma 1.
The test file checks Theorem 2 in exact rational arithmetic on random designs.
Corollary 3. , and adding a constant to every adds to .
Proof. By Lemma 1, is a convex combination of the . The second claim is Theorem 2 plus the linearity of in .
A line is not reproduced in general. With and no noise, , which is 0 only when the weighted mean of the is . That holds when the design is symmetric around within distance , as at the interior grid points of an equally spaced design, but it fails near the ends of the data.
Lemma 4 (the leave-one-out shortcut). Let and be the numerator and denominator at with all points. Then the estimate at without point is , when .
Proof. Point contributes to and to .
Part 2. Bias at the boundary and in the interior
Take the equally spaced design , , on , so . The weights depend only on the design, so , and the bias is . Let
Lemma 5 (Riemann sums). Let and for . Then , where is the total variation of on and .
Proof. Let on and let be the largest with . On each cell with , , and the variations of the cells add up to at most . The last term and the integral over , a piece of length less than , each add at most .
Theorem 6 (boundary bias of order ). Let have a bounded second derivative on . Then at the end point ,
So if , the bias is of exact order as and . For the Epanechnikov kernel, and the factor is .
Proof. Only the points with have weight. By Taylor's theorem, with . With Lemma 1,
Write with . Then , with as in Lemma 5. Lemma 5 gives , and , so . Multiplying by turns into .
The reason is plain: at the end of the data, all the points with weight lie on one side of , so their weighted mean is about away from , and a sloped is evaluated there instead of at . The test file measures the ratio of the bias to for : 0.3722 for , and 0.3736 for , , against the limit 0.375. For the Gaussian kernel, which is not compactly supported, the same computation gives the factor ; the test checks this too.
Theorem 7 (interior bias of order on a symmetric design). If is a design point with , then , and the bias is 0 when is linear.
Proof. The points with weight are with , and is symmetric, so and . So the linear term of the Taylor expansion cancels, and what remains is at most . If is linear, nothing remains.
What is cited, not proved
For a random design with density , the interior bias is and the variance is (Wand and Jones 1995, Chapter 5; Fan and Gijbels 1996, Chapter 3). The term , the design bias, is absent for a uniform design, as in Theorem 7. For a random design the boundary result of Theorem 6 holds in probability, with the same factor , when is continuous and positive at the end point. The test file measures the interior bias of on the uniform design: the ratio of the bias to was 0.19998 and 0.199995, against .
Cost
Lines L1 to L5 make one pass over the data, with work for each point, so the estimate at one point takes time and extra space. The leave-one-out score takes time by Lemma 4.
Complexity
- One point. Lines L1 to L5 take time and extra space. For points, .
- Compact kernel and sorted data. Only the points within of count. Binary search finds them, so a point costs for points in the window, and a sweep over sorted query points updates the two sums as the window moves.
- Grid. With linear binning, two FFT convolutions give the numerator and the denominator on grid points in time.
- Choosing . Leave-one-out cross-validation costs for each candidate bandwidth.
Properties
- Linear smoother. with weights that depend only on the , so the variance and the leave-one-out residuals have simple formulas.
- Rate. In the interior, the bias is and the variance , to first order, where is the density of the . With the best of order , the mean squared error falls like (Wand and Jones 1995). These are cited, not proved here.
- Design bias. The term means the estimate is biased where the design density changes, even for a straight line. The local linear fit has no such term.
- Boundary bias. Of order at the ends of the data, as in the example and the theorem above.
- Bounded output. The estimate never leaves the range of the responses, so it never overshoots. This is useful for probabilities and other bounded responses, and the reason why it flattens peaks.
Variants and improvements
- Local polynomial regression. Fit a line, not a constant, in each window. Local linear regression removes the boundary bias and the design bias, at a small cost in variance.
- Nearest-neighbour windows. Use the nearest instead of a fixed , so the window widens where the data are sparse; with a uniform kernel this is k-nearest neighbour regression.
- Gasser-Müller and Priestley-Chao. Weights from the spacing of a fixed design instead of a density estimate. They have no design bias, but a larger variance for random designs.
- Boundary kernels. Kernels that change shape near the ends of the data, so that the first moment of the weights is 0 there.
- Several predictors. Use a product kernel or a kernel on a distance. The rate becomes , and the method needs very many points for more than a few predictors.
- Classification. With , the estimate is a smoothed class proportion, a kernel classifier.
When to use it
Use it for a quick smooth curve through a scatter plot, for a nonparametric estimate of a conditional mean or a conditional probability, and as a building block, for example inside kernel estimates of conditional densities. Its output stays within the range of the data, which suits bounded responses. When the curve matters near the ends of the data, or when the are unevenly spread, prefer a local linear fit. When you need a smooth function with good extrapolation, consider a smoothing spline or a Gaussian process.
Pitfalls
- Bias at the boundary. A rising curve is estimated too low at its right end and too high at its left end, or the opposite for a falling curve. In a regression discontinuity design, the effect is estimated exactly at a boundary, and the Nadaraya-Watson estimate is biased there; local linear fits are the standard choice.
- Empty windows. With a compact kernel and a small , the estimate is undefined in gaps of the data. Use a kernel with unbounded support, a larger , or nearest-neighbour windows.
- The bandwidth for density is not the bandwidth for regression. A bandwidth chosen for the density of the ignores how fast changes. Use cross-validation on the prediction error, or a plug-in rule for regression.
- Outliers in . The estimate is a weighted mean, so one wild response moves it. A robust local fit, such as LOWESS, guards against this.
- Heteroscedastic errors. The variance of the estimate follows ; confidence bands must allow for it.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/nadaraya-watson-estimator/. The authors are listed in prov/HA8PMS.jsonl.
import math
def gaussian(u):
return math.exp(-0.5 * u * u) / math.sqrt(2 * math.pi)
def epanechnikov(u):
"""(3/4)(1 - u^2) on [-1, 1]; works with floats and Fractions."""
return 3 * (1 - u * u) / 4 if -1 <= u <= 1 else 0 * u
def weights(x, xs, h, kernel=epanechnikov):
"""The Nadaraya-Watson weights w_i(x); they sum to 1. None if all are 0."""
k = [kernel((x - xi) / h) for xi in xs]
s = sum(k)
if s == 0:
return None
return [v / s for v in k]
def nadaraya_watson(x, xs, ys, h, kernel=epanechnikov):
"""m(x) = sum K((x - x_i)/h) y_i / sum K((x - x_i)/h). O(n) time.
Returns None where no x_i is within the support of the kernel.
"""
num = 0 * x # @line L1
den = 0 * x
for xi, yi in zip(xs, ys):
w = kernel((x - xi) / h) # @line L2
num += w * yi # @line L3
den += w
if den == 0: # @line L4
return None
return num / den # @line L5
def loo_cv(h, xs, ys, kernel=epanechnikov):
"""Leave-one-out mean squared prediction error, in O(n^2).
Uses m_{-i}(x_i) = (num_i - K(0) y_i) / (den_i - K(0)): removing point i
from the sums at x_i removes the term K(0) y_i and K(0).
Points whose leave-one-out denominator is 0 are skipped.
"""
k0 = kernel(0 * h)
tot, cnt = 0, 0
for xi, yi in zip(xs, ys):
num = sum(kernel((xi - xj) / h) * yj for xj, yj in zip(xs, ys)) - k0 * yi
den = sum(kernel((xi - xj) / h) for xj in xs) - k0
if den > 0:
tot += (yi - num / den) ** 2
cnt += 1
return tot / cnt if cnt else math.inf
def loo_cv_brute(h, xs, ys, kernel=epanechnikov):
"""The same score by refitting without each point (for tests)."""
tot, cnt = 0, 0
for i in range(len(xs)):
rest_x = xs[:i] + xs[i + 1:]
rest_y = ys[:i] + ys[i + 1:]
m = nadaraya_watson(xs[i], rest_x, rest_y, h, kernel)
if m is not None:
tot += (ys[i] - m) ** 2
cnt += 1
return tot / cnt if cnt else math.inf
def choose_bandwidth(xs, ys, candidates, kernel=epanechnikov):
"""The candidate with the smallest leave-one-out error."""
return min(candidates, key=lambda h: loo_cv(h, xs, ys, kernel))
test_nadaraya_watson_estimator.py 103 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/nadaraya-watson-estimator/. The authors are listed in prov/HA8PMS.jsonl.
import math
import random
from fractions import Fraction
from nadaraya_watson_estimator import (
choose_bandwidth, epanechnikov, gaussian, loo_cv, loo_cv_brute,
nadaraya_watson, weights,
)
def test_page_example() -> None:
xs = list(range(7))
ys = [2 * x for x in xs]
got = [nadaraya_watson(Fraction(x), xs, ys, Fraction(2)) for x in range(7)]
assert got == [Fraction(6, 7), 2, 4, 6, 8, 10, Fraction(78, 7)]
got = [nadaraya_watson(Fraction(x), xs, ys, Fraction(3)) for x in range(7)]
assert got == [Fraction(18, 11), Fraction(8, 3), 4, 6, 8, Fraction(28, 3), Fraction(114, 11)]
assert nadaraya_watson(Fraction(-3), xs, ys, Fraction(2)) is None
def test_reproduces_a_constant_exactly() -> None:
rng = random.Random(71)
for _ in range(200):
n = rng.randint(1, 12)
xs = [Fraction(rng.randint(-30, 30), rng.randint(1, 5)) for _ in range(n)]
c = Fraction(rng.randint(-50, 50), rng.randint(1, 7))
h = Fraction(rng.randint(1, 20), rng.randint(1, 5))
x = Fraction(rng.randint(-40, 40), rng.randint(1, 5))
m = nadaraya_watson(x, xs, [c] * n, h)
assert m is None or m == c
def test_weights_and_range() -> None:
rng = random.Random(72)
for _ in range(200):
n = rng.randint(1, 15)
xs = [Fraction(rng.randint(-30, 30), rng.randint(1, 5)) for _ in range(n)]
ys = [Fraction(rng.randint(-30, 30)) for _ in range(n)]
h = Fraction(rng.randint(1, 20), rng.randint(1, 5))
x = Fraction(rng.randint(-40, 40), rng.randint(1, 5))
w = weights(x, xs, h)
m = nadaraya_watson(x, xs, ys, h)
if w is None:
assert m is None
continue
assert sum(w) == 1 and min(w) >= 0
assert m == sum(wi * yi for wi, yi in zip(w, ys))
assert min(ys) <= m <= max(ys)
def test_boundary_bias_is_of_order_h() -> None:
# Equally spaced design i/N on [0, 1], m(x) = a + b x, no noise: the
# estimate at 0 is a + b sum w_i x_i, and bias/(b h) tends to
# int_0^1 u K / int_0^1 K, which is 3/8 for the Epanechnikov kernel.
a, b = Fraction(2), Fraction(-3)
for N, h in ((1000, Fraction(1, 10)), (4000, Fraction(1, 20))):
xs = [Fraction(i, N) for i in range(N + 1)]
ys = [a + b * x for x in xs]
bias = nadaraya_watson(Fraction(0), xs, ys, h) - a
assert abs(bias / (b * h) - Fraction(3, 8)) < 3 / (N * h)
# In the interior the design is symmetric around x, and the bias is 0.
assert nadaraya_watson(Fraction(1, 2), xs, ys, h) == a + b / 2
# Gaussian kernel: the limit is phi(0) / (1/2) = sqrt(2/pi).
N, h = 4000, 0.02
xs = [i / N for i in range(N + 1)]
bias = nadaraya_watson(0.0, xs, [1 + 5 * x for x in xs], h, gaussian) - 1
assert abs(bias / (5 * h) - math.sqrt(2 / math.pi)) < 3 / (N * h)
def test_interior_bias_is_of_order_h_squared() -> None:
# For m(x) = x^2 on a uniform design, bias/h^2 tends to mu2 m''/2 = 1/5.
for N, h in ((2000, Fraction(1, 10)), (4000, Fraction(1, 20))):
xs = [Fraction(i, N) for i in range(N + 1)]
bias = nadaraya_watson(Fraction(1, 2), xs, [x * x for x in xs], h) - Fraction(1, 4)
assert abs(bias / (h * h) - Fraction(1, 5)) < 5 / (N * h) ** 2 + Fraction(1, 10**9)
def test_leave_one_out_shortcut() -> None:
rng = random.Random(73)
for _ in range(30):
n = rng.randint(2, 10)
xs = [Fraction(rng.randint(0, 20)) for _ in range(n)]
ys = [Fraction(rng.randint(-9, 9)) for _ in range(n)]
h = Fraction(rng.randint(1, 12), 2)
assert loo_cv(h, xs, ys) == loo_cv_brute(h, xs, ys)
def test_choose_bandwidth_on_a_curve() -> None:
rng = random.Random(74)
n = 120
xs = sorted(rng.random() for _ in range(n))
ys = [math.sin(2 * math.pi * x) + rng.gauss(0, 0.3) for x in xs]
cands = [0.02 * k for k in range(2, 26)]
h = choose_bandwidth(xs, ys, cands)
assert all(loo_cv_brute(h, xs, ys) <= loo_cv_brute(g, xs, ys) + 1e-12 for g in cands)
# Measured, not guaranteed: the chosen fit is closer to the truth than
# the narrowest and the widest candidates.
err = lambda g: sum((nadaraya_watson(t / 50, xs, ys, g) - math.sin(2 * math.pi * t / 50)) ** 2
for t in range(5, 46))
assert err(h) < err(cands[0]) and err(h) < err(cands[-1])
History
Nadaraya and Watson published the estimator independently in 1964. Nadaraya proved its consistency; Watson derived it as the ratio of kernel estimates and applied it to data. Priestley and Chao (1972) and Gasser and Müller (1979) proposed weights for fixed designs. In the early 1990s, Fan showed that the local linear fit has better bias at the boundary and in designs that are not uniform, with the same variance order. Since then the Nadaraya-Watson estimator has been seen as the degree 0 case of local polynomial regression.
References
- E. A. Nadaraya, On estimating regression, Theory of Probability and Its Applications 9(1), 1964, pp. 141 to 142 (the estimator and its consistency)
- Geoffrey S. Watson, Smooth regression analysis, Sankhyā Series A 26(4), 1964, pp. 359 to 372, The whole paper (the same estimator, from a kernel estimate of the joint density)
- M. P. Wand and M. C. Jones, Kernel Smoothing, Chapman and Hall, 1995, Chapter 5 (kernel regression; the bias and variance of the local constant estimator, the design bias and the boundary bias)
- Jianqing Fan and Irène Gijbels, Local Polynomial Modelling and Its Applications, Chapman and Hall, 1996, Chapter 3 (the Nadaraya-Watson estimator as a local polynomial fit of degree 0, and its comparison with the local linear fit)
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag HA8PMS Edit this page History Report an error Markdown