Algorithm Search⌘K

Algorithmcore

Kernel density estimation

Also called Parzen-Rosenblatt window method, KDE.

Estimates a density by averaging a kernel, such as a Gaussian bump, centred at each data point. The bandwidth trades bias against variance.

Time
O(n q) worstO(n + m log m) binned
Space
O(m) 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
deterministicexactintegrates to onenonnegativenot randomized
Origin
Murray Rosenblatt, Emanuel Parzen, V. A. Epanechnikov, Bernard W. Silverman, 1956

Kernel density estimation (KDE) estimates the probability density of a sample without a model for its shape. Put a small bump, the kernel, on each data point, and average the bumps. The width of the bumps is the bandwidth hh. It is the one choice that matters: a small hh follows the noise of the sample, and a large hh smooths away real features. The estimate at a point costs O(n)O(n). On a grid of mm points, linear binning and the FFT give the whole curve in O(n+mlog⁡m)O(n + m \log m) time.

In plain words

A histogram counts points in fixed bins, so its shape depends on where the bins start. Kernel density estimation removes the bins. Each point spreads one unit of probability around itself as a smooth hump, for example a bell curve. The estimate at any place is the total height of the humps there, divided by the number of points. Where points are close together, many humps overlap and the estimate is high.

The width of the humps is the main choice. Narrow humps give a spiky curve with a peak at every point. Wide humps give a flat curve that can hide two separate groups. The right width shrinks slowly as the sample grows.

The problem

The input is a sample X1,…,XnX_1, \ldots, X_n from an unknown density ff on the real line, a kernel KK and a bandwidth h>0h > 0. The kernel is a symmetric density, usually the Gaussian K(u)=e−u2/2/2πK(u) = e^{-u^2/2}/\sqrt{2\pi} or the Epanechnikov kernel K(u)=34(1−u2)K(u) = \frac34(1 - u^2) on [−1,1][-1, 1]. The output is the function

f^h(x)=1nh∑i=1nK ⁣(x−Xih),\hat f_h(x) = \frac{1}{nh}\sum_{i=1}^n K\!\left(\frac{x - X_i}{h}\right),

evaluated at the points where it is wanted, often on an equally spaced grid. The quality is measured by the mean integrated squared error MISE(h)=E∫(f^h−f)2\mathrm{MISE}(h) = \mathbb{E}\int (\hat f_h - f)^2. How to choose hh from the data is the separate problem of bandwidth selection.

The algorithm

Line L1 is the definition. For many points on a grid, the binned version replaces the data by grid counts and turns the sum into a discrete convolution, which the FFT computes for all grid points at once.

  1. KDE(x, X_1..X_n, h)
  2. 1return (1/(n h)) · Σ_i K((x − X_i)/h)
  3. KDE-ON-GRID(X_1..X_n, h, lo, hi, m) ▷ binned, with the FFT
  4. 2δ ← (hi − lo)/(m − 1); c ← linear binning of the X_i onto the grid g_k = lo + kδ
  5. 3κ_l ← K(lδ/h)/(n h) for −L ≤ l ≤ L, with L δ at least the reach of the kernel
  6. 4pad c and κ with zeros to a length N ≥ m + 2L, and take their FFTs
  7. 5s ← the inverse FFT of the product of the two transforms
  8. 6return s_{k+L} for k = 0, ..., m − 1 ▷ the estimate at g_k

Linear binning gives a point at gj+tδg_j + t\delta, with 0≤t<10 \le t < 1, the weight 1−t1 - t at gjg_j and tt at gj+1g_{j+1}. The binned estimate at gkg_k is ∑jcjκk−j\sum_j c_j \kappa_{k-j}, a convolution of the counts with the sampled kernel. The zero padding makes the cyclic convolution of the FFT equal to the ordinary one. The Gaussian kernel is cut at 8h8h, where it is below 5.1×10−155.1 \times 10^{-15}.

Example

Five points 1,2,4,7,81, 2, 4, 7, 8, the Epanechnikov kernel and h=2h = 2. Each point adds 110⋅34(1−((x−Xi)/2)2)\frac{1}{10}\cdot\frac34\big(1 - ((x - X_i)/2)^2\big) when ∣x−Xi∣<2|x - X_i| < 2. At x=2x = 2, the point 1 gives u=1/2u = 1/2 and K=9/16K = 9/16; the point 2 gives u=0u = 0 and K=3/4K = 3/4; the point 4 is at distance 2, at the edge, and adds 0. So f^(2)=110(916+34)=21160\hat f(2) = \frac1{10}(\frac{9}{16} + \frac34) = \frac{21}{160}.

xx 0 1 2 3 4 5 5.5 6 7 7.5 8 9 10
f^(x)\hat f(x) 9/160 21/160 21/160 9/80 3/40 9/160 21/320 9/160 21/160 9/64 21/160 9/160 0
decimal 0.056 0.131 0.131 0.113 0.075 0.056 0.066 0.056 0.131 0.141 0.131 0.056 0

The estimate has two humps, over {1,2}\{1, 2\} and over {7,8}\{7, 8\}, and a dip near 5. The isolated point 4 makes the dip shallow. It is zero outside (−1,10)(-1, 10), and its integral is exactly 1. With h=1h = 1 the curve has three humps, at 1.5, 4 and 7.5. With h=6h = 6 the two groups merge into one hump with its top near 4.5. The test file checks these values in exact arithmetic.

Correctness

The estimate is a density: each scaled kernel Kh(x−Xi)=K((x−Xi)/h)/hK_h(x - X_i) = K((x - X_i)/h)/h has integral 1, and the estimate is their mean. If f′′f'' is bounded and continuous, a Taylor expansion inside E f^h(x)=∫K(u)f(x−hu) du\mathbb{E}\,\hat f_h(x) = \int K(u) f(x - hu)\,du gives the bias and the variance:

E f^h(x)−f(x)=h22μ2f′′(x)+o(h2),Var⁡f^h(x)=R(K)f(x)nh+o ⁣(1nh),\mathbb{E}\,\hat f_h(x) - f(x) = \frac{h^2}{2}\mu_2 f''(x) + o(h^2), \qquad \operatorname{Var}\hat f_h(x) = \frac{R(K) f(x)}{nh} + o\!\left(\frac1{nh}\right),

where μ2=∫u2K\mu_2 = \int u^2 K and R(K)=∫K2R(K) = \int K^2. Integrated over xx, they give

AMISE(h)=h44μ22R(f′′)+R(K)nh,\mathrm{AMISE}(h) = \frac{h^4}{4}\mu_2^2 R(f'') + \frac{R(K)}{nh},

which is strictly convex in hh and has its minimum at

h∗=(R(K)μ22R(f′′) n)1/5,AMISE(h∗)=54(μ22R(K)4R(f′′))1/5n−4/5.h^* = \left(\frac{R(K)}{\mu_2^2 R(f'')\,n}\right)^{1/5}, \qquad \mathrm{AMISE}(h^*) = \frac54\left(\mu_2^2 R(K)^4 R(f'')\right)^{1/5} n^{-4/5}.

Any bandwidth of a different order than n−1/5n^{-1/5} gives a larger order of error. For the binned estimate, the FFT computes the binned sum exactly, and linear binning changes the estimate by at most δ2sup⁡∣K′′∣/(8h3)\delta^2 \sup|K''|/(8h^3), since it replaces each kernel value by its linear interpolation between grid points. The full proofs are below; the step that integrates the pointwise remainders is quoted from Wand and Jones.

Proof: The kernel estimate is a density, its bias and variance expansions, the AMISE-optimal bandwidth, and the error of the binned FFT estimatefull

Setting. X1,…,XnX_1, \ldots, X_n are independent with density ff on R\mathbb{R}. The kernel KK is a symmetric function with ∫K=1\int K = 1, ∫u2∣K(u)∣ du<∞\int u^2 |K(u)|\,du < \infty and ∫K2<∞\int K^2 < \infty. Write μ2=∫u2K(u) du\mu_2 = \int u^2 K(u)\,du, R(g)=∫g(u)2 duR(g) = \int g(u)^2\,du, Kh(t)=K(t/h)/hK_h(t) = K(t/h)/h, and

f^h(x)=1nh∑i=1nK ⁣(x−Xih)=1n∑i=1nKh(x−Xi).\hat f_h(x) = \frac{1}{nh}\sum_{i=1}^n K\!\left(\frac{x - X_i}{h}\right) = \frac1n \sum_{i=1}^n K_h(x - X_i).

Part 1. The estimate is a density

Lemma 1. ∫f^h(x) dx=1\int \hat f_h(x)\,dx = 1. If K≥0K \ge 0, then f^h≥0\hat f_h \ge 0, so f^h\hat f_h is a probability density.

Proof. For each ii, the substitution u=(x−Xi)/hu = (x - X_i)/h gives ∫Kh(x−Xi) dx=∫K(u) du=1\int K_h(x - X_i)\,dx = \int K(u)\,du = 1. The estimate is the mean of nn such functions. A sum of non-negative terms is non-negative. □\square

The test file checks Lemma 1 without rounding for the Epanechnikov kernel. Between two consecutive points of the set {Xi±h}\{X_i \pm h\}, the estimate is a polynomial of degree at most 2, and Simpson's rule is exact for such polynomials. So Simpson's rule on each piece, in exact rational arithmetic, must give exactly 1.

Part 2. Bias and variance at a point

Lemma 2 (bias). E f^h(x)=∫K(u) f(x−hu) du\mathbb{E}\,\hat f_h(x) = \int K(u)\,f(x - hu)\,du. If f′′f'' is bounded and continuous at xx, then as h→0h \to 0,

E f^h(x)−f(x)=h22 μ2 f′′(x)+o(h2).\mathbb{E}\,\hat f_h(x) - f(x) = \frac{h^2}{2}\,\mu_2\, f''(x) + o(h^2).

Proof. The terms are identically distributed, so E f^h(x)=E Kh(x−X1)=∫Kh(x−t)f(t) dt\mathbb{E}\,\hat f_h(x) = \mathbb{E}\,K_h(x - X_1) = \int K_h(x - t) f(t)\,dt, and the substitution t=x−hut = x - hu gives the first claim. By Taylor's theorem with the Lagrange remainder, f(x−hu)=f(x)−hu f′(x)+12h2u2f′′(ξu)f(x - hu) = f(x) - hu\,f'(x) + \tfrac12 h^2u^2 f''(\xi_u) for some ξu\xi_u between xx and x−hux - hu. Integrate against K(u)K(u): the first term gives f(x)f(x) because ∫K=1\int K = 1, and the second gives 0 because KK is symmetric. So

E f^h(x)−f(x)−h22μ2f′′(x)=h22∫u2K(u) (f′′(ξu)−f′′(x)) du.\mathbb{E}\,\hat f_h(x) - f(x) - \frac{h^2}{2}\mu_2 f''(x) = \frac{h^2}{2}\int u^2 K(u)\,\big(f''(\xi_u) - f''(x)\big)\,du.

For each uu, ξu→x\xi_u \to x as h→0h \to 0, so the bracket goes to 0. It is bounded by 2sup⁡∣f′′∣2\sup|f''|, and u2∣K(u)∣u^2|K(u)| is integrable, so by dominated convergence the integral goes to 0. □\square

Lemma 3 (variance). If ff is bounded and continuous at xx, then as h→0h \to 0 and nh→∞nh \to \infty,

Var⁡f^h(x)=R(K) f(x)nh+o ⁣(1nh).\operatorname{Var}\hat f_h(x) = \frac{R(K)\,f(x)}{nh} + o\!\left(\frac{1}{nh}\right).

Proof. The terms are independent and identically distributed, so Var⁡f^h(x)=1n(E Kh(x−X1)2−(E Kh(x−X1))2)\operatorname{Var}\hat f_h(x) = \frac1n\left(\mathbb{E}\,K_h(x - X_1)^2 - \big(\mathbb{E}\,K_h(x - X_1)\big)^2\right). The same substitution as in Lemma 2 gives

E Kh(x−X1)2=1h∫K(u)2f(x−hu) du=R(K)f(x)h+1h∫K(u)2(f(x−hu)−f(x)) du,\mathbb{E}\,K_h(x - X_1)^2 = \frac1h \int K(u)^2 f(x - hu)\,du = \frac{R(K) f(x)}{h} + \frac1h\int K(u)^2\big(f(x - hu) - f(x)\big)\,du,

and the last integral goes to 0 by dominated convergence, because ff is bounded and K2K^2 is integrable. The squared mean is at most (sup⁡f∫∣K∣)2(\sup f \int |K|)^2, a constant, so after the division by nn it is O(1/n)=o(1/(nh))O(1/n) = o(1/(nh)). □\square

So the mean squared error at xx is

MSE(x)=h44μ22f′′(x)2+R(K)f(x)nh+o ⁣(h4+1nh).\mathrm{MSE}(x) = \frac{h^4}{4}\mu_2^2 f''(x)^2 + \frac{R(K) f(x)}{nh} + o\!\left(h^4 + \frac1{nh}\right).

The squared bias grows with hh and the variance falls with hh. A consistent estimate needs h→0h \to 0 and nh→∞nh \to \infty.

Part 3. The AMISE and the optimal bandwidth

Integrate the mean squared error over xx. If f′′f'' is square integrable and the remainders in Lemmas 2 and 3 can be integrated, which holds for example when f′′′f''' is bounded and integrable and KK has a finite fourth moment (Wand and Jones 1995, Section 2.5), then

MISE(h)=∫MSE(x) dx=AMISE(h)+o ⁣(h4+1nh),AMISE(h)=h44μ22R(f′′)+R(K)nh,\mathrm{MISE}(h) = \int \mathrm{MSE}(x)\,dx = \mathrm{AMISE}(h) + o\!\left(h^4 + \frac1{nh}\right), \qquad \mathrm{AMISE}(h) = \frac{h^4}{4}\mu_2^2 R(f'') + \frac{R(K)}{nh},

where ∫f=1\int f = 1 gives the variance term. The integrability step is quoted, not proved here.

Theorem 4. Let A=14μ22R(f′′)>0A = \frac14 \mu_2^2 R(f'') > 0 and B=R(K)>0B = R(K) > 0. On h>0h > 0, AMISE(h)=Ah4+B/(nh)\mathrm{AMISE}(h) = A h^4 + B/(nh) has exactly one minimum, at

h∗=(R(K)μ22 R(f′′) n)1/5=C n−1/5,h^* = \left(\frac{R(K)}{\mu_2^2\, R(f'')\, n}\right)^{1/5} = C\, n^{-1/5},

and the minimum value is

AMISE(h∗)=54(μ22 R(K)4 R(f′′))1/5n−4/5.\mathrm{AMISE}(h^*) = \frac54 \left(\mu_2^2\, R(K)^4\, R(f'')\right)^{1/5} n^{-4/5}.

Proof. The derivative is 4Ah3−B/(nh2)4Ah^3 - B/(nh^2). It is negative for small hh, positive for large hh, and it is 0 only at h5=B/(4An)h^5 = B/(4An). Its own derivative 12Ah2+2B/(nh3)12Ah^2 + 2B/(nh^3) is positive, so the function is strictly convex on h>0h > 0, and the zero is the unique minimum. Since 4A=μ22R(f′′)4A = \mu_2^2 R(f''), this gives h∗h^*. At the minimum, B/(nh∗)=4A(h∗)4B/(nh^*) = 4A(h^*)^4, so AMISE(h∗)=5A(h∗)4=5A (B/(4An))4/5=5⋅4−4/5A1/5(B/n)4/5\mathrm{AMISE}(h^*) = 5A(h^*)^4 = 5A\,(B/(4An))^{4/5} = 5\cdot 4^{-4/5} A^{1/5} (B/n)^{4/5}. Put in A1/5=4−1/5(μ22R(f′′))1/5A^{1/5} = 4^{-1/5}(\mu_2^2 R(f''))^{1/5}; the powers of 4 combine to 4−14^{-1}, which gives the stated value. □\square

Corollary 5 (the rate). If h=c n−ah = c\,n^{-a} with a≠1/5a \ne 1/5, then AMISE(h)\mathrm{AMISE}(h) is of larger order than n−4/5n^{-4/5}: for a<1/5a < 1/5 the term Ah4A h^4 is of order n−4an^{-4a}, and for a>1/5a > 1/5 the term B/(nh)B/(nh) is of order na−1n^{a - 1}. Both exponents are larger than −4/5-4/5. So the bandwidth must shrink like n−1/5n^{-1/5}, and the best MISE falls like n−4/5n^{-4/5}, slower than the n−1n^{-1} of a parametric fit.

For the standard normal ff, R(f′′)=3/(8π)R(f'') = 3/(8\sqrt\pi), and with the Gaussian kernel (μ2=1\mu_2 = 1, R(K)=1/(2π)R(K) = 1/(2\sqrt\pi)) Theorem 4 gives h∗=(4/(3n))1/5≈1.06 n−1/5h^* = (4/(3n))^{1/5} \approx 1.06\,n^{-1/5}. The test file compares this with the minimizer of the exact MISE, which has a closed form for normal data and a Gaussian kernel. The ratio of the two is measured, not proved: about 1.056 for n=100n = 100, 1.010 for n=104n = 10^4 and 1.002 for n=106n = 10^6.

Part 4. The binned FFT estimate

Lines L2 to L6 compute the estimate on the grid gk=lo+kδg_k = \mathrm{lo} + k\delta, k=0,…,m−1k = 0, \ldots, m-1, δ=(hi−lo)/(m−1)\delta = (\mathrm{hi} - \mathrm{lo})/(m-1). Linear binning gives each XiX_i in [gj,gj+1][g_j, g_{j+1}] the weight 1−t1 - t at gjg_j and tt at gj+1g_{j+1}, where Xi=gj+tδX_i = g_j + t\delta; cjc_j is the total weight at gjg_j. The binned estimate is

f~(gk)=1nh∑j=0m−1cj K ⁣((k−j)δh).\tilde f(g_k) = \frac1{nh}\sum_{j=0}^{m-1} c_j\,K\!\left(\frac{(k - j)\delta}{h}\right).

Lemma 6 (the FFT computes the binned sum). Let κl=K(lδ/h)/(nh)\kappa_l = K(l\delta/h)/(nh) for −L≤l≤L-L \le l \le L, stored at positions 0,…,2L0, \ldots, 2L, and let both sequences be padded with zeros to a length N≥m+2LN \ge m + 2L. Then entry k+Lk + L of the cyclic convolution is ∑∣k−j∣≤Lcjκk−j\sum_{|k - j| \le L} c_j \kappa_{k-j}.

Proof. By the convolution theorem, lines L4 and L5 give the cyclic convolution sr=∑jcj a(r−j) mod Ns_r = \sum_{j} c_j\,a_{(r - j) \bmod N}, where aa is the padded kernel sequence. For r=k+Lr = k + L and 0≤j≤m−10 \le j \le m - 1, the index r−j=(k−j)+Lr - j = (k - j) + L lies in [−(m−1),m−1+2L][-(m-1), m - 1 + 2L]. When it is in [0,2L][0, 2L], the term is cjκk−jc_j\kappa_{k-j}. When it is in [2L+1,m−1+2L][2L+1, m-1+2L], it is at most N−1N - 1, so no wrap occurs and aa is 0 there. When it is negative, it wraps to N+(r−j)≥N−(m−1)>2LN + (r - j) \ge N - (m - 1) > 2L, where aa is again 0. □\square

So the FFT result equals the binned sum with the kernel cut off at ∣u∣≤Lδ/h|u| \le L\delta/h. For the Epanechnikov kernel, L=⌈h/δ⌉L = \lceil h/\delta \rceil and nothing is cut off. For the Gaussian kernel, the code uses Lδ≥8hL\delta \ge 8h (or the whole grid), and each cut term has K≤φ(8)<5.1×10−15K \le \varphi(8) < 5.1 \times 10^{-15}; the total of the weights is nn, so the cut changes the result by less than 5.1×10−15/h5.1 \times 10^{-15}/h. The test compares the FFT result with a direct O(m2)O(m^2) sum and finds agreement within 10−1210^{-12}.

Lemma 7 (binning error). If all XiX_i lie in [lo,hi][\mathrm{lo}, \mathrm{hi}] and KK has a bounded second derivative, then for every grid point

∣f~(gk)−f^h(gk)∣≤δ2sup⁡∣K′′∣8h3.|\tilde f(g_k) - \hat f_h(g_k)| \le \frac{\delta^2 \sup|K''|}{8h^3}.

Proof. Fix kk and let ψ(t)=K((gk−t)/h)\psi(t) = K((g_k - t)/h). Point Xi=gj+tiδX_i = g_j + t_i\delta adds (1−ti)ψ(gj)+tiψ(gj+1)(1 - t_i)\psi(g_j) + t_i\psi(g_{j+1}) to nh f~(gk)nh\,\tilde f(g_k), which is the linear interpolant of ψ\psi at XiX_i. It adds ψ(Xi)\psi(X_i) to nh f^h(gk)nh\,\hat f_h(g_k). The error of linear interpolation on an interval of length δ\delta is at most δ28sup⁡∣ψ′′∣\frac{\delta^2}{8}\sup|\psi''|, and sup⁡∣ψ′′∣=sup⁡∣K′′∣/h2\sup|\psi''| = \sup|K''|/h^2. Add the nn errors and divide by nhnh. □\square

For the Gaussian kernel, sup⁡∣K′′∣=∣K′′(0)∣=1/2π\sup|K''| = |K''(0)| = 1/\sqrt{2\pi}, and the test checks the bound for three grid sizes. The Epanechnikov kernel has a kink at ±1\pm 1, so Lemma 7 does not apply to it as stated; its binning error is of order δ/h2\delta/h^2 near the kinks of the kernel.

Part 5. Cost

Line L1 costs O(n)O(n) kernel evaluations, so qq points cost O(nq)O(nq). Binning costs O(n)O(n), the kernel weights O(L)O(L) with L≤m−1L \le m - 1, and three FFTs of length N<2(m+2L)≤6mN < 2(m + 2L) \le 6m cost O(mlog⁡m)O(m \log m). The total for the grid is O(n+mlog⁡m)O(n + m\log m).

Complexity

  • Direct. Line L1 costs O(n)O(n) kernel evaluations, so qq points cost O(nq)O(nq) time. With a compact kernel and sorted data, only the points within hh of xx count, and a search finds them.
  • Binned. Binning is O(n)O(n), and three FFTs of length less than 6m6m are O(mlog⁡m)O(m \log m). The extra space is O(m)O(m). In the test file, for n=2000n = 2000 and m=1025m = 1025, the binned estimate took 0.013 s and the direct one 0.35 s, in pure Python. This is a measurement on one machine.
  • Accuracy of binning. For n=2000n = 2000 standard normal points, h=0.3h = 0.3 and a Gaussian kernel, the largest error against the direct estimate was 7.7×10−47.7 \times 10^{-4} for δ/h=0.42\delta/h = 0.42, 2.1×10−42.1 \times 10^{-4} for δ/h=0.21\delta/h = 0.21 and 9.4×10−69.4 \times 10^{-6} for δ/h=0.041\delta/h = 0.041, with a peak density near 0.4. The error falls like δ2\delta^2, as the bound says. These numbers are measured.

Properties

  • A density. With a non-negative kernel the estimate is non-negative and integrates to 1. It is as smooth as the kernel.
  • Rate. With the best hh, the MISE falls like n−4/5n^{-4/5}, slower than the n−1n^{-1} of a correct parametric model, but with no assumption on the shape of ff beyond smoothness. Kernels of higher order (with μ2=0\mu_2 = 0) give faster rates for smoother ff, but they take negative values.
  • The kernel matters little. The Epanechnikov kernel minimizes the AMISE among non-negative kernels (Epanechnikov 1969). The Gaussian kernel needs only about 5 percent more data for the same AMISE. The bandwidth matters much more.
  • Bias at peaks and valleys. The bias h22μ2f′′\frac{h^2}{2}\mu_2 f'' is negative at a peak and positive in a valley, so the estimate flattens the density.
  • Linear in the data. The estimate is a sum over points, so adding a point adds one term, and estimates for two samples combine by a weighted average.

Variants and improvements

  • Several dimensions. Use a product kernel or a kernel with a bandwidth matrix HH: f^(x)=n−1∑i∣H∣−1/2K(H−1/2(x−Xi))\hat f(x) = n^{-1}\sum_i |H|^{-1/2} K(H^{-1/2}(x - X_i)). The rate becomes n−4/(d+4)n^{-4/(d+4)}, which is very slow in high dimensions.
  • Adaptive bandwidth. A bandwidth that grows where the data are sparse, for example in proportion to f^(Xi)−1/2\hat f(X_i)^{-1/2} from a pilot estimate (Abramson), or to the distance to the kk-th nearest neighbour, as in k-nearest neighbours.
  • Boundaries. Near the edge of a bounded support, the plain estimate puts mass outside it. Reflection of the data, boundary kernels, or a transform of the data fix this.
  • Fast summation. For many evaluation points off a grid, tree methods and the fast Gauss transform approximate the sums in about O(n+q)O(n + q) time.
  • Regression. The same weights give the Nadaraya-Watson estimator and local polynomial regression for a mean function.
  • Modes and clusters. Mean shift climbs the gradient of a kernel density estimate to its modes.

When to use it

Use it to look at the shape of one or two variables, as a smooth replacement for a histogram: to see skewness, several modes or heavy tails. It also gives a density for a likelihood ratio, a classifier or a simulation. When the data come from a known family with a few parameters, fit that family instead, because it converges faster. In more than about four or five dimensions, kernel estimates need very many points; a Gaussian mixture or another model is usually better.

Pitfalls

  • The default bandwidth. Software often uses a normal reference rule, which oversmooths densities with several modes. Look at several bandwidths, or use a plug-in or cross-validation selector.
  • Bounded data. For data that cannot be negative, such as waiting times, the estimate leaks mass below 0 and is biased near 0.
  • Grid too coarse. The binning error grows like (δ/h)2(\delta/h)^2. Keep δ\delta well below hh; a few hundred grid points are usually enough in one dimension.
  • Data outside the grid. Linear binning drops points outside [lo,hi][\mathrm{lo}, \mathrm{hi}]. Extend the grid by a few bandwidths beyond the data.
  • Heavy tails. A fixed bandwidth that suits the centre leaves spikes in the tails; an adaptive bandwidth or a transform helps.
  • Discrete data. Ties and rounded values create false modes when hh is smaller than the rounding.

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.

kernel_density_estimation.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/kernel-density-estimation/. The authors are listed in prov/29Z7ZM.jsonl.

import cmath
import math

SQRT2PI = math.sqrt(2 * math.pi)


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


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


# R(K) = integral of K^2 and mu2(K) = integral of u^2 K, for the AMISE formula.
KERNEL_CONSTANTS = {
    "gaussian": (1 / (2 * math.sqrt(math.pi)), 1.0),
    "epanechnikov": (3 / 5, 1 / 5),
}


def kde(x, data, h, kernel=gaussian):
    """Direct estimate f(x) = (1/(n h)) sum K((x - X_i)/h). O(n) per point."""
    n = len(data)
    return sum(kernel((x - xi) / h) for xi in data) / (n * h)  # @line L1


def kde_grid_direct(grid, data, h, kernel=gaussian):
    """The direct estimate at every grid point. O(n m)."""
    return [kde(g, data, h, kernel) for g in grid]


def _fft(a, invert=False):
    """Iterative radix-2 FFT; len(a) must be a power of two."""
    n = len(a)
    a = list(a)
    j = 0
    for i in range(1, n):  # bit-reversal permutation
        bit = n >> 1
        while j & bit:
            j ^= bit
            bit >>= 1
        j |= bit
        if i < j:
            a[i], a[j] = a[j], a[i]
    length = 2
    while length <= n:
        ang = (2 if invert else -2) * math.pi / length
        wl = cmath.exp(1j * ang)
        for i in range(0, n, length):
            w = 1
            for k in range(length // 2):
                u, v = a[i + k], a[i + k + length // 2] * w
                a[i + k], a[i + k + length // 2] = u + v, u - v
                w *= wl
        length <<= 1
    if invert:
        a = [v / n for v in a]
    return a


def linear_binning(data, lo, delta, m):
    """Grid counts c_0..c_{m-1}: each point splits its unit weight between
    the two nearest grid points, in proportion to closeness."""
    c = [0.0] * m
    for xi in data:
        t = (xi - lo) / delta
        j = int(math.floor(t))
        f = t - j
        if 0 <= j < m:
            c[j] += 1 - f
        if 0 <= j + 1 < m:
            c[j + 1] += f
    return c


def kde_binned_fft(data, h, lo, hi, m, kernel=gaussian, support=None):
    """Binned estimate on the grid lo + k delta, k = 0..m-1, delta = (hi-lo)/(m-1).

    Linear binning, then a discrete convolution of the counts with the kernel
    weights, done by FFT. O(n + m log m) time.
    """
    n = len(data)
    delta = (hi - lo) / (m - 1)
    c = linear_binning(data, lo, delta, m)  # @line L2
    reach = support if support is not None else (1.0 if kernel is epanechnikov else 8.0)
    L = min(m - 1, int(math.ceil(reach * h / delta)))
    kap = [kernel(l * delta / h) / (n * h) for l in range(-L, L + 1)]  # @line L3
    size = 1
    while size < m + 2 * L:
        size <<= 1
    A = _fft(c + [0.0] * (size - m))  # @line L4
    B = _fft(kap + [0.0] * (size - len(kap)))
    conv = _fft([u * v for u, v in zip(A, B)], invert=True)  # @line L5
    return [conv[k + L].real for k in range(m)]  # @line L6


def binned_direct(data, h, lo, hi, m, kernel=gaussian):
    """The same binned estimate by a direct O(m^2) convolution (for tests)."""
    n = len(data)
    delta = (hi - lo) / (m - 1)
    c = linear_binning(data, lo, delta, m)
    return [sum(c[j] * kernel((k - j) * delta / h) for j in range(m)) / (n * h)
            for k in range(m)]


def amise_bandwidth(n, r_f2, kernel="gaussian"):
    """h* = (R(K) / (mu2^2 R(f'') n))^(1/5)."""
    rk, mu2 = KERNEL_CONSTANTS[kernel]
    return (rk / (mu2 * mu2 * r_f2 * n)) ** 0.2


def amise(h, n, r_f2, kernel="gaussian"):
    """(1/4) h^4 mu2^2 R(f'') + R(K)/(n h)."""
    rk, mu2 = KERNEL_CONSTANTS[kernel]
    return 0.25 * h ** 4 * mu2 * mu2 * r_f2 + rk / (n * h)


def normal_density(x, s):
    return math.exp(-0.5 * (x / s) ** 2) / (s * SQRT2PI)


def exact_mise_gaussian(h, n, sigma):
    """Exact MISE of the Gaussian-kernel KDE for N(0, sigma^2) data."""
    c = 1 / (2 * math.sqrt(math.pi))
    s1 = math.sqrt(sigma * sigma + h * h)
    bias2 = c / s1 - 2 / (SQRT2PI * math.sqrt(s1 * s1 + sigma * sigma)) + c / sigma
    var = (c / h - c / s1) / n
    return bias2 + var
test_kernel_density_estimation.py 127 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/kernel-density-estimation/. The authors are listed in prov/29Z7ZM.jsonl.

import math
import random
from fractions import Fraction

from kernel_density_estimation import (
    KERNEL_CONSTANTS, amise, amise_bandwidth, binned_direct, epanechnikov,
    exact_mise_gaussian, gaussian, kde, kde_binned_fft, kde_grid_direct,
    normal_density,
)

PAGE_DATA = [1, 2, 4, 7, 8]


def simpson(f, a, b, m):
    """Composite Simpson rule with m (even) panels; exact for quadratics."""
    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:
    f = lambda x: kde(Fraction(x), PAGE_DATA, Fraction(2), epanechnikov)
    assert f(2) == Fraction(21, 160)
    assert f(3) == Fraction(9, 80)
    assert f(4) == Fraction(3, 40)
    assert f(Fraction(11, 2)) == Fraction(21, 320)
    assert f(Fraction(15, 2)) == Fraction(9, 64)
    assert f(-1) == 0 and f(10) == 0


def test_epanechnikov_integrates_to_one_exactly() -> None:
    rng = random.Random(51)
    for _ in range(20):
        data = [Fraction(rng.randint(-20, 20), rng.randint(1, 4)) for _ in range(rng.randint(1, 8))]
        h = Fraction(rng.randint(1, 12), rng.randint(1, 4))
        # The estimate is a quadratic between consecutive breakpoints X_i +- h,
        # so Simpson's rule on each piece is exact.
        cuts = sorted({xi + s * h for xi in data for s in (-1, 1)})
        total = sum(simpson(lambda x: kde(x, data, h, epanechnikov), a, b, 2)
                    for a, b in zip(cuts, cuts[1:]))
        assert total == 1


def test_gaussian_integrates_to_one() -> None:
    rng = random.Random(52)
    data = [rng.gauss(0, 1) for _ in range(50)]
    h = 0.4
    a, b = min(data) - 10 * h, max(data) + 10 * h
    assert abs(simpson(lambda x: kde(x, data, h), a, b, 4000) - 1) < 1e-9


def test_fft_convolution_matches_direct_binned_sum() -> None:
    rng = random.Random(53)
    data = [rng.gauss(0, 1) for _ in range(300)]
    for kernel in (gaussian, epanechnikov):
        fast = kde_binned_fft(data, 0.35, -5.0, 5.0, 129, kernel)
        slow = binned_direct(data, 0.35, -5.0, 5.0, 129, kernel)
        assert max(abs(u - v) for u, v in zip(fast, slow)) < 1e-12


def test_binned_fft_against_direct_within_bound() -> None:
    # Linear binning replaces K_h(g - x) by its linear interpolation between
    # grid points, so the error is at most delta^2 sup|K''| / (8 h^3).
    rng = random.Random(54)
    data = [rng.gauss(0, 1) for _ in range(1000)]
    h, lo, hi = 0.3, -7.0, 7.0
    for m in (65, 129, 257):
        delta = (hi - lo) / (m - 1)
        grid = [lo + k * delta for k in range(m)]
        err = max(abs(u - v) for u, v in zip(kde_binned_fft(data, h, lo, hi, m),
                                              kde_grid_direct(grid, data, h)))
        bound = delta ** 2 / (8 * h ** 3 * math.sqrt(2 * math.pi))
        assert err <= bound + 1e-12


def test_bias_and_variance_expansions() -> None:
    # For N(0,1) data and the Gaussian kernel, E f(x) = phi_{sqrt(1+h^2)}(x)
    # and E K_h(x - X)^2 = phi_{sqrt(1 + h^2/2)}(x) / (2 h sqrt(pi)).
    f = lambda x: normal_density(x, 1.0)
    f2 = lambda x: (x * x - 1) * f(x)  # f''
    rk = KERNEL_CONSTANTS["gaussian"][0]
    for x in (0.0, 0.7, 1.5):
        for h in (1e-1, 1e-2):
            mean = normal_density(x, math.sqrt(1 + h * h))
            bias = mean - f(x)
            assert abs(bias / (h * h / 2 * f2(x)) - 1) < 3 * h * h + 1e-6
            ek2 = normal_density(x, math.sqrt(1 + h * h / 2)) / (2 * h * math.sqrt(math.pi))
            nh_var = h * (ek2 - mean * mean)  # n h Var for any n
            assert abs(nh_var - rk * f(x)) < 2 * h
    # And a Monte Carlo check of the mean of the code's estimate.
    rng = random.Random(55)
    h, n, reps = 0.5, 100, 400
    vals = [kde(0.0, [rng.gauss(0, 1) for _ in range(n)], h) for _ in range(reps)]
    m = sum(vals) / reps
    sd = math.sqrt(sum((v - m) ** 2 for v in vals) / (reps - 1))
    assert abs(m - normal_density(0.0, math.sqrt(1 + h * h))) < 3 * sd / math.sqrt(reps)


def golden(f, a, b, it=200):
    g = (math.sqrt(5) - 1) / 2
    c, d = b - g * (b - a), a + g * (b - a)
    for _ in range(it):
        if f(c) < f(d):
            b = d
        else:
            a = c
        c, d = b - g * (b - a), a + g * (b - a)
    return (a + b) / 2


def test_amise_bandwidth() -> None:
    rf2 = 3 / (8 * math.sqrt(math.pi))  # R(f'') for N(0, 1)
    for n in (10, 1000, 10**6):
        h = amise_bandwidth(n, rf2)
        assert abs(h - (4 / (3 * n)) ** 0.2) < 1e-12
        # h minimises the AMISE: its derivative h^3 mu2^2 R - R(K)/(n h^2) is 0.
        assert abs(golden(lambda t: amise(t, n, rf2), 1e-4, 3) / h - 1) < 1e-6
    # The exact MISE minimiser approaches the AMISE one as n grows.
    ratios = [golden(lambda t: exact_mise_gaussian(t, n, 1.0), 1e-4, 3) / amise_bandwidth(n, rf2)
              for n in (100, 10**4, 10**6)]
    assert ratios[0] > ratios[1] > ratios[2] > 1
    assert ratios[2] < 1.005

History

Fix and Hodges studied nonparametric discrimination in 1951, an early use of local density estimates. Rosenblatt defined the kernel estimate in 1956 and found the n−4/5n^{-4/5} rate of its mean squared error. Parzen (1962) proved its consistency and asymptotic normality for general kernels, and the estimate is often called the Parzen window in pattern recognition. Epanechnikov (1969) found the optimal kernel. Silverman (1982) published the FFT algorithm with binning, and Jones and Lotwick improved the binning to the linear form. His 1986 book made the method standard. Wand and Jones (1995) gave the usual modern account.

References

  1. Murray Rosenblatt, Remarks on some nonparametric estimates of a density function, The Annals of Mathematical Statistics 27(3), 1956, pp. 832 to 837 (the kernel estimate, its bias and variance, and the n^(-4/5) rate of the mean squared error)
  2. Emanuel Parzen, On estimation of a probability density function and mode, The Annals of Mathematical Statistics 33(3), 1962, pp. 1065 to 1076 (consistency and asymptotic normality for a general class of kernels)
  3. V. A. Epanechnikov, Non-parametric estimation of a multivariate probability density, Theory of Probability and Its Applications 14(1), 1969, pp. 153 to 158 (the kernel that minimizes the asymptotic mean integrated squared error)
  4. B. W. Silverman, Algorithm AS 176. Kernel density estimation using the fast Fourier transform, Applied Statistics 31(1), 1982, pp. 93 to 99 (the binned estimate computed by the FFT)
  5. B. W. Silverman, Density Estimation for Statistics and Data Analysis, Chapman and Hall, 1986, Chapter 3 (the kernel method, its bias and variance, and the choice of the smoothing parameter)
  6. M. P. Wand and M. C. Jones, Kernel Smoothing, Chapman and Hall, 1995, Chapter 2 (MISE, AMISE and the optimal bandwidth, Section 2.5; the exact MISE for normal mixtures) and Appendix D (binned computation)

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