Algorithm Search⌘K

Problemcore

Bandwidth selection

Also called Silverman's rule of thumb, smoothing parameter selection.

Choose the bandwidth of a kernel estimator, by a rule of thumb, by cross-validation or by plug-in estimates of the integrated squared error.

Bandwidth selection is the problem of choosing, from the data alone, the bandwidth hh of a kernel density estimate or another kernel smoother. The bandwidth sets the balance between bias and variance, and it changes the estimate much more than the choice of kernel does. The target is the hh that makes the integrated squared error small, but that error depends on the unknown density. So every method replaces it by something it can compute: the error at a normal density with the same scale (a rule of thumb), an unbiased estimate of the error from the sample (cross-validation), or the asymptotic formula with the unknown functional estimated from the data (plug-in).

In plain words

A kernel density estimate puts a bump on every data point, and the bandwidth is the width of the bumps. Too narrow, and the curve shows a peak at every point. Too wide, and two real groups melt into one. We want the width that makes the estimate closest to the true curve, but we do not know the true curve.

There are three common ways out. Pretend the data are bell shaped and use the best width for a bell curve. Or leave out each point in turn, and see how well the estimate made from the other points predicts it. Or use the formula for the best width, which needs the curvature of the true curve, and estimate that curvature from the data. The first is quick but can smooth too much. The second follows the data but is noisy. The third is a good default.

Definition

The input is a sample X1,…,XnX_1, \ldots, X_n from an unknown density ff on R\mathbb{R} and a kernel KK. For each h>0h > 0 let f^h(x)=(nh)−1∑iK((x−Xi)/h)\hat f_h(x) = (nh)^{-1}\sum_i K((x - X_i)/h). The loss of hh is the integrated squared error, and its mean is the MISE:

ISE(h)=∫(f^h−f)2,MISE(h)=E ISE(h).\mathrm{ISE}(h) = \int (\hat f_h - f)^2, \qquad \mathrm{MISE}(h) = \mathbb{E}\,\mathrm{ISE}(h).

A bandwidth selector is a function h^=h^(X1,…,Xn)\hat h = \hat h(X_1, \ldots, X_n). Its targets are hISEh_{\mathrm{ISE}}, the minimizer of the ISE for the sample at hand, and hMISEh_{\mathrm{MISE}}, the minimizer of the MISE. A selector is judged by its relative error h^/hMISE−1\hat h/h_{\mathrm{MISE}} - 1, and the usual measure is the power α\alpha for which this error is of order n−αn^{-\alpha}.

For a kernel with ∫K=1\int K = 1, μ2=∫u2K\mu_2 = \int u^2 K and R(K)=∫K2R(K) = \int K^2, and a density with a smooth second derivative, the asymptotic MISE is minimized at

hAMISE=(R(K)μ22 R(f′′) n)1/5,R(f′′)=∫f′′(x)2 dx=ψ4,h_{\mathrm{AMISE}} = \left(\frac{R(K)}{\mu_2^2\, R(f'')\, n}\right)^{1/5}, \qquad R(f'') = \int f''(x)^2\,dx = \psi_4,

where ψr=∫f(r)f=E f(r)(X)\psi_r = \int f^{(r)} f = \mathbb{E}\,f^{(r)}(X); the last identity for ψ4\psi_4 is integration by parts twice. The proof is on the kernel density estimation page. The only unknown is R(f′′)R(f''), the total curvature of ff.

Variants

  • Target. Minimize the ISE of the sample, the MISE, or the asymptotic MISE. They agree to first order but differ for small samples, and hISEh_{\mathrm{ISE}} itself varies from sample to sample with relative error of order n−1/10n^{-1/10}.
  • Other losses. The integrated absolute error, or the Kullback-Leibler loss, which likelihood cross-validation targets. They lead to different bandwidths, especially in the tails.
  • Several dimensions. A bandwidth matrix HH in place of hh. A diagonal HH has dd parameters and a full one has d(d+1)/2d(d+1)/2; the normal reference rule becomes H=(4/((d+2)n))2/(d+4)Σ^H = (4/((d+2)n))^{2/(d+4)}\hat\Sigma.
  • Local and adaptive bandwidths. A bandwidth h(x)h(x) that changes along the line, or one hih_i for each data point.
  • Regression. For the Nadaraya-Watson estimator and local polynomial regression, the loss is the squared error of the fitted mean, and leave-one-out prediction error is the cross-validation criterion.

Examples

Fourteen points in two groups:

−1.9, −1.6, −1.5, −1.3, −1.2, −1.0, −0.8, 0.9, 1.1, 1.2, 1.4, 1.5, 1.7, 2.0.-1.9,\ -1.6,\ -1.5,\ -1.3,\ -1.2,\ -1.0,\ -0.8,\ 0.9,\ 1.1,\ 1.2,\ 1.4,\ 1.5,\ 1.7,\ 2.0.

The sample standard deviation is s=1.4606s = 1.4606. The quartiles, by linear interpolation at position (n−1)p(n-1)p, are −1.275-1.275 and 1.351.35, so the interquartile range is 2.6252.625. With the Gaussian kernel, the selectors of the code on this page give:

selector formula hh estimate at the dip x=0x = 0 highest value
normal reference (4/(3n))1/5s(4/(3n))^{1/5} s 0.913 0.155 0.208
Silverman (1986), robust 0.9min⁡(s,IQR/1.34) n−1/50.9 \min(s, \mathrm{IQR}/1.34)\, n^{-1/5} 0.775 0.130 0.235
least squares cross-validation minimizer of LSCV 0.464 0.040 0.338
two-stage direct plug-in (R(K)/(ψ^4n))1/5(R(K)/(\hat\psi_4 n))^{1/5} 0.537 0.063 0.309

All four estimates have two modes, near −1.3-1.3 and 1.351.35. The two rules smooth much more, because a sample with two well separated groups has a large standard deviation but a small spread within each group. Here IQR/1.34=1.959>s\mathrm{IQR}/1.34 = 1.959 > s, so the robust rule uses ss and differs from the normal reference only by its factor 0.9. The LSCV criterion, as a function of hh:

hh 0.1 0.2 0.3 0.4 0.6 0.8 1.0
LSCV(hh) 0.0916 −0.1364 −0.2199 −0.2479 −0.2410 −0.2099 −0.1840

It is flat near its minimum: values of hh from 0.4 to 0.6 differ by less than 0.01. This flatness is the reason the cross-validated bandwidth varies so much between samples.

Measured behaviour on simulated data. These are measurements with the code of this page, not theorems. The reference hMISEh_{\mathrm{MISE}} is computed from the exact MISE formula of Marron and Wand (1992).

data nn hMISEh_{\mathrm{MISE}} normal reference robust 0.9 rule LSCV plug-in
N(0,1)N(0, 1), 30 samples 100 0.446 0.94 (0.80 to 1.09) 0.77 (0.53 to 0.91) 0.94 (0.27 to 1.48) 0.92 (0.59 to 1.21)
N(0,1)N(0, 1), 30 samples 400 0.330 0.96 (0.91 to 1.02) 0.80 (0.76 to 0.87) 0.97 (0.36 to 1.23) 0.95 (0.74 to 1.06)

The entries are the mean of h^/hMISE\hat h/h_{\mathrm{MISE}}, with the smallest and largest value in brackets. For normal data the normal reference rule is close to the target and has the least spread. LSCV is nearly unbiased but very variable. For the separated bimodal mixture 12N(−1.5,0.52)+12N(1.5,0.52)\frac12 N(-1.5, 0.5^2) + \frac12 N(1.5, 0.5^2) with n=200n = 200 (10 samples), hMISE=0.224h_{\mathrm{MISE}} = 0.224. The mean selected bandwidths were 0.579 (normal reference), 0.492 (robust rule), 0.220 (LSCV) and 0.259 (plug-in), and the MISE at the selected bandwidth was on average 4.97, 3.41, 1.12 and 1.05 times the smallest MISE. The rules oversmooth badly when the density is far from normal.

Known algorithms

  • Normal reference rule. Put the normal value R(f′′)=3/(8π σ5)R(f'') = 3/(8\sqrt\pi\,\sigma^5) into hAMISEh_{\mathrm{AMISE}}. For the Gaussian kernel this gives h=(4/(3n))1/5σ^≈1.06 σ^n−1/5h = (4/(3n))^{1/5}\hat\sigma \approx 1.06\,\hat\sigma n^{-1/5}. Silverman (1986) suggests 0.9min⁡(σ^,IQR/1.34) n−1/50.9 \min(\hat\sigma, \mathrm{IQR}/1.34)\,n^{-1/5}: the interquartile range of a normal density is 1.349σ1.349\sigma, so the minimum protects against heavy tails and outliers, and the factor 0.9 instead of 1.06 protects a little against bimodality. Cost O(n)O(n), with the quartiles by selection or O(nlog⁡n)O(n \log n) by sorting. The code checks both formulas.
  • Least squares cross-validation (LSCV). Since ISE(h)=R(f^h)−2∫f^hf+R(f)\mathrm{ISE}(h) = R(\hat f_h) - 2\int \hat f_h f + R(f) and the last term does not depend on hh, minimize
    LSCV(h)=R(f^h)−2n∑i=1nf^h,−i(Xi),\mathrm{LSCV}(h) = R(\hat f_h) - \frac2n\sum_{i=1}^n \hat f_{h,-i}(X_i),
    where f^h,−i\hat f_{h,-i} leaves out XiX_i. With the Gaussian kernel, ϕh∗ϕh=ϕh2\phi_h * \phi_h = \phi_{h\sqrt2} gives the closed form R(f^h)=n−2∑i,jϕh2(Xi−Xj)R(\hat f_h) = n^{-2}\sum_{i,j}\phi_{h\sqrt2}(X_i - X_j). Each value costs O(n2)O(n^2), or O(n+mlog⁡m)O(n + m\log m) with binning on mm grid points. LSCV can have several local minima, so the code evaluates it on a log-spaced grid and then refines the best grid point by golden section search. The tests compare the closed form with numerical integration of f^h2\hat f_h^2 and explicit leave-one-out sums.
  • Plug-in. Estimate ψ4=R(f′′)\psi_4 = R(f'') by the kernel estimate ψ^r(g)=n−2∑i,jLg(r)(Xi−Xj)\hat\psi_r(g) = n^{-2}\sum_{i,j} L_g^{(r)}(X_i - X_j) with a pilot bandwidth gg. The best gg for ψ^4\hat\psi_4 depends on ψ6\psi_6, whose best pilot depends on ψ8\psi_8, and so on. The two-stage direct plug-in of Wand and Jones stops this chain with a normal value for ψ8\psi_8, then estimates ψ6\psi_6 and ψ4\psi_4 in turn, each with its asymptotically optimal pilot g=(2L(r)(0)/(−μ2ψr+2n))1/(r+3)g = (2L^{(r)}(0)/(-\mu_2\psi_{r+2} n))^{1/(r+3)}, and returns h=(R(K)/(μ22ψ^4n))1/5h = (R(K)/(\mu_2^2\hat\psi_4 n))^{1/5}. The code uses the Gaussian kernel for LL and min⁡(σ^,IQR/1.349)\min(\hat\sigma, \mathrm{IQR}/1.349) for the normal scale. The tests check ψ^r\hat\psi_r against the identity ψ^r(g)=(−1)r/2∫(f^g/2(r/2))2\hat\psi_r(g) = (-1)^{r/2}\int (\hat f_{g/\sqrt2}^{(r/2)})^2, computed by quadrature. Cost O(n2)O(n^2), or O(n+mlog⁡m)O(n + m \log m) binned.
  • Solve-the-equation plug-in (Sheather and Jones 1991). Make the pilot bandwidth for ψ4\psi_4 a function of hh itself, g=γ(h)g = \gamma(h), through the ratio of the two optimal bandwidths, and solve h=(R(K)/(μ22ψ^4(γ(h)) n))1/5h = (R(K)/(\mu_2^2\hat\psi_4(\gamma(h))\,n))^{1/5} by a root finder. This is the most widely recommended general selector.
  • Biased cross-validation and smoothed cross-validation. Variants of LSCV that estimate R(f′′)R(f'') inside the cross-validation criterion, or smooth the criterion. They trade some bias for much less variance.
  • Likelihood cross-validation. Maximize ∑ilog⁡f^h,−i(Xi)\sum_i \log \hat f_{h,-i}(X_i). It targets the Kullback-Leibler loss and breaks down for heavy tails, where one isolated point forces a large hh.

Bounds

  • LSCV is unbiased up to a constant. E LSCV(h)=MISE(h)−R(f)\mathbb{E}\,\mathrm{LSCV}(h) = \mathrm{MISE}(h) - R(f), exactly, for every nn and hh. Proof: f^h,−i(Xi)\hat f_{h,-i}(X_i) is an estimate from n−1n - 1 points, which are independent of XiX_i, so E f^h,−i(Xi)=∫E[f^h,n−1(x)] f(x) dx=∫(Kh∗f)f\mathbb{E}\,\hat f_{h,-i}(X_i) = \int \mathbb{E}[\hat f_{h,n-1}(x)]\,f(x)\,dx = \int (K_h * f) f, and the mean of a kernel estimate does not depend on the sample size. So E LSCV(h)=E R(f^h)−2 E∫f^hf=MISE(h)−R(f)\mathbb{E}\,\mathrm{LSCV}(h) = \mathbb{E}\,R(\hat f_h) - 2\,\mathbb{E}\int \hat f_h f = \mathrm{MISE}(h) - R(f).
  • Rates of the selectors. Stone (1984) proved that LSCV is asymptotically optimal: ISE(h^)/min⁡hISE(h)→1\mathrm{ISE}(\hat h)/\min_h \mathrm{ISE}(h) \to 1 almost surely. Hall and Marron (1987) showed that its relative error is of order n−1/10n^{-1/10}, which is very slow. The Sheather-Jones plug-in has relative error of order n−5/14n^{-5/14}. These rates are cited, not proved here.
  • Rules are not consistent for the target. The normal reference bandwidth converges to the right value only if ff is normal. For other densities, h^/hAMISE\hat h/h_{\mathrm{AMISE}} converges to (R(f′′)/R(ϕσ′′))1/5(R(f'')/R(\phi_\sigma''))^{1/5}, which is different from 1, and for densities with several modes it is larger than 1: the rule oversmooths.
  • Upper bound in practice. Over all densities with a given variance σ2\sigma^2, the largest AMISE-optimal bandwidth is 3(R(K)/(35μ22n))1/5σ3(R(K)/(35\mu_2^2 n))^{1/5}\sigma, which is 1.144 σn−1/51.144\,\sigma n^{-1/5} for the Gaussian kernel, only 8 percent above the normal reference value (Terrell's maximal smoothing principle, 1990). So the normal reference bandwidth is a sensible upper end of a range of bandwidths to look at.
  • Cost. Rules cost O(n)O(n). Cross-validation and plug-in cost O(n2)O(n^2) for each evaluation exactly, or O(n+mlog⁡m)O(n + m\log m) with binning.

Reductions

  • Plug-in reduces to estimating a functional. Bandwidth selection by plug-in is the estimation of R(f′′)=ψ4R(f'') = \psi_4, the integrated squared second derivative. That problem has its own bandwidth, which is why the method has stages.
  • Cross-validation reduces to model selection. LSCV is leave-one-out cross-validation with the loss ∫f^2−2f^(X)\int \hat f^2 - 2\hat f(X), an unbiased estimate of the MISE up to a constant. Likelihood cross-validation is the same with the log loss, the density version of model selection by Kullback-Leibler divergence or the AIC.
  • Histograms. Choosing the bin width of a histogram is the same problem with a different bias: the best width is of order n−1/3n^{-1/3}, and rules such as 2 IQR n−1/32\,\mathrm{IQR}\,n^{-1/3} (Freedman and Diaconis) come from the same normal reference idea.
  • Smoothing in regression. The smoothing parameter of a smoothing spline, the span of LOESS and the bandwidth of kernel regression are chosen by the same tools: cross-validation, generalized cross-validation and plug-in.

Applications

  • Default plots. Every density plot in statistical software needs a bandwidth without user input. R's density uses the robust 0.9 rule by default and offers the Sheather-Jones selector.
  • Exploratory analysis. Use several bandwidths, such as the rule, the plug-in and half of the rule, to decide whether a second mode is real.
  • Smoothing in other methods. Mean shift clustering, kernel classifiers and density ratio estimates depend on the bandwidth in the same way, and use the same selectors.
  • Nonparametric regression. The bandwidth of a Nadaraya-Watson estimator or a local linear fit is chosen by leave-one-out prediction error or by a plug-in for the regression AMISE.

Code

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.

kde_bandwidth_selection.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/kde-bandwidth-selection/. The authors are listed in prov/677AW6.jsonl.
"""Bandwidth selectors for a Gaussian-kernel density estimate in one dimension.

normal_reference, silverman, lscv_bandwidth (least squares cross-validation)
and dpi_bandwidth (two-stage direct plug-in, Sheather-Jones type).
"""

import math

SQRTPI = math.sqrt(math.pi)
SQRT2PI = math.sqrt(2 * math.pi)
RK = 1 / (2 * SQRTPI)  # R(K) for the Gaussian kernel; mu2(K) = 1


def phi(u):
    return math.exp(-0.5 * u * u) / SQRT2PI


def sample_sd(data):
    n = len(data)
    m = sum(data) / n
    return math.sqrt(sum((x - m) ** 2 for x in data) / (n - 1))


def quantile(data, p):
    """Linear interpolation between order statistics at position (n-1)p."""
    s = sorted(data)
    t = (len(s) - 1) * p
    j = int(math.floor(t))
    if j + 1 >= len(s):
        return s[-1]
    return s[j] + (t - j) * (s[j + 1] - s[j])


def iqr(data):
    return quantile(data, 0.75) - quantile(data, 0.25)


def normal_reference(data):
    """AMISE-optimal h if f were normal: (4/(3n))^(1/5) sigma, about 1.06 sigma n^(-1/5)."""
    return (4 / (3 * len(data))) ** 0.2 * sample_sd(data)


def silverman(data):
    """0.9 min(sigma, IQR/1.34) n^(-1/5)."""
    return 0.9 * min(sample_sd(data), iqr(data) / 1.34) * len(data) ** -0.2


def lscv(h, data):
    """LSCV(h) = R(f_h) - (2/n) sum_i f_{h,-i}(X_i), closed form for the Gaussian kernel.

    R(f_h) = n^-2 sum_{i,j} phi_{h sqrt 2}(X_i - X_j) and
    f_{h,-i}(X_i) = (n-1)^-1 sum_{j != i} phi_h(X_i - X_j). O(n^2) time.
    """
    n = len(data)
    s2 = math.sqrt(2) * h
    r = n / (s2 * SQRT2PI)  # the diagonal terms i = j
    loo = 0.0
    for i in range(n):
        for j in range(i + 1, n):
            d = data[i] - data[j]
            r += 2 * phi(d / s2) / s2
            loo += 2 * phi(d / h) / h
    return r / (n * n) - 2 * loo / (n * (n - 1))


def golden_min(f, a, b, tol=1e-10):
    g = (math.sqrt(5) - 1) / 2
    c, d = b - g * (b - a), a + g * (b - a)
    fc, fd = f(c), f(d)
    while b - a > tol * (abs(a) + abs(b)):
        if fc < fd:
            b, d, fd = d, c, fc
            c = b - g * (b - a)
            fc = f(c)
        else:
            a, c, fc = c, d, fd
            d = a + g * (b - a)
            fd = f(d)
    return (a + b) / 2


def lscv_bandwidth(data, grid=60, lo=0.05, hi=2.0):
    """Minimise LSCV over a log-spaced grid of h/sigma, then refine by golden section.

    LSCV can have several local minima; the grid picks the smallest grid value
    and the refinement stays between its two neighbours.
    """
    s = sample_sd(data)
    hs = [s * lo * (hi / lo) ** (k / (grid - 1)) for k in range(grid)]
    vals = [lscv(h, data) for h in hs]
    k = min(range(grid), key=vals.__getitem__)
    a, b = hs[max(k - 1, 0)], hs[min(k + 1, grid - 1)]
    return golden_min(lambda h: lscv(h, data), a, b)


def hermite(r, u):
    """Probabilists' Hermite polynomial He_r(u)."""
    h0, h1 = 1.0, u
    if r == 0:
        return h0
    for k in range(1, r):
        h0, h1 = h1, u * h1 - k * h0
    return h1


def psi_hat(r, g, data):
    """psi_r = integral f^(r) f, estimated by n^-2 sum_{i,j} phi_g^(r)(X_i - X_j), r even.

    phi_g^(r)(x) = g^(-r-1) He_r(x/g) phi(x/g), as (-1)^r He_r = He_r for even r.
    """
    n = len(data)
    tot = n * hermite(r, 0.0) * phi(0.0)
    for i in range(n):
        for j in range(i + 1, n):
            u = (data[i] - data[j]) / g
            tot += 2 * hermite(r, u) * phi(u)
    return tot / (n * n * g ** (r + 1))


def psi_normal(r, sigma):
    """psi_r for N(mu, sigma^2): (-1)^(r/2) r! / ((2 sigma)^(r+1) (r/2)! sqrt(pi))."""
    return (-1) ** (r // 2) * math.factorial(r) / ((2 * sigma) ** (r + 1) * math.factorial(r // 2) * SQRTPI)


def dpi_bandwidth(data):
    """Two-stage direct plug-in (Wand and Jones 1995, Section 3.6.1), Gaussian kernel.

    psi_8 from a normal scale, then psi_6 and psi_4 by kernel estimates with
    their own AMSE-optimal pilot bandwidths, then h = (R(K)/(psi_4 n))^(1/5).
    """
    n = len(data)
    s = min(sample_sd(data), iqr(data) / 1.349)
    psi8 = psi_normal(8, s)
    # g = (-2 L^(r)(0) / (mu2 psi_{r+2} n))^(1/(r+3)); phi^(6)(0) = -15 phi(0), phi^(4)(0) = 3 phi(0).
    g1 = (2 * 15 * phi(0.0) / (psi8 * n)) ** (1 / 9)
    psi6 = psi_hat(6, g1, data)
    g2 = (-2 * 3 * phi(0.0) / (psi6 * n)) ** (1 / 7)
    psi4 = psi_hat(4, g2, data)
    return (RK / (psi4 * n)) ** 0.2


def kde(x, data, h):
    return sum(phi((x - xi) / h) for xi in data) / (len(data) * h)


def exact_mise_mixture(h, n, weights, means, sds):
    """Exact MISE of the Gaussian-kernel KDE for a normal mixture (Marron and Wand 1992)."""
    k = len(weights)

    def omega(a):
        return [[phi((means[l] - means[m]) / math.sqrt(a * h * h + sds[l] ** 2 + sds[m] ** 2))
                 / math.sqrt(a * h * h + sds[l] ** 2 + sds[m] ** 2) for m in range(k)] for l in range(k)]

    o2, o1, o0 = omega(2), omega(1), omega(0)
    quad = sum(weights[l] * weights[m] * ((1 - 1 / n) * o2[l][m] - 2 * o1[l][m] + o0[l][m])
               for l in range(k) for m in range(k))
    return RK / (n * h) + quad
test_kde_bandwidth_selection.py 122 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/kde-bandwidth-selection/. The authors are listed in prov/677AW6.jsonl.

import math
import random

from kde_bandwidth_selection import (
    RK, dpi_bandwidth, exact_mise_mixture, golden_min, hermite, iqr, kde, lscv,
    lscv_bandwidth, normal_reference, phi, psi_hat, psi_normal, sample_sd, silverman,
)

PAGE = [-1.9, -1.6, -1.5, -1.3, -1.2, -1.0, -0.8, 0.9, 1.1, 1.2, 1.4, 1.5, 1.7, 2.0]


def simpson(f, a, b, m):
    step = (b - a) / m
    s = f(a) + f(b)
    for k in range(1, m):
        s += (4 if k % 2 else 2) * f(a + k * step)
    return s * step / 3


def test_page_example() -> None:
    assert abs(sample_sd(PAGE) - 1.46056) < 1e-5
    assert abs(iqr(PAGE) - 2.625) < 1e-12
    assert abs(normal_reference(PAGE) - 0.9126) < 1e-4
    assert abs(silverman(PAGE) - 0.7754) < 1e-4
    assert abs(lscv_bandwidth(PAGE) - 0.4643) < 1e-4
    assert abs(dpi_bandwidth(PAGE) - 0.5365) < 1e-4


def test_rules_match_their_formulas() -> None:
    rng = random.Random(61)
    for _ in range(20):
        n = rng.randint(5, 60)
        d = [rng.gauss(3, 2) for _ in range(n)]
        s = sample_sd(d)
        assert abs(normal_reference(d) - (4 / 3) ** 0.2 * s * n ** -0.2) < 1e-12
        # The normal reference rule is Theorem 4 of the KDE page with R(f'') of N(0, s^2).
        rf2 = psi_normal(4, s)
        assert abs(normal_reference(d) - (RK / (rf2 * n)) ** 0.2) < 1e-12
        assert abs(silverman(d) - 0.9 * min(s, iqr(d) / 1.34) * n ** -0.2) < 1e-12
    # With one far outlier the IQR branch is used.
    d = [float(v) for v in range(20)] + [1000.0]
    assert iqr(d) / 1.34 < sample_sd(d)
    assert abs(silverman(d) - 0.9 * 10 / 1.34 * 21 ** -0.2) < 1e-12


def test_psi_normal_against_quadrature() -> None:
    # psi_r = integral f^(r) f, and f^(r)(x) = He_r(x) phi(x) for even r and sigma = 1.
    for r in (4, 6, 8):
        num = simpson(lambda x: hermite(r, x) * phi(x) ** 2, -12, 12, 4000)
        assert abs(num - psi_normal(r, 1.0)) < 1e-10
    assert abs(psi_normal(4, 1.0) - 3 / (8 * math.sqrt(math.pi))) < 1e-15


def test_lscv_closed_form_against_definition() -> None:
    rng = random.Random(62)
    d = [rng.gauss(0, 1) for _ in range(25)]
    for h in (0.15, 0.4, 0.9):
        a, b = min(d) - 10 * h, max(d) + 10 * h
        rf = simpson(lambda x: kde(x, d, h) ** 2, a, b, 6000)
        loo = sum(kde(d[i], d[:i] + d[i + 1:], h) for i in range(len(d)))
        assert abs(lscv(h, d) - (rf - 2 * loo / len(d))) < 1e-9


def test_psi_hat_against_quadrature() -> None:
    # n^-2 sum phi_g^(r)(X_i - X_j) = (-1)^(r/2) integral (f_a^(r/2))^2 with a = g / sqrt 2.
    rng = random.Random(63)
    d = [rng.gauss(0, 1) for _ in range(20)]
    for r, g in ((4, 0.5), (6, 0.7)):
        a, s = g / math.sqrt(2), r // 2

        def deriv(x):  # the s-th derivative of the estimate with bandwidth a
            return sum((-1) ** s * hermite(s, (x - xi) / a) * phi((x - xi) / a)
                       for xi in d) / (len(d) * a ** (s + 1))

        num = simpson(lambda x: deriv(x) ** 2, min(d) - 12 * a, max(d) + 12 * a, 6000)
        assert abs(psi_hat(r, g, d) - (-1) ** s * num) < 1e-8 * abs(num)


def test_lscv_bandwidth_is_the_grid_minimum() -> None:
    rng = random.Random(64)
    d = [rng.gauss(0, 1) for _ in range(30)] + [rng.gauss(4, 0.5) for _ in range(15)]
    h = lscv_bandwidth(d)
    s = sample_sd(d)
    best = min(lscv(s * (0.05 + k * 0.005), d) for k in range(391))
    assert lscv(h, d) <= best + 1e-12


def test_exact_mise_against_quadrature() -> None:
    w, mu, sd = [0.3, 0.7], [-1.0, 2.0], [0.6, 1.2]
    f_conv = lambda x, s2: sum(wl * phi((x - m) / math.sqrt(v + s2)) / math.sqrt(v + s2)
                               for wl, m, v in zip(w, mu, [t * t for t in sd]))
    for n, h in ((10, 0.5), (200, 0.3)):
        def mse(x):
            mean = f_conv(x, h * h)
            ek2 = f_conv(x, h * h / 2) / (2 * h * math.sqrt(math.pi))
            return (mean - f_conv(x, 0.0)) ** 2 + (ek2 - mean * mean) / n
        num = simpson(mse, -10, 12, 4000)
        assert abs(exact_mise_mixture(h, n, w, mu, sd) - num) < 1e-10


def test_selectors_on_normal_and_bimodal_data() -> None:
    # Measured behaviour for fixed seeds, not a guarantee.
    rng = random.Random(7)
    n = 300
    d = [rng.gauss(0, 1) for _ in range(n)]
    h_mise = golden_min(lambda h: exact_mise_mixture(h, n, [1], [0], [1]), 0.01, 3)
    assert abs(dpi_bandwidth(d) / h_mise - 1) < 0.1
    assert abs(normal_reference(d) / h_mise - 1) < 0.1
    # Separated bimodal: the normal reference rule oversmooths badly.
    w, mu, sd = [0.5, 0.5], [-1.5, 1.5], [0.5, 0.5]
    rng = random.Random(2)
    n = 200
    d = [rng.gauss(mu[c], sd[c]) for c in (rng.randrange(2) for _ in range(n))]
    h_mise = golden_min(lambda h: exact_mise_mixture(h, n, w, mu, sd), 0.01, 3)
    best = exact_mise_mixture(h_mise, n, w, mu, sd)
    ratio = lambda h: exact_mise_mixture(h, n, w, mu, sd) / best
    assert ratio(normal_reference(d)) > 3
    assert ratio(silverman(d)) > 2
    assert ratio(dpi_bandwidth(d)) < 1.3

References

  1. B. W. Silverman, Density Estimation for Statistics and Data Analysis, Chapman and Hall, 1986, Section 3.4 (the normal reference bandwidth 1.06 sigma n^(-1/5), the robust version with the interquartile range, and least squares and likelihood cross-validation)
  2. M. P. Wand and M. C. Jones, Kernel Smoothing, Chapman and Hall, 1995, Chapter 3 (bandwidth selection; the estimation of psi_r in Section 3.5 and the two-stage direct plug-in in Section 3.6.1)
  3. Mats Rudemo, Empirical choice of histograms and kernel density estimators, Scandinavian Journal of Statistics 9(2), 1982, pp. 65 to 78, The whole paper (least squares cross-validation)
  4. Adrian W. Bowman, An alternative method of cross-validation for the smoothing of density estimates, Biometrika 71(2), 1984, pp. 353 to 360 (least squares cross-validation)
  5. Charles J. Stone, An asymptotically optimal window selection rule for kernel density estimates, The Annals of Statistics 12(4), 1984, pp. 1285 to 1297 (the integrated squared error at the cross-validated bandwidth is asymptotically optimal)
  6. Peter Hall and J. S. Marron, Extent to which least-squares cross-validation minimises integrated square error in nonparametric density estimation, Probability Theory and Related Fields 74(4), 1987, pp. 567 to 581 (the relative error of the cross-validated bandwidth is of order n^(-1/10))
  7. S. J. Sheather and M. C. Jones, A reliable data-based bandwidth selection method for kernel density estimation, Journal of the Royal Statistical Society Series B 53(3), 1991, pp. 683 to 690 (the solve-the-equation plug-in selector and its relative rate n^(-5/14))
  8. J. S. Marron and M. P. Wand, Exact mean integrated squared error, The Annals of Statistics 20(2), 1992, pp. 712 to 736 (the exact MISE for normal mixtures with a Gaussian kernel)
  9. M. C. Jones, J. S. Marron and S. J. Sheather, A brief survey of bandwidth selection for density estimation, Journal of the American Statistical Association 91(433), 1996, pp. 401 to 407 (comparison of rules, cross-validation and plug-in selectors)

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 proofH0 no proof
  • add a proof in proofs/ (06.5)
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 known algorithm
  • a contract.yaml