Kernel Density Estimation
Bandwidths, bias–variance and convergence rates.
Rosenblatt (1956) and Parzen (1962) introduced the kernel density estimator and the first theory of its accuracy, and the questions they raised still organize the field. How fast can any estimator converge? How should the bandwidth be chosen from the data? What goes wrong at the edges of the data? This lesson proves the rates, shows that no estimator can beat them, and turns the same machinery into kernel regression.
What you’ll learn
- State and prove the bias and variance expansions of the -dimensional kernel density estimator, and derive the AMISE-optimal bandwidth , the rate and the efficiencies of common kernels.
- Prove by a two-point argument that is a lower bound for estimating a -smooth density at a point, and explain what higher-order kernels gain and lose.
- Derive Silverman's rule and the least-squares cross-validation criterion, and explain why data-driven bandwidths converge slowly.
- Analyze boundary bias and its corrections, and derive the Nadaraya–Watson regression estimator together with its design bias.
The bias–variance expansion in d dimensions
Let be i.i.d. with density on . The kernel density estimator with smoothing kernel and bandwidth is , where . Assume is bounded, integrates to 1, is symmetric, , and satisfies and ; product kernels and radially symmetric kernels qualify. Write for any square-integrable .
Mean. The estimator averages i.i.d. terms, so its mean is that of one term. Substitute :
Bias. Expand by Taylor's theorem with integral remainder. The linear term integrates to zero by symmetry; the quadratic term converges by continuity of and dominated convergence, and :
Variance. One term's second moment carries the factor , while its squared mean is :
Integrate and optimize. The integrated variance is exactly , and the integrated squared bias is by the same expansion, using continuity of translation in . Minimize : at the minimum , so the variance term equals times the squared-bias term.
In one dimension the kernel enters the optimal error only through , as , and does not change when is rescaled. Epanechnikov (1969) showed that among nonnegative kernels it is minimized by the parabola . To match a given error, the sample size must be proportional to , which defines each kernel's efficiency:
| Kernel | Efficiency | |||
|---|---|---|---|---|
| Epanechnikov | on | 1 | ||
| Biweight | on | 0.994 | ||
| Triangular | on | 0.986 | ||
| Gaussian | 0.951 | |||
| Uniform | on | 0.930 |
An Epanechnikov-kernel KDE at its best bandwidth uses 1,000 observations. Asymptotically, how many observations does a Gaussian-kernel KDE need, also at its best bandwidth, to match its mean integrated squared error?
Show the answer
1051 observations
Sample size scales with : for the Gaussian and for the Epanechnikov kernel. The ratio is , so about 1,051 observations. Five percent is real but small, which is why the Gaussian kernel's smoothness usually wins.
No estimator does better
Is a weakness of kernels, or of the problem? Fix a point and a smoothness class. For , let be the largest integer strictly below , and let contain the densities on whose partial derivatives of order exist and are Hölder continuous with exponent and constant . Densities whose second derivatives are bounded by belong to .
Take with near , and a smooth bump supported in the unit ball with and . Perturb at scale . For a small fixed , is a density (it integrates to 1 because , and stays positive because near ), and it lies in : the bump's derivatives of order have Hölder constant proportional to , whatever is.
The two hypotheses are hard to tell apart. Bound the KL divergence between the laws of the samples by the divergence; the bump has squared integral :
Choose . The divergence stays below a constant, so by Pinsker's inequality the total-variation distance between the two laws stays below some . Le Cam's two-point argument then says any estimator misses by at least half the gap, , with probability at least under one of the two densities:
The proof shows where the rate comes from: a bump of height and width is invisible to samples once . For this is exactly the KDE's , so the kernel estimator is rate-optimal, and the curse of dimensionality belongs to the problem, not to the method. Smoother densities allow faster rates, but only kernels of higher order exploit them. A kernel whose second moment vanishes must take negative values, so the estimate can dip below zero; truncating at zero and renormalizing repairs that, and in practice the gains appear only at large .
A density on is known to be Hölder smooth with . What is the best possible rate for the mean squared error of estimating it at a point?
Show the answer
B.
. A kernel of order 3 with attains it. A nonnegative kernel stays at , because its bias is of order however smooth is.
Choosing the bandwidth from the data
The optimal involves the unknown curvature . Bandwidth selectors either plug in a guess for it, estimate it, or bypass it by estimating the error directly. Take .
Pretend is , whose curvature functional is
The Gaussian kernel has and . Substitute into :
Replace by an estimate. Data with two separated peaks inflate the sample standard deviation and the rule then oversmooths, so Silverman (1986) recommends a robust version: a normal distribution's interquartile range is , and the factor 0.9 leans toward less smoothing.
Least-squares cross-validation (Rudemo, 1982; Bowman, 1984) estimates the integrated squared error of the estimate in hand. Expand . The last term does not involve , the first is computable, and the middle one is estimated with leave-one-out estimates that never see :
where is the estimate from points. So is unbiased for the MISE, up to the difference between and points. Unbiased does not mean precise: the selected bandwidth is so variable that its relative error shrinks only like (Hall & Marron, 1987), and in some samples it badly undersmooths.
Plug-in selectors estimate the functional itself, with a pilot bandwidth tuned for that purpose, and then solve . The solve-the-equation method of Sheather & Jones (1991) is the standard choice, and it is reliably good on smooth densities. Likelihood cross-validation maximizes , the held-out log-likelihood of the Descent lesson, and targets the KL divergence instead of squared error; an isolated point drives its term toward unless grows, so heavy tails make it oversmooth everywhere. In dimensions the bandwidth becomes a positive definite matrix , with , and the same three ideas extend with more to estimate.
import numpy as np
from scipy.stats import norm
def lscv(h, x):
"""Least-squares cross-validation score of a 1-D Gaussian KDE."""
n = len(x)
D = x[:, None] - x[None, :] # all pairwise differences
int_p2 = norm.pdf(D, scale=np.sqrt(2) * h).sum() / n**2 # exact integral of p_hat^2
K = norm.pdf(D, scale=h)
loo = (K.sum(axis=1) - np.diag(K)) / (n - 1) # leave-one-out p_hat at each x_i
return int_p2 - 2 * loo.mean()
sd = x.std()
iqr = np.subtract(*np.percentile(x, [75, 25]))
grid = np.geomspace(0.02, 2.0, 60) * sd
h_cv = grid[np.argmin([lscv(h, x) for h in grid])]
h_rot = 0.9 * min(sd, iqr / 1.34) * len(x) ** (-1 / 5) # Silverman's robust ruleWith a Gaussian kernel, is exact: two Gaussian bumps of width overlap like one bump of width . This direct version costs per bandwidth; binning the data and using the fast Fourier transform make it nearly linear.
Boundaries and kernel regression
Let live on with , and let be symmetric. At only the half of each bump that falls inside the support collects mass:
For supported on and with , the limit is , so the estimate is inconsistent within one bandwidth of the edge; even after dividing by , the bias there is of order , not , because the truncated kernel is no longer symmetric. Reflecting the data restores consistency; its bias near zero stays of order unless . Boundary kernels and transformations (such as for positive data) are the other standard fixes.
The regression function is a ratio of densities:
Estimate with a product kernel . A symmetric has mean zero, so integrating against returns exactly , and integrating out leaves the KDE of . The ratio is the estimator of Nadaraya (1964) and Watson (1964):
For a random design with density for and conditional variance , expansions like those of the first step give, at an interior point with , as and :
The second bias term, the design bias, appears wherever slopes and changes, for instance near the edge of the data. A local linear fit, which solves a kernel-weighted least-squares problem for an intercept and a slope at each , removes it and corrects the boundary bias automatically, with the same asymptotic variance at interior points. The rates match the density case: mean squared error of order , which Stone (1980) showed is optimal for twice-differentiable regression functions. Nearest-neighbor regression is the same idea with an adaptive window, and the widget tests the bandwidth rate on it.
Key takeaways
- For a symmetric second-order kernel and a twice-differentiable density: bias , variance , best bandwidth and . At the optimum the variance term is times the squared-bias term.
- The rate is minimax. A bump of height and width is undetectable once , so no estimator beats ; kernels of higher order reach it for smoother densities, at the price of negative values.
- The kernel matters little (the Gaussian is 95% efficient); the bandwidth matters a lot. Silverman's rule is optimal for Gaussian data; least-squares cross-validation is unbiased but its bandwidth converges at the relative rate ; plug-in selectors are more stable.
- Symmetric kernels are inconsistent at boundaries, with ; reflection, boundary kernels and transformations fix it.
- Nadaraya–Watson regression is a ratio of kernel estimates. Its design bias disappears with local linear fitting, and its rates match the density case.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
With a nonnegative second-order kernel in dimensions, how does the AMISE-optimal bandwidth scale with the sample size ?
- Like , in every dimension
- Like
- Like
- Like
Show the answer
B. Like
Balancing against gives . In one dimension this is ; in ten it is , so bandwidths shrink very slowly in high dimension.
Least-squares cross-validation minimizes . What goes wrong if you replace the leave-one-out terms by ?
- Nothing: the two versions have the same minimizer
- The criterion becomes unbiased for the log-likelihood instead
- Each includes its own bump , which grows without bound as , so the criterion is minimized by
- diverges
Show the answer
C. Each includes its own bump , which grows without bound as , so the criterion is minimized by
The middle term must estimate with points the estimate has not seen. With in-sample points the self-term dominates for small and drags the criterion to ; leaving each point out makes the term unbiased for the cross term (with points).
A density on has . A KDE with a symmetric kernel, and , is evaluated at . What does its expectation converge to?
- 2
- 0
- 4
- 1
Show the answer
D. 1
Only the half of each bump that lies inside collects mass near , so . Reflecting the data about doubles it back.
Which change removes the Nadaraya–Watson design-bias term ?
- Using the Epanechnikov kernel
- Fitting a local line instead of a local constant at each
- Doubling the bandwidth
- Standardizing the response
Show the answer
B. Fitting a local line instead of a local constant at each
A local linear fit uses the slope at , so an uneven design density no longer tilts the local average. It also corrects the boundary bias automatically, with the same variance order.
Further reading
- M. Rosenblatt, "Remarks on some nonparametric estimates of a density function," Annals of Mathematical Statistics 27(3), 832–837 (1956).
- E. Parzen, "On estimation of a probability density function and mode," Annals of Mathematical Statistics 33(3), 1065–1076 (1962).
- M. P. Wand & M. C. Jones, Kernel Smoothing (Chapman & Hall, 1995).
- A. B. Tsybakov, Introduction to Nonparametric Estimation (Springer, 2009).
- S. J. Sheather & M. C. Jones, "A reliable data-based bandwidth selection method for kernel density estimation," Journal of the Royal Statistical Society B 53(3), 683–690 (1991).