Kernel density estimation
Estimate a smooth probability density from samples by summing kernels; choose the bandwidth well.
Animated explanation
The idea
A histogram estimates a distribution by counting points in bins, but the picture changes with the bin width and where the bins start, and it is blocky. Kernel density estimation fixes both: put a small smooth bump (a kernel, usually a Gaussian) on top of every data point and add the bumps up. Where points crowd together the bumps pile up into a hill.
The width of each bump, the bandwidth , is the one decision that matters. Too narrow and the estimate is a row of spikes; too wide and real features blur away. KDE gives you a smooth density for visualising distributions, for anomaly scores (low density = unusual), for sampling, and as the engine inside mean shift.
Bandwidth selection
Rules of thumb (Scott's, Silverman's) work for roughly bell-shaped data. For multi-modal data, choose by cross-validated log-likelihood: leave points out, evaluate the density there, keep the that predicts held-out points best. The kernel shape matters far less than .
Limits
Evaluating the density costs per query (tree methods help). In more than a handful of dimensions, KDE needs exponentially more data (the curse of dimensionality), so for high-dimensional densities use GMMs, normalising flows or other parametric models.
The algorithm, step by step
- 1Choose a kernel K (Gaussian) and bandwidth h (rule of thumb or cross-validation).
- 2For a query x, compute for every training point.
- 3Average and divide by h (or by in d dimensions).
- 4Use the density for plots, anomaly scores (low density), or sampling (pick a point, add kernel noise).
The maths
Estimator
Gaussian kernel
Silverman's rule
Bias–variance in h
Strengths and weaknesses
Strengths
- Smooth, assumption-light density estimate
- One parameter (h) with good selection methods
- Useful for visualisation, anomaly detection and sampling
Weaknesses
- Bandwidth choice drives the result
- O(n) per query; whole dataset must be stored
- Poor in high dimensions
Reach for it when…
Check your understanding
Lambdian Lab
KDE and bandwidth by cross-validation
Gaussian KDE in any dimension with a scalar bandwidth h.
- log_density(X_train, X_query, h): log of the estimated density at each query point (use log-sum-exp for stability).
- silverman(x): Silverman's rule for 1-D data (std with ddof=1).
- best_bandwidth(X, hs, k, seed): k-fold cross-validated total log-likelihood; return the best h.