Algorithm Search⌘K

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
Properties
deterministicexactlinear smoothernot randomizedreproduces constantsnot reproduces lines
Origin
E. A. Nadaraya, Geoffrey S. Watson, 1964

The Nadaraya-Watson estimator estimates a regression function m(x)=E[Y∣X=x]m(x) = \mathbb{E}[Y \mid X = x] without a model for its shape. At each point xx, it takes a weighted average of the responses yiy_i, and the weights come from a kernel: points with xix_i near xx count much, distant points little or not at all. The bandwidth hh 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 hh 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 nn pairs (x1,y1),…,(xn,yn)(x_1, y_1), \ldots, (x_n, y_n), a kernel K≥0K \ge 0 and a bandwidth h>0h > 0. The model is yi=m(xi)+eiy_i = m(x_i) + e_i with errors of mean 0. The output is the estimate

m^h(x)=∑i=1nK ⁣(x−xih)yi∑j=1nK ⁣(x−xjh)\hat m_h(x) = \frac{\sum_{i=1}^n K\!\left(\frac{x - x_i}{h}\right) y_i}{\sum_{j=1}^n K\!\left(\frac{x - x_j}{h}\right)}

at each point xx where it is wanted. It is undefined where the denominator is 0, which happens with a compact kernel far from all the data. Equivalently, m^h(x)\hat m_h(x) is the constant β0\beta_0 that minimizes ∑iK((x−xi)/h) (yi−β0)2\sum_i K((x - x_i)/h)\,(y_i - \beta_0)^2, a weighted least squares fit of degree 0.

The algorithm

  1. NADARAYA-WATSON(x, (x_1, y_1), ..., (x_n, y_n), h)
  2. 1num ← 0; den ← 0
  3. 2for i ← 1 to n do w ← K((x − x_i)/h)
  4. 3num ← num + w · y_i; den ← den + w
  5. 4if den = 0 then return undefined ▷ no data within the kernel's reach
  6. 5return num / den

The numerator divided by nhnh estimates m(x)f(x)m(x) f(x), and the denominator divided by nhnh is a kernel density estimate of f(x)f(x), the density of the xix_i. Their ratio estimates m(x)m(x). 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 O(n+mlog⁡m)O(n + m\log m) time. To choose hh, the code minimizes the leave-one-out prediction error 1n∑i(yi−m^h,−i(xi))2\frac1n\sum_i (y_i - \hat m_{h,-i}(x_i))^2. The estimate without point ii is (Ni−K(0)yi)/(Di−K(0))(N_i - K(0)y_i)/(D_i - K(0)), where NiN_i and DiD_i are the full sums at xix_i, so each score costs O(n2)O(n^2) and not O(n3)O(n^3).

Example

Seven points on the line y=2xy = 2x, at x=0,1,…,6x = 0, 1, \ldots, 6, with the Epanechnikov kernel K(u)=34(1−u2)K(u) = \frac34(1 - u^2) on [−1,1][-1, 1] and h=2h = 2. At x=0x = 0, the point 0 has u=0u = 0 and weight K(0)=3/4K(0) = 3/4, the point 1 has u=−1/2u = -1/2 and weight 9/169/16, and the point 2 is at the edge with weight 0. So

m^(0)=34⋅0+916⋅234+916=9/821/16=67≈0.857.\hat m(0) = \frac{\frac34 \cdot 0 + \frac9{16}\cdot 2}{\frac34 + \frac9{16}} = \frac{9/8}{21/16} = \frac67 \approx 0.857.
xx 0 1 2 3 4 5 6
true m(x)=2xm(x) = 2x 0 2 4 6 8 10 12
m^(x)\hat m(x), h=2h = 2 6/7 2 4 6 8 10 78/7
m^(x)\hat m(x), h=3h = 3 18/11 8/3 4 6 8 28/3 114/11

At x=1,…,5x = 1, \ldots, 5 with h=2h = 2, the neighbours lie symmetrically on both sides, and the estimate is exact. At the two ends it is pulled toward the inside by 6/76/7. With h=3h = 3 the error at the ends grows to 18/11≈1.6418/11 \approx 1.64, and it reaches x=1x = 1 and x=5x = 5 as well. If all the yiy_i were equal to one constant, the estimate would equal that constant everywhere. The test file checks these values in exact arithmetic.

Correctness

The weights wi(x)=K((x−xi)/h)/∑jK((x−xj)/h)w_i(x) = K((x - x_i)/h)/\sum_j K((x - x_j)/h) are non-negative and sum to 1, so the estimate is a convex combination of the responses. If all yi=cy_i = c, it is exactly cc, and it always lies between the smallest and the largest yiy_i. For a line m(x)=a+bxm(x) = a + bx the error is b∑iwi(x)(xi−x)b\sum_i w_i(x)(x_i - x), which is 0 only when the weighted mean of the xix_i is xx. At the end point 0 of an equally spaced design on [0,1][0, 1], with mm twice differentiable, the bias is

E m^(0)−m(0)=h m′(0) ∫01uK(u) du∫01K(u) du+O ⁣(h2+1N),\mathbb{E}\,\hat m(0) - m(0) = h\,m'(0)\,\frac{\int_0^1 uK(u)\,du}{\int_0^1 K(u)\,du} + O\!\left(h^2 + \frac1N\right),

which is 38h m′(0)\frac38 h\,m'(0) for the Epanechnikov kernel: a bias of order hh, not h2h^2. At interior design points the neighbours are symmetric, the linear term cancels, and the bias is O(h2)O(h^2). 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 (x1,y1),…,(xn,yn)(x_1, y_1), \ldots, (x_n, y_n) with yi=m(xi)+eiy_i = m(x_i) + e_i, where the errors have mean 0. The kernel K≥0K \ge 0 is symmetric, vanishes outside [−1,1][-1, 1], and has ∫K=1\int K = 1; the Epanechnikov kernel of the code is one. For h>0h > 0 and a point xx with D(x)=∑jK((x−xj)/h)>0D(x) = \sum_j K((x - x_j)/h) > 0, the estimate is

m^(x)=∑i=1nwi(x) yi,wi(x)=K((x−xi)/h)D(x).\hat m(x) = \sum_{i=1}^n w_i(x)\,y_i, \qquad w_i(x) = \frac{K((x - x_i)/h)}{D(x)}.

Lines L1 to L3 compute the numerator ∑iK((x−xi)/h) yi\sum_i K((x - x_i)/h)\,y_i and the denominator D(x)D(x), line L4 detects D(x)=0D(x) = 0, and line L5 returns their ratio, which is m^(x)\hat m(x).

Part 1. Exact properties

Lemma 1. The weights are non-negative and sum to 1.

Proof. Each K((x−xi)/h)≥0K((x - x_i)/h) \ge 0, and the sum of the numerators of the wiw_i is the denominator D(x)>0D(x) > 0. □\square

Theorem 2 (a constant is reproduced exactly). If yi=cy_i = c for all ii, then m^(x)=c\hat m(x) = c at every xx where the estimate is defined.

Proof. m^(x)=∑iwi(x) c=c∑iwi(x)=c\hat m(x) = \sum_i w_i(x)\,c = c\sum_i w_i(x) = c by Lemma 1. □\square

The test file checks Theorem 2 in exact rational arithmetic on random designs.

Corollary 3. min⁡iyi≤m^(x)≤max⁡iyi\min_i y_i \le \hat m(x) \le \max_i y_i, and adding a constant cc to every yiy_i adds cc to m^(x)\hat m(x).

Proof. By Lemma 1, m^(x)\hat m(x) is a convex combination of the yiy_i. The second claim is Theorem 2 plus the linearity of m^\hat m in yy. □\square

A line is not reproduced in general. With m(x)=a+bxm(x) = a + bx and no noise, m^(x)−m(x)=b∑iwi(x)(xi−x)\hat m(x) - m(x) = b\sum_i w_i(x)(x_i - x), which is 0 only when the weighted mean of the xix_i is xx. That holds when the design is symmetric around xx within distance hh, 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 NiN_i and DiD_i be the numerator and denominator at x=xix = x_i with all points. Then the estimate at xix_i without point ii is (Ni−K(0) yi)/(Di−K(0))(N_i - K(0)\,y_i)/(D_i - K(0)), when Di>K(0)D_i > K(0).

Proof. Point ii contributes K((xi−xi)/h) yi=K(0) yiK((x_i - x_i)/h)\,y_i = K(0)\,y_i to NiN_i and K(0)K(0) to DiD_i. □\square

Part 2. Bias at the boundary and in the interior

Take the equally spaced design xi=i/Nx_i = i/N, i=0,…,Ni = 0, \ldots, N, on [0,1][0, 1], so n=N+1n = N + 1. The weights depend only on the design, so E m^(x)=∑iwi(x) m(xi)\mathbb{E}\,\hat m(x) = \sum_i w_i(x)\,m(x_i), and the bias is ∑iwi(x)(m(xi)−m(x))\sum_i w_i(x)\big(m(x_i) - m(x)\big). Let

μk+=∫01ukK(u) du,μ0+=12,μ1+>0.\mu_k^+ = \int_0^1 u^k K(u)\,du, \qquad \mu_0^+ = \tfrac12, \qquad \mu_1^+ > 0.

Lemma 5 (Riemann sums). Let δ=1/(Nh)\delta = 1/(Nh) and Sk=δ∑i≥0, iδ≤1K(iδ) (iδ)kS_k = \delta\sum_{i \ge 0,\ i\delta \le 1} K(i\delta)\,(i\delta)^k for k=0,1k = 0, 1. Then ∣Sk−μk+∣≤δ (V+2M)|S_k - \mu_k^+| \le \delta\,(V + 2M), where VV is the total variation of ukK(u)u^k K(u) on [0,1][0, 1] and M=sup⁡KM = \sup K.

Proof. Let g(u)=ukK(u)g(u) = u^k K(u) on [0,1][0, 1] and let JJ be the largest ii with iδ≤1i\delta \le 1. On each cell [iδ,(i+1)δ][i\delta, (i+1)\delta] with i<Ji < J, ∣δ g(iδ)−∫cellg∣≤δ⋅(variation of g on the cell)|\delta\,g(i\delta) - \int_{\text{cell}} g| \le \delta \cdot (\text{variation of } g \text{ on the cell}), and the variations of the cells add up to at most VV. The last term δ g(Jδ)\delta\,g(J\delta) and the integral over [Jδ,1][J\delta, 1], a piece of length less than δ\delta, each add at most δM\delta M. □\square

Theorem 6 (boundary bias of order hh). Let mm have a bounded second derivative on [0,1][0, 1]. Then at the end point x=0x = 0,

E m^(0)−m(0)=h m′(0) μ1+μ0++O ⁣(h2+1N).\mathbb{E}\,\hat m(0) - m(0) = h\,m'(0)\,\frac{\mu_1^+}{\mu_0^+} + O\!\left(h^2 + \frac{1}{N}\right).

So if m′(0)≠0m'(0) \ne 0, the bias is of exact order hh as h→0h \to 0 and Nh→∞Nh \to \infty. For the Epanechnikov kernel, μ1+=34(12−14)=316\mu_1^+ = \frac34\left(\frac12 - \frac14\right) = \frac3{16} and the factor is μ1+/μ0+=38\mu_1^+/\mu_0^+ = \frac38.

Proof. Only the points with xi≤hx_i \le h have weight. By Taylor's theorem, m(xi)−m(0)=m′(0) xi+rim(x_i) - m(0) = m'(0)\,x_i + r_i with ∣ri∣≤12sup⁡∣m′′∣ xi2≤12sup⁡∣m′′∣ h2|r_i| \le \frac12\sup|m''|\,x_i^2 \le \frac12\sup|m''|\,h^2. With Lemma 1,

∑iwi(0)(m(xi)−m(0))=m′(0)∑iwi(0) xi+O(h2).\sum_i w_i(0)\big(m(x_i) - m(0)\big) = m'(0)\sum_i w_i(0)\,x_i + O(h^2).

Write xi=h⋅(iδ)x_i = h\cdot(i\delta) with δ=1/(Nh)\delta = 1/(Nh). Then ∑iwi(0) xi=h S1/S0\sum_i w_i(0)\,x_i = h\,S_1/S_0, with S0,S1S_0, S_1 as in Lemma 5. Lemma 5 gives Sk=μk++O(δ)S_k = \mu_k^+ + O(\delta), and μ0+=12\mu_0^+ = \frac12, so S1/S0=μ1+/μ0++O(δ)S_1/S_0 = \mu_1^+/\mu_0^+ + O(\delta). Multiplying by hh turns O(δ)O(\delta) into O(hδ)=O(1/N)O(h\delta) = O(1/N). □\square

The reason is plain: at the end of the data, all the points with weight lie on one side of xx, so their weighted mean is about 0.375 h0.375\,h away from xx, and a sloped mm is evaluated there instead of at xx. The test file measures the ratio of the bias to bhb h for m(x)=2−3xm(x) = 2 - 3x: 0.3722 for N=1000N = 1000, h=0.1h = 0.1 and 0.3736 for N=4000N = 4000, h=0.05h = 0.05, against the limit 0.375. For the Gaussian kernel, which is not compactly supported, the same computation gives the factor ∫0∞uφ(u) du/12=2/π≈0.798\int_0^\infty u\varphi(u)\,du / \frac12 = \sqrt{2/\pi} \approx 0.798; the test checks this too.

Theorem 7 (interior bias of order h2h^2 on a symmetric design). If x=xkx = x_k is a design point with h≤x≤1−hh \le x \le 1 - h, then E m^(x)−m(x)=O(h2)\mathbb{E}\,\hat m(x) - m(x) = O(h^2), and the bias is 0 when mm is linear.

Proof. The points with weight are xk±jx_{k \pm j} with j/N<hj/N < h, and KK is symmetric, so wk+j(x)=wk−j(x)w_{k+j}(x) = w_{k-j}(x) and ∑iwi(x)(xi−x)=0\sum_i w_i(x)(x_i - x) = 0. So the linear term of the Taylor expansion cancels, and what remains is at most 12sup⁡∣m′′∣ h2\frac12\sup|m''|\,h^2. If mm is linear, nothing remains. □\square

What is cited, not proved

For a random design with density ff, the interior bias is h2μ2(12m′′(x)+m′(x)f′(x)/f(x))+o(h2)h^2\mu_2\big(\tfrac12 m''(x) + m'(x)f'(x)/f(x)\big) + o(h^2) and the variance is σ2(x) R(K)/(nhf(x))+o(1/(nh))\sigma^2(x)\,R(K)/(nh f(x)) + o(1/(nh)) (Wand and Jones 1995, Chapter 5; Fan and Gijbels 1996, Chapter 3). The term m′f′/fm'f'/f, 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 μ1+/μ0+\mu_1^+/\mu_0^+, when ff is continuous and positive at the end point. The test file measures the interior bias of m(x)=x2m(x) = x^2 on the uniform design: the ratio of the bias to h2h^2 was 0.19998 and 0.199995, against μ2m′′/2=1/5\mu_2 m''/2 = 1/5.

Cost

Lines L1 to L5 make one pass over the data, with O(1)O(1) work for each point, so the estimate at one point takes O(n)O(n) time and O(1)O(1) extra space. The leave-one-out score takes O(n2)O(n^2) time by Lemma 4.

Complexity

  • One point. Lines L1 to L5 take O(n)O(n) time and O(1)O(1) extra space. For qq points, O(nq)O(nq).
  • Compact kernel and sorted data. Only the points within hh of xx count. Binary search finds them, so a point costs O(log⁡n+k)O(\log n + k) for kk 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 mm grid points in O(n+mlog⁡m)O(n + m\log m) time.
  • Choosing hh. Leave-one-out cross-validation costs O(n2)O(n^2) for each candidate bandwidth.

Properties

  • Linear smoother. m^=Wy\hat m = W y with weights that depend only on the xix_i, so the variance and the leave-one-out residuals have simple formulas.
  • Rate. In the interior, the bias is h2μ2(12m′′+m′f′/f)h^2\mu_2\big(\tfrac12 m'' + m'f'/f\big) and the variance σ2R(K)/(nhf(x))\sigma^2 R(K)/(nhf(x)), to first order, where ff is the density of the xix_i. With the best hh of order n−1/5n^{-1/5}, the mean squared error falls like n−4/5n^{-4/5} (Wand and Jones 1995). These are cited, not proved here.
  • Design bias. The term m′f′/fm'f'/f 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 hh 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 kk nearest xix_i instead of a fixed hh, 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 n−4/(d+4)n^{-4/(d+4)}, and the method needs very many points for more than a few predictors.
  • Classification. With yi∈{0,1}y_i \in \{0, 1\}, 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 xix_i 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 hh, the estimate is undefined in gaps of the data. Use a kernel with unbounded support, a larger hh, or nearest-neighbour windows.
  • The bandwidth for density is not the bandwidth for regression. A bandwidth chosen for the density of the xix_i ignores how fast mm changes. Use cross-validation on the prediction error, or a plug-in rule for regression.
  • Outliers in yy. 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 σ2(x)/f(x)\sigma^2(x)/f(x); 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.

nadaraya_watson_estimator.pyI0RawGitHub
# 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

  1. E. A. Nadaraya, On estimating regression, Theory of Probability and Its Applications 9(1), 1964, pp. 141 to 142 (the estimator and its consistency)
  2. 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)
  3. 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)
  4. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.binned
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example