Kernel density estimation
| Problem | Estimate a smooth probability density from a sample, without assuming a parametric family |
| Devised by | Murray Rosenblatt (1956) and Emanuel Parzen (1962); David Scott (1979) and Bernard Silverman (1986), bandwidth rules of thumb; Simon Sheather and Chris Jones (1991), plug-in bandwidths |
| Accuracy | Mean integrated squared error with a well-chosen bandwidth; matches scipy.stats.gaussian_kde to rounding |
| Cost | per evaluation point |
| Read first | Descriptive statistics, Background: bias and variance |
| API | GaussianKde (new, pdf, cdf, resample, bandwidth), Bandwidth (Scott, Silverman, Fixed) |
Overview
A histogram estimates a density, but depends on the arbitrary placement of its bins and is discontinuous. A kernel density estimate places a small smooth bump, the kernel, at each observation and adds them up:
With the Gaussian kernel the estimate is a mixture of normal densities of standard deviation centred at the data. The kernel shape matters little; the bandwidth matters a great deal.
Where it is used
A density estimate shows the shape of the data without assuming a formula.
- Exploration. Revealing several peaks (modes) in a histogram-like plot of measurements, such as particle sizes or response times.
- Anomaly detection. Points in regions of low estimated density are unusual.
- Simulation. Sampling new points from a smoothed version of observed data.
- Choosing the bandwidth. Too narrow gives noise, too wide hides structure, and rules of thumb pick a sensible value.
History
Murray Rosenblatt (1956) and Emanuel Parzen (1962) introduced kernel estimators and proved their consistency, and the method is sometimes called the Parzen-Rosenblatt window. David Scott (1979) derived normal-reference rules for histogram bin widths and kernel bandwidths; Bernard Silverman’s monograph Density Estimation for Statistics and Data Analysis (1986) made the method standard and gave the robust rule of thumb that bears his name. Simon Sheather and Chris Jones (1991) developed plug-in bandwidths that estimate the curvature of the density from the data.
The idea
Bias, variance and the bandwidth
This is the bias-variance trade-off in a density estimate.
The estimate places a small bump, the kernel, of width on each observation and adds the bumps up. Everything depends on the bandwidth , and the two ways of getting it wrong have names.
- If is too small, each bump is narrow and the estimate is a row of spikes. It follows the particular sample closely and would look quite different for another sample. This is variance.
- If is too large, the bumps are so wide that real features, peaks and valleys, are smeared out. The estimate would be much the same for any sample, but systematically wrong. This is bias.
Both can be quantified. For a twice-differentiable density and the Gaussian kernel, at a point :
The bias formula says that smoothing lowers peaks (where ) and fills valleys (where ), more so the sharper they are. The variance formula says that the noise falls as , roughly the number of observations inside one kernel width, grows.
The total error at a point is the squared bias plus the variance. Integrating over (the variance term integrates to because ) gives the asymptotic mean integrated squared error
The first term grows with and the second falls, so there is a best bandwidth, found by setting the derivative to zero:
This is the same kind of balance as the choice of step in numerical differentiation. Two consequences follow. The best bandwidth shrinks only slowly as the sample grows, like . And substituting back gives an error of order , which is slower than the of a parametric fit: that is the price of assuming nothing about the shape of the density.
Rules of thumb
The formula for cannot be used directly, because it contains , a property of the unknown density being estimated. Normal-reference rules break the circle by pretending, for this one purpose, that the density is normal with the sample’s standard deviation . For a normal density the integral can be done exactly, and the formula gives . The library offers:
- Scott: , the factor used by
scipy.stats.gaussian_kde(slightly smaller than 1.06). - Silverman: , which shrinks the bandwidth for heavy tails and resists outliers.
- Fixed: any given .
The assumption has a cost. A density with two or more peaks has much more curvature than a normal density of the same overall spread, so its is larger and its best bandwidth smaller. Both rules are tuned to unimodal, normal-like data and oversmooth multimodal densities:
Figure 10.3. Kernel density estimates.
| density | Scott | Silverman | best fixed | |
|---|---|---|---|---|
| normal | 50 | 1.12e-2 | 1.36e-2 | 9.36e-3 () |
| normal | 500 | 1.52e-3 | 1.59e-3 | 1.47e-3 () |
| normal | 5000 | 3.18e-4 | 3.31e-4 | 3.16e-4 () |
| bimodal mixture | 50 | 2.53e-2 | 2.22e-2 | 1.48e-2 () |
| bimodal mixture | 500 | 8.11e-3 | 6.41e-3 | 2.81e-3 () |
| bimodal mixture | 5000 | 1.96e-3 | 1.44e-3 | 4.88e-4 () |
Mean integrated squared error over 20 samples.
For normal data Scott’s rule is within 20% of the best fixed bandwidth’s error at and within a few per cent at larger sizes. For the bimodal mixture both rules choose bandwidths about twice too large, and by their error is three to four times the best achievable; Silverman’s rule helps a little. Plug-in and cross-validation bandwidths address this.
The distribution function and resampling
Integrating the kernels gives the estimated CDF . Sampling from is easy: pick an observation at random and add noise, the smoothed bootstrap. The samples have variance , slightly inflated.
Algorithm
Set-up. Compute the bandwidth from the chosen rule: the standard deviation of the data for Scott’s rule; the standard deviation and the interquartile range for Silverman’s; or the value given.
pdf(x): add up the kernel over all the data points and divide by
.
cdf(x): average the normal distribution function over the data
points.
resample: choose one of the data points uniformly at random and add a normal deviate with
standard deviation .
Each evaluation of the density or the distribution function visits every data point, . Evaluating on a grid of points therefore costs ; for very large samples, binning the data and convolving with the kernel by FFT reduces this to about , which the library does not do.
Implementation
pub fn new(data: &[f64], bandwidth: Bandwidth) -> Result<Self, ErrorsJSL> {
if data.len() < 2 || data.iter().any(|v| !v.is_finite()) {
return Err(ErrorsJSL::InvalidInputRange("Need at least two finite observations."));
}
let n = data.len() as f64;
let h = match bandwidth {
Bandwidth::Scott => standard_deviation(data, 1)? * n.powf(-0.2),
Bandwidth::Silverman => {
let sigma = standard_deviation(data, 1)?;
let spread = interquartile_range(data)? / 1.34;
0.9 * if spread > 0.0 { sigma.min(spread) } else { sigma } * n.powf(-0.2)
}
Bandwidth::Fixed(h) => h,
};
if !(h > 0.0) {
return Err(ErrorsJSL::InvalidInputRange("The bandwidth must be positive (is the sample constant?)."));
}
Ok(GaussianKde { data: data.to_vec(), bandwidth: h })
}
- Each evaluation costs ; for many points on a grid, binning the data and convolving with an FFT reduces the cost to .
- A constant sample has zero bandwidth under the rules and gives an error.
In practice
//! Estimate the density of eruption gaps of a geyser-like bimodal process.
use lib_jsl_random::uniform_generator::UniformRNG;
use lib_jsl_random::distributions::gaussian_distribution_box_muller;
use lib_jsl_statistics::kernel_density::{Bandwidth, GaussianKde};
fn main() {
let mut rng = UniformRNG::from_seed(1);
// Waiting times in minutes: short gaps near 55, long gaps near 80.
let data: Vec<f64> = (0..300)
.map(|i| if i % 3 == 0 { gaussian_distribution_box_muller(&mut rng, 55.0, 6.0).0 } else { gaussian_distribution_box_muller(&mut rng, 80.0, 5.0).0 })
.collect();
for rule in [Bandwidth::Scott, Bandwidth::Silverman, Bandwidth::Fixed(2.0)] {
let kde = GaussianKde::new(&data, rule).unwrap();
let curve: Vec<String> = (40..=95).step_by(5).map(|x| format!("{:.3}", kde.pdf(x as f64))).collect();
println!("{rule:?} (h = {:.2}): {}", kde.bandwidth(), curve.join(" "));
}
let kde = GaussianKde::new(&data, Bandwidth::Silverman).unwrap();
println!("P(gap < 65) = {:.3}", kde.cdf(65.0));
let draws = kde.resample(5, &mut rng);
println!("five simulated gaps: {draws:.1?}");
}
Scott (h = 4.31): 0.003 0.008 0.014 0.017 0.013 0.009 0.014 0.031 0.040 0.031 0.014 0.004
Silverman (h = 3.88): 0.003 0.008 0.014 0.018 0.013 0.008 0.014 0.031 0.042 0.031 0.013 0.003
Fixed(2.0) (h = 2.00): 0.002 0.008 0.014 0.022 0.012 0.005 0.009 0.033 0.048 0.033 0.010 0.002
P(gap < 65) = 0.308
five simulated gaps: [79.5, 83.1, 46.8, 86.1, 73.5]
The rules blur the valley between the two modes at 55 and 80 minutes; a smaller fixed bandwidth shows it more clearly.
Strengths
- No assumption about the shape of the density; a smooth estimate with a CDF and a sampler.
- Bandwidth rules match SciPy.
Weaknesses
- One dimension only, and one kernel.
- Rules of thumb oversmooth multimodal densities; no plug-in or cross-validated bandwidth.
- Bias at boundaries: for data on the estimate leaks mass below zero.
Exercises
- Show that integrates to 1 and is non-negative for any non-negative kernel.
- Derive the bias and variance to leading order.
- Minimise the AMISE to find , and evaluate it for a normal density to obtain the constant 1.06.
- Implement least-squares cross-validation for and compare it with the rules on the bimodal mixture.
- Estimate the density of an exponential sample and correct the boundary bias by reflecting the data about 0.
Hints and answers
- by substituting ; non-negativity follows from .
- for (the entry takes ). The variance is .
- with . Setting its derivative to zero gives ; for a normal density and Gaussian kernel this is .
- Minimise over (leaving each point out when evaluating); on the bimodal mixture it typically selects a smaller bandwidth than the normal-reference rules, which oversmooth bimodal data.
- For an exponential sample, the estimate leaks mass to and underestimates the density near 0. Reflecting means adding the estimate of the reflected data to the estimate on , which cancels the boundary bias.
Further reading
- B. W. Silverman, Density Estimation for Statistics and Data Analysis, Chapman and Hall, 1986.
- D. W. Scott, Multivariate Density Estimation, 2nd ed., Wiley, 2015.
- M. P. Wand and M. C. Jones, Kernel Smoothing, Chapman and Hall, 1995.
- S. J. Sheather and M. C. Jones, “A reliable data-based bandwidth selection method for kernel density estimation”, Journal of the Royal Statistical Society B 53 (1991) 683–690.