Module contents
Lesson 4 of 24Core 95 min

Nonparametric density estimation and mean shift

Nonparametric density estimation, bandwidth selection, nearest-neighbor estimation and mean shift clustering.

After this lesson you can

  • Derive kernel density bias, variance, optimal bandwidth and convergence rate.
  • Implement a Gaussian KDE and select bandwidth by likelihood cross-validation.
  • Compare reference rules and cross-validation on multimodal and heavy-tailed densities.
  • Explain how dimensionality degrades convergence rates.
  • Implement mean shift as gradient ascent on a KDE and cluster by modes.

Before you start

Motivation: density as the central object

You measure service latency: the mean is 80 ms and the 99th percentile 400 ms, but neither tells you there are two populations, cache hits and misses. You examine an asset’s daily returns and want value at risk without assuming normality: you need a distribution quantile, a property of its density. You have events from a normally operating system and want to know whether the next is rare: “rare” means it falls where density is low. All three ask the same question: what is ff, the density generating these data?

This is the most basic unsupervised question (lesson 1 places it as the task of which the others are partial readings): clusters are ff‘s hills, anomalies its valleys, and generating data means sampling from it. Here you approach it without assuming a parametric family. “Nonparametric” does not mean “assumption-free”; the effective number of parameters grows with nn: require ff to be smooth and let data draw its shape. This has a price to quantify, the thread of the whole lesson: error falls not as n−1n^{-1} as in a parametric problem, but as n−4/5n^{-4/5} in one dimension and n−4/(4+d)n^{-4/(4+d)} in dimension dd.

The plan: histograms, already containing the entire problem (bin width and error from choosing badly); kernel density estimation and its complete bias–variance analysis; selecting bandwidth; what happens as dimension grows; kk-neighbor estimation, adapting scale to each point; and finally mean shift, which climbs the estimated density gradient to its modes and turns density estimation into clustering. A measurement note: given X1,…,Xn∼iidfX_1, \dots, X_n \iid f in Rd\R^d and estimator f^\hat f, global error is integrated squared error ISE(f^)=∫(f^−f)2\mathrm{ISE}(\hat f) = \int (\hat f - f)^2 and its expectation MISE=E[ISE]\mathrm{MISE} = \E[\mathrm{ISE}]. By the mean squared error decomposition, at each point E[(f^(x)−f(x))2]=sesgo⁡(x)2+Var⁡(f^(x))\E[(\hat f(x) - f(x))^2] = \operatorname{sesgo}(x)^2 + \Var(\hat f(x)), and MISE is the integral of that sum.

Histograms: the simplest estimator already contains the whole problem

Divide the line into intervals (bins) Bj=[ t0+(j−1)b,  t0+jb )B_j = [\,t_0 + (j-1)b,\; t_0 + jb\,) of width bb and origin t0t_0. Probability of BjB_j is pj=∫Bjfp_j = \int_{B_j} f, estimated by the fraction nj/nn_j/n of data falling in it. Distributing that mass uniformly within the bin yields the estimator.

Since nj∼Bin(n,pj)n_j \sim \mathrm{Bin}(n, p_j), mean and variance follow directly. Let cjc_j be the center of bin BjB_j. For x∈Bjx \in B_j:

E[f^b(x)]=pjb=1b∫Bjf(y) ⁣dy=f(x)+f′(x) (cj−x)+O(b2),Var⁡(f^b(x))=pj(1−pj)nb2=f(x)nb+O ⁣(1n).\E[\hat f_b(x)] = \frac{p_j}{b} = \frac{1}{b}\int_{B_j} f(y)\dd y = f(x) + f'(x)\,(c_j - x) + \bigO(b^2), \qquad \Var(\hat f_b(x)) = \frac{p_j(1 - p_j)}{n b^2} = \frac{f(x)}{n b} + \bigO\!\Big(\frac{1}{n}\Big).

The first equality is a Taylor expansion of ff around xx (Taylor in one variable): 1b∫Bj(y−x) ⁣dy=cj−x\frac{1}{b}\int_{B_j}(y - x)\dd y = c_j - x. Bias is order bb, not b2b^2: it depends on where xx falls in its bin and the slope of ff there. Integrating the square, with (cj−x)(c_j - x) uniform on [−b/2,b/2][-b/2, b/2] and thus mean square b2/12b^2/12, and writing R(g)=∫g2\mathrm{R}(g) = \int g^2 (the roughness of gg):

AMISE(b)=b212 R(f′)+1nb,b∗=(6R(f′) n)1/3,AMISE(b∗)=14(36 R(f′))1/3n−2/3.\mathrm{AMISE}(b) = \frac{b^2}{12}\,\mathrm{R}(f') + \frac{1}{n b}, \qquad b^* = \Big(\frac{6}{\mathrm{R}(f')\,n}\Big)^{1/3}, \qquad \mathrm{AMISE}(b^*) = \frac{1}{4}\big(36\,\mathrm{R}(f')\big)^{1/3} n^{-2/3}.

Here AMISE is asymptotic MISE (leading terms as b→0b \to 0 and nb→∞nb \to \infty), and f′f' must be square-integrable. Two interpretations. First, the tradeoff: narrow bins give little bias and high variance, wide bins the reverse, and the optimum scales as n−1/3n^{-1/3}. Second, rate n−2/3n^{-2/3} is worse than the n−4/5n^{-4/5} obtained with smooth kernels, precisely because of the steps: a piecewise-constant estimator has order-bb rather than order-b2b^2 bias. For a normal distribution, R(f′)=1/(4π σ3)\mathrm{R}(f') = 1/(4\sqrt{\pi}\,\sigma^3) and b∗=(24π)1/3σ n−1/3≈3.49 σ n−1/3b^* = (24\sqrt{\pi})^{1/3}\sigma\, n^{-1/3} \approx 3.49\,\sigma\, n^{-1/3}, Scott’s rule (1979).

Besides its slow rate there are two defects familiar from any histogram: the result depends on origin t0t_0 (with the same width and data, shifting redistributes data among bins and can move or create peaks), and the step function has no derivative, so cannot be used to climb the gradient at the end. The solution is one more idea: instead of a fixed grid, center a bin at each evaluation point and smooth.

Kernel density estimator

To evaluate f^(x)\hat f(x) with a histogram bin centered at xx, count data at distance less than b/2b/2 from xx. Replacing “inside or outside” with a weight decaying with distance gives the kernel density estimator (KDE), introduced by Rosenblatt (1956) and Parzen (1962).

It is a mixture of nn copies of the kernel, one centered on each datum and all weighted 1/n1/n. It inherits good properties from KK: if K≥0K \ge 0, f^h\hat f_h is a density (∫f^h=1\int \hat f_h = 1), and is as smooth as KK (with the Gaussian it is infinitely differentiable). Common kernels:

KernelK(u)K(u)μ2(K)\mu_2(K)R(K)\mathrm{R}(K)Efficiency
Epanechnikov34(1−u2)\tfrac{3}{4}(1 - u^2) on [−1,1][-1, 1]1/51/53/53/511
Biweight1516(1−u2)2\tfrac{15}{16}(1 - u^2)^2 on [−1,1][-1, 1]1/71/75/75/70.9940.994
Triangular1−∣u∣1 - \abs{u} on [−1,1][-1, 1]1/61/62/32/30.9860.986
Gaussian12πe−u2/2\tfrac{1}{\sqrt{2\pi}}e^{-u^2/2}1112π≈0.282\tfrac{1}{2\sqrt{\pi}} \approx 0.2820.9510.951
Uniform12\tfrac12 on [−1,1][-1, 1]1/31/31/21/20.9300.930

Efficiency is the ratio of sample sizes at which two kernels reach the same optimal AMISE (below you will see it follows from μ2(K)1/2 R(K)\mu_2(K)^{1/2}\,\mathrm{R}(K)): the Gaussian kernel needs 1/0.951−1≈5 %1/0.951 - 1 \approx 5\,\% more data than Epanechnikov, optimal among symmetric densities (Epanechnikov, 1969; Silverman, 1986, section 3.3). The kernel matters little; bandwidth is everything. Gaussian loses 5%, and a poor choice of hh loses an order of magnitude.

An interpretation useful twice: f^h=Pn∗Kh\hat f_h = P_n * K_h is the convolution of empirical measure Pn=1n∑iδXiP_n = \frac1n\sum_i \delta_{X_i} with KhK_h (density convolution): it is the density of XI+h εX_I + h\,\varepsilon, where you choose a random datum XIX_I and add noise ε∼K\varepsilon \sim K. And in expectation, E[f^h(x)]=(Kh∗f)(x)\E[\hat f_h(x)] = (K_h * f)(x): the estimator is systematically blurred by that kernel. This produces bias, so bias does not disappear as nn grows with fixed hh.

InteractiveBandwidth is everything
Estimate from 50 points (rug marks) versus the true density
KDE, h = 0.400
Integrated squared error versus smoothing parameter (log scale)
  • true density
  • estimator (current parameter)
  • difference from true density
  • Normal reference rule
  • Silverman
  • Cross-validation
  • Oracle
Estimator
0.400
50
Current ISE0.0081
Oracle: grid minimum (h = 0.301)0.0060
Normal reference rule (h = 0.424)ISE 0.0089
Silverman (h = 0.360)ISE 0.0070
Cross-validation (h = 0.368)ISE 0.0072
Modes of f̂ (true density has 2)1
Mass of f̂ in [−3.5, 3.5]1.000
Select Normal reference rule and look at the modes. What does a rule designed for Gaussian data do with this sample? Then try cross-validation.
A sample of 50 data points (ticks at the bottom) from a bimodal mixture whose true density is dashed. With KDE, click 'Normal rule': at h = 0.424 the estimate has one mode and ISE 0.0089. With 'Cross-validation' (h = 0.368) and the oracle (h = 0.301), both modes appear, with ISE 0.0072 and 0.0060. Lower h to 0.05 and 12 modes appear, one per small data group (enable individual kernels); raise it to 1.5 and everything becomes one hill. The lower panel is ISE versus parameter: each rule lands at a different position in the valley. With 'Histogram', move the bin origin without changing data: shape changes. With 'k neighbors', inspect the mass of f̂ in [−3.5, 3.5] and the tails. 'New sample' repeats the experiment with different data.

The figure is the lesson in miniature. Take away: (1) error has a valley, with undersmoothing on one side and oversmoothing on the other; (2) the valley is asymmetric, contrary to appearance: the undersmoothed curve looks worse with spurious peaks, but in ISE overshooting costs more. With h=c h∗h = c\,h^*, the next section’s AMISE is c4+4/c5\frac{c^4 + 4/c}{5} times optimum: 3.6 times with c=2c = 2 and 1.6 with c=1/2c = 1/2, because squared bias grows as h4h^4 and variance only as 1/h1/h; (3) no rule always succeeds: on this sample, the rule designed for normal data merges the two modes. This is not bad sample luck. With this mixture’s true standard deviation (σ=0.952\sigma = 0.952), the normal rule gives h=1.06 σ n−1/5h = 1.06\,\sigma\, n^{-1/5}, and the KDE of the expected density f∗Khf * K_h ceases to have two modes when h≳0.439h \gtrsim 0.439; this happens for n≲64n \lesssim 64. With fewer than about 64 data points, this rule blurs the two modes on average, not just in an unlucky sample. The exact optimum for n=50n = 50 is h∗=0.356h^* = 0.356, clearly below.

Asymptotic analysis: bias, variance and optimal bandwidth

Now the analysis explaining the valley. Complete assumptions: ff is twice differentiable with continuous, bounded, square-integrable f′′f''; KK is a bounded kernel as defined; and bandwidth h=hnh = h_n satisfies h→0h \to 0 and nh→∞nh \to \infty (data must fill each window of width hh).

Proof

Bias. Substituting y=x−huy = x - hu, E[f^h(x)]=∫Kh(x−y)f(y) ⁣dy=∫K(u) f(x−hu) ⁣du\E[\hat f_h(x)] = \int K_h(x - y)f(y)\dd y = \int K(u)\,f(x - hu)\dd u. Second-order Taylor: f(x−hu)=f(x)−hu f′(x)+12h2u2f′′(x)+o(h2u2)f(x - hu) = f(x) - hu\,f'(x) + \tfrac12 h^2u^2 f''(x) + o(h^2 u^2), with uniform remainder since f′′f'' is continuous and bounded. Since ∫K=1\int K = 1 and ∫uK=0\int uK = 0 (symmetry), this gives E[f^h(x)]=f(x)+12h2μ2(K)f′′(x)+o(h2)\E[\hat f_h(x)] = f(x) + \tfrac12 h^2\mu_2(K) f''(x) + o(h^2).

Variance. f^h(x)\hat f_h(x) is the mean of nn iid variables Yi=Kh(x−Xi)Y_i = K_h(x - X_i), so Var⁡(f^h(x))=1n(E[Y2]−(E[Y])2)\Var(\hat f_h(x)) = \frac{1}{n}\big(\E[Y^2] - (\E[Y])^2\big). With the same substitution, E[Y2]=∫Kh(x−y)2f(y) ⁣dy=1h∫K(u)2f(x−hu) ⁣du=f(x)R(K)h+o(1/h)\E[Y^2] = \int K_h(x - y)^2 f(y)\dd y = \frac{1}{h}\int K(u)^2 f(x - hu)\dd u = \frac{f(x)\mathrm{R}(K)}{h} + o(1/h), and E[Y]2=f(x)2+o(1)\E[Y]^2 = f(x)^2 + o(1). Then Var⁡=f(x)R(K)nh+O(1/n)\Var = \frac{f(x)\mathrm{R}(K)}{nh} + \bigO(1/n), and since nh→∞nh \to \infty, 1/n=o(1/(nh))1/n = o(1/(nh)).

Integrate and minimize. ∫sesgo⁡2=h44μ22 R(f′′)+o(h4)\int \operatorname{sesgo}^2 = \frac{h^4}{4}\mu_2^2\,\mathrm{R}(f'') + o(h^4) and, since ∫f=1\int f = 1, ∫Var⁡=R(K)nh+O(1/n)\int \Var = \frac{\mathrm{R}(K)}{nh} + \bigO(1/n). Differentiating AMISE, h3μ22 R(f′′)−R(K)/(nh2)=0h^3\mu_2^2\,\mathrm{R}(f'') - \mathrm{R}(K)/(n h^2) = 0, giving h5=R(K)/(μ22 R(f′′) n)h^5 = \mathrm{R}(K)/(\mu_2^2\,\mathrm{R}(f'')\,n). At the optimum, the bias term is one quarter of the variance term (h4μ22R(f′′)=R(K)/(nh)h^4\mu_2^2\mathrm{R}(f'') = \mathrm{R}(K)/(nh) gives 14\tfrac14 of that value), so AMISE(h∗)=54 R(K)/(nh∗)\mathrm{AMISE}(h^*) = \tfrac54\,\mathrm{R}(K)/(nh^*), the stated formula. To compare kernels, AMISE(h∗)∝(μ21/2R(K))4/5\mathrm{AMISE}(h^*) \propto (\mu_2^{1/2}\mathrm{R}(K))^{4/5}, giving table efficiency 3/(55)μ21/2R(K)\frac{3/(5\sqrt5)}{\mu_2^{1/2}\mathrm{R}(K)}. ■\blacksquare

∎

What the theorem says, without overreaching:

  • Bias is f′′f''. At a peak f′′<0f'' < 0 and KDE lies below (flattens the top); in a valley f′′>0f'' > 0 and it lies above (fills it). Bias grows with h2h^2 and does not depend on nn.
  • Variance is proportional to f(x)f(x) and decreases with nhnh. In absolute terms it is greater where density is higher, at peaks. What explodes in tails is relative variance: Var⁡/f2≈R(K)/(nh f(x))\Var/f^2 \approx \mathrm{R}(K)/(nh\,f(x)) grows as f→0f \to 0, because few data fall in each window there. (The common description “variance lives in tails” is true only in this relative reading.)
  • The rate is n−4/5n^{-4/5}: slower than n−1n^{-1} for a parametric estimator. With a positive kernel it gets no better; higher-order kernels (with μ2=0\mu_2 = 0) improve the rate, but cease to be densities and the estimate can be negative.
  • h∗h^* depends on R(f′′)\mathrm{R}(f''), the roughness of the density to estimate: densities with narrow peaks need small hh. It is unknown, motivating all the next section’s selection methods.
InteractiveKDE bias and variance
50 KDEs from independent samples of size 100
Exact pointwise squared bias and variance. Dotted line shows the shape of f(x).
Error integrado frente a h con n = 100 (el punto marca el h actual)
  • true density
  • mean of the 50 KDEs
  • squared bias
  • variance
  • exact MISE
  • AMISE
  • h* (orange line)
100
×1.00
Center plot
Exact h* (minimizes MISE)0.2926
Current h0.2926
h* · n^(1/5)0.735
Integrated squared bias (exact)0.00297
Integrated variance (exact)0.00685
Exact MISE0.00983
Mean ISE across 50 curves0.01104
Near the optimum. Variance is 0.0069 and squared bias is 0.0030. As n grows, theory predicts variance at h* approaches four times the squared bias. The exact ratio for this n is 2.31.
Above, 50 KDEs from 50 independent samples of size n (thin) and their mean (orange) against truth (dashed). Center: squared bias and variance at each point, calculated exactly for this Gaussian mixture: bias concentrates in the two peaks and valley (where f'' is large) and variance follows f(x); enable 'Relative to f(x)' to see relative error explode in tails. Below, integrated error against h: increasing squared bias, decreasing variance, exact MISE (thick line) and AMISE (dashed). With n = 100 initially, optimal h is 0.293, with integrated variance (0.00685) 2.3 times squared bias (0.00297); at half optimal h, squared bias is 0.00026 and variance 0.01634, and at double h they are 0.01698 and 0.00237. Raise n from 25 to 3200: optimal h falls from 0.449 to 0.131 and its product with n^(1/5) from 0.855 to 0.660, approaching asymptotic limit 0.641; variance/squared-bias ratio at optimum rises from 1.5 to 3.3, approaching the theorem's 4.

One detail in the figure qualifies the theorem: h∗∝n−1/5h^* \propto n^{-1/5} is asymptotic. At moderate nn, h∗ n1/5h^*\,n^{1/5} still moves (0.855 with 25 points to 0.660 with 3200), and the optimal 4-to-1 variance–squared-bias ratio is reached slowly. Do not use n−1/5n^{-1/5} as an exact law to extrapolate bandwidth from a small sample to a large one without recalculation.

Bandwidth selection

Choosing hh is the central problem, and we name it because the rest of this module (and your life with KDE) revolves around it.

There are three families, from fastest to most expensive.

Reference rules. Replace unknown R(f′′)\mathrm{R}(f'') in the theorem with that of a normal distribution with the data’s standard deviation, R(f′′)=3/(8π σ5)\mathrm{R}(f'') = 3/(8\sqrt\pi\,\sigma^5). With a Gaussian kernel this gives h=(4/3)1/5 σ^ n−1/5≈1.06 σ^ n−1/5h = (4/3)^{1/5}\,\hat\sigma\, n^{-1/5} \approx 1.06\,\hat\sigma\, n^{-1/5}. Silverman’s rule (1986) uses 0.9 min⁡{σ^, IQR/1.34} n−1/50.9\,\min\{\hat\sigma,\ \mathrm{IQR}/1.34\}\,n^{-1/5}: factor 0.9 and the minimum provide some protection against bimodality or outliers. In dd dimensions, Scott gives hj=σ^j n−1/(d+4)h_j = \hat\sigma_j\,n^{-1/(d+4)} for each coordinate, and Silverman multiplies by (4/(d+2))1/(d+4)(4/(d+2))^{1/(d+4)} (returning to 1.061.06 at d=1d = 1). They cost one line and are exact if ff is normal. Terrell (1990) provides context: for any density of variance σ2\sigma^2, AMISE h∗h^* with Gaussian kernel does not exceed 1.144 σ n−1/51.144\,\sigma\,n^{-1/5}, so 1.061.06 is near that ceiling: these rules err on the high side (oversmooth) when ff has more structure than a normal distribution, and nearby modes are the first thing lost.

Likelihood cross-validation. Evaluate each hh using each datum’s likelihood under the estimator constructed without it: CV(h)=1n∑i=1nlog⁡f^h,−i(Xi),f^h,−i(x)=1(n−1)h∑j≠iK(x−Xjh).\mathrm{CV}(h) = \frac{1}{n}\sum_{i=1}^n \log \hat f_{h,-i}(X_i), \qquad \hat f_{h,-i}(x) = \frac{1}{(n-1)h}\sum_{j \ne i}K\Big(\frac{x - X_j}{h}\Big).

Proof

XiX_i is independent of the other n−1n-1 data points, on which f^h,−i\hat f_{h,-i} depends. Conditioning on them, E[log⁡f^h,−i(Xi)∣X−i]=∫f(x)log⁡f^h,−i(x) ⁣dx=∫flog⁡f−KL⁡(f ∥ f^h,−i)\E[\log \hat f_{h,-i}(X_i)\mid X_{-i}] = \int f(x)\log\hat f_{h,-i}(x)\dd x = \int f \log f - \KL(f\,\|\,\hat f_{h,-i}). Take expectations; all terms have the same expectation because f^h,−i\hat f_{h,-i} is the KDE of n−1n-1 iid data. ■\blacksquare

∎

Notice why the datum must be left out. In sample, f^h(Xi)\hat f_h(X_i) includes the datum’s own term, worth K(0)/(nh)K(0)/(nh). Then 1n∑ilog⁡f^h(Xi)≥log⁡K(0)nh→∞\frac1n\sum_i\log\hat f_h(X_i) \ge \log\frac{K(0)}{nh} \to \infty as h→0h \to 0: likelihood evaluated on data defining the estimate has no maximum and escapes toward the smallest hh, a delta peak on each datum. (Cell 2 prints this.) KL also severely penalizes places where f^\hat f is near zero and data exist: with heavy tails and a light-tailed kernel, extremes drag h^\hat h to overly large values (Schuster and Gregory, 1981, study this inconsistency). Cell 5 shows it with a Student tt.

Least-squares cross-validation. Target ISE directly: ISE(h)=∫f^h2−2∫f^hf+∫f2\mathrm{ISE}(h) = \int\hat f_h^2 - 2\int\hat f_h f + \int f^2, with the last term independent of hh, and estimate ∫f^hf=EX[f^h(X)]\int\hat f_h f = \E_X[\hat f_h(X)] by 1n∑if^h,−i(Xi)\frac1n\sum_i\hat f_{h,-i}(X_i). With a Gaussian kernel the first term has closed form, and LSCV(h)=1n2∑i,jφ2h(Xi−Xj)−2n(n−1)∑i≠jφh(Xi−Xj),\mathrm{LSCV}(h) = \frac{1}{n^2}\sum_{i,j}\varphi_{\sqrt2 h}(X_i - X_j) - \frac{2}{n(n-1)}\sum_{i\ne j}\varphi_h(X_i - X_j), where φs\varphi_s is the N(0,s2)\Normal(0, s^2) density. It is unbiased for ISE (up to a constant) and uses no logarithms, so does not suffer from tails, but is highly variable: its h^\hat h converges to h∗h^* at relative rate n−1/10n^{-1/10} (Hall and Marron, 1987), sometimes with multiple local minima. Second-generation plug-in selectors, such as Sheather and Jones (1991), estimate R(f′′)\mathrm{R}(f'') with another bandwidth and reach n−5/14n^{-5/14}; R provides these as bw.SJ. Neither SciPy nor scikit-learn includes them.

Reflection, transformations and bounded support

Gaussian KDE puts mass on the entire line. If data are positive times or prices, some mass falls on impossible values, and near the boundary bias is no longer O(h2)\bigO(h^2) because the window is cut off. Two common remedies. Reflection mirrors data at the boundary, f^R(x)=f^h(x)+f^h(−x)\hat f_R(x) = \hat f_h(x) + \hat f_h(-x) for x≥0x \ge 0: it loses no mass, but forces f^R′(0)=0\hat f_R'(0) = 0 and thus remains biased of order hh near 0 if f′(0)≠0f'(0) \neq 0. Transformation: estimate with Y=log⁡XY = \log X (on the whole line) and transform back, f^X(x)=f^Y(log⁡x)/x\hat f_X(x) = \hat f_Y(\log x)/x, also giving a smoothing scale proportional to value, suitable for skewed long-tailed data. Cell 6 compares them.

Multivariate KDE and the curse of dimensionality

For x∈Rd\vb{x} \in \R^d, f^H(x)=1n ∣H∣1/2∑iK(H−1/2(x−xi))\hat f_{\mat{H}}(\vb{x}) = \frac{1}{n\,\abs{\mat{H}}^{1/2}}\sum_i K\big(\mat{H}^{-1/2}(\vb{x} - \vb{x}_i)\big) with a symmetric positive-definite bandwidth matrix H\mat{H}. Gaussian kernel and H=h2I\mat{H} = h^2\mat{I} (isotropic) are common, but dangerous: the same hh in every direction makes sense only when scales are comparable. If one variable is measured in thousands and another in units, an hh small enough for the second is ridiculously narrow for the first, and an hh appropriate for the first erases the second. Two solutions: standardize each variable (one hjh_j per coordinate, Scott’s rule), or whiten using sample covariance, z=L^−1(x−μ^)\vb{z} = \hat{\mat{L}}^{-1}(\vb{x} - \hat{\vb{\mu}}) with Σ^=L^L^⊤\hat{\mat{\Sigma}} = \hat{\mat{L}}\hat{\mat{L}}\T, and use isotropic hh in z\vb{z}; SciPy does this by default in gaussian_kde, using H=h2Σ^\mat{H} = h^2\hat{\mat{\Sigma}}. Cell 7 shows the difference in test likelihood.

The same analysis, with KK in dd dimensions, gives bias O(h2)\bigO(h^2) and variance O(1/(nhd))\bigO\big(1/(nh^d)\big): a window of side hh in Rd\R^d contains a fraction hdh^d of mass, not hh. AMISE is ≍h4+1nhd\asymp h^4 + \frac{1}{nh^d}, minimized at h∗∝n−1/(d+4),AMISE(h∗)∝n−4/(d+4).h^* \propto n^{-1/(d+4)}, \qquad \mathrm{AMISE}(h^*) \propto n^{-4/(d+4)}. For d=1d = 1 this is the previous n−4/5n^{-4/5}. To divide error by 10 you must multiply nn by 10(4+d)/410^{(4+d)/4}: 17.817.8 with d=1d = 1, but 103.5≈316210^{3.5} \approx 3162 with d=10d = 10. This is the curse of dimensionality in its clearest form.

Silverman (1986, table 4.2) made it concrete with a criterion: how many points from N(0,Id)\Normal(\vb{0}, \mat{I}_d) are needed for relative mean squared error of Gaussian KDE at the origin, with the best possible hh, to be 0.1. Error has closed form (bias (2π(1+h2))−d/2−(2π)−d/2\big(2\pi(1+h^2)\big)^{-d/2} - (2\pi)^{-d/2}, and variance follows from E[Kh2]\E[K_h^2]), which the figure calculates exactly.

InteractiveHow much data each dimension requires
Required sample size versus dimension (log scale)
768
Best achievable relative error versus n. Gray curves show other dimensions, from 1 on the left to 10 on the right.
  • selected dimension
  • other dimensions
  • tolerated error
  • your n
5
10.0 %
1000
Samples needed at d=5d = 5768
Ratio to the previous dimension×3.4
Optimal h at that sample size0.349
Relative error with your nn9.0 %
Asymptotic exponent −4/(4+d)−0.444
Sample multiplier to divide error by 10 (asymptotic)×178
Dimension 5 requires 768 samples, 3.4 times the requirement in dimension 4. With your n = 1000, the best relative MSE is 9.0% (RMSE 30% of f(0)).
Above, points required for 10% relative squared error (Silverman's criterion) at the mode of a standard Gaussian, with best bandwidth: 4 points at d = 1, 768 at d = 5 and 841,566 at d = 10 (the book table's rounded values). Each extra dimension multiplies the count by 3.3 to 4.8; increase tolerance or lower d to see the change. Below, best achievable error versus n for each dimension; the selected dimension's curve is blue, and the orange line marks available data.

Two reading clarifications. First, this is a best-case result: optimal hh, Gaussian ff, one point (the origin). Rougher ff or evaluation in a tail is worse. Second, the exponent uses the dimension in which data have mass at scale hh. If data live near a manifold of dimension dint≪dd_{\text{int}} \ll d (intrinsic dimension, lesson 1), dintd_{\text{int}}, not dd, matters at small scales; but if ambient noise is wider than hh, ambient dimension counts again. And if data lie exactly on the manifold, no density exists with respect to Lebesgue measure on Rd\R^d: KDE merely draws increasingly narrow ridges as hh falls.

kk-neighbor estimation

KDE fixes window width and lets the number of contained data vary. The opposite idea fixes the number of data and lets the window vary. Probability of a ball B(x,r)B(x, r) is approximately f(x) Vd rdf(x)\,V_d\,r^d, with Vd=πd/2/Γ(d/2+1)V_d = \pi^{d/2}/\Gamma(d/2+1) the unit-ball volume. If the smallest ball centered at xx containing kk of the nn data points has radius Rk(x)R_k(x), its probability is of order k/nk/n; solving gives:

This is a uniform-kernel KDE with variable bandwidth, h=Rk(x)h = R_k(x): small where data are plentiful (resolving narrow peaks) and large where they are sparse (smoothing tails). This adaptation is its advantage. The costs:

  • It is not normalized. Far from data, Rk(x)≈∥x∥R_k(x) \approx \norm{x} and f^k(x)≈k/(nVd∥x∥d)\hat f_k(x) \approx k/(n V_d\norm{x}^d), whose integral over {∥x∥>L}\{\norm{x} > L\} is proportional to ∫L∞r−d rd−1 ⁣dr=∫L∞r−1 ⁣dr\int_L^\infty r^{-d}\,r^{d-1}\dd r = \int_L^\infty r^{-1}\dd r, which diverges (logarithmically). It is not a density. Cell 3 measures this: with n=200n = 200, k=10k = 10, mass inside the data range is already 1.079 and each tail decade adds more.
  • It is not smooth: RkR_k is not differentiable where the counted neighbor changes, so f^k\hat f_k has corners and mean shift or another gradient method has no gradient to follow there.
  • Consistency. Convergence requires k→∞k \to \infty and k/n→0k/n \to 0. Pointwise squared error is of order (k/n)4/d+1/k(k/n)^{4/d} + 1/k (squared bias plus relative variance, Mack and Rosenblatt, 1979), minimized at k∗∝n4/(d+4)k^* \propto n^{4/(d+4)} and giving the same n−4/(d+4)n^{-4/(d+4)} as KDE: local scale adjustment does not improve the rate, only the allocation of error. Rule k≈nk \approx \sqrt n is a reasonable heuristic, not a result.

Even so, it is the one you will use most without knowing: it needs only distances (works for any metric, including mixed-data distances from lesson 1) and underlies kk-NN classification (the ratio of two such class densities). Distance to the kkth neighbor is HDBSCAN’s “core distance” (next lesson) and the basis of local anomaly factors. A variant without that defect, with variable but smooth normalized bandwidth, is Abramson’s (1982) adaptive KDE, with hi∝f^(Xi)−1/2h_i \propto \hat f(X_i)^{-1/2}.

Mean shift: climb density to its modes

Now use what you built for clustering. If f^\hat f estimates ff well, modes of f^\hat f are group centers and each datum belongs to the hill it climbs. An algorithm is still needed to climb. With radial kernel K(u)=cK k(∥u∥2)K(\vb{u}) = c_K\,k(\norm{\vb{u}}^2), the KDE gradient in Rd\R^d is ∇f^h(x)=2cKnhd+2∑ig(∥x−xih∥2)(xi−x),g=−k′,\grad \hat f_h(\vb{x}) = \frac{2c_K}{n h^{d+2}}\sum_i g\Big(\Big\|\frac{\vb{x} - \vb{x}_i}{h}\Big\|^2\Big)(\vb{x}_i - \vb{x}), \qquad g = -k', and since weights gi=g(∥(x−xi)/h∥2)≥0g_i = g(\norm{(\vb{x} - \vb{x}_i)/h}^2) \ge 0 form a profile decreasing with distance, the gradient is a positive number times the weighted mean of data minus x\vb{x}:

With the Gaussian kernel, k(u)=e−u/2k(u) = e^{-u/2} and g=12kg = \tfrac12 k is proportional to kk, so weights are gi∝exp⁡(−∥x−xi∥2/2h2)g_i \propto \exp(-\norm{\vb{x} - \vb{x}_i}^2/2h^2) and the result is clean.

Proof

Identity. ∇xexp⁡(−∥x−xi∥2/2h2)=exp⁡(⋅) (xi−x)/h2\grad_{\vb{x}}\exp(-\norm{\vb{x} - \vb{x}_i}^2/2h^2) = \exp(\cdot)\,(\vb{x}_i - \vb{x})/h^2. Summing with factors 1/(n(2πh2)d/2)1/(n(2\pi h^2)^{d/2}), ∇f^h(x)=1h2 (∑if^i) (m(x)−x)\grad\hat f_h(\vb{x}) = \frac{1}{h^2}\,\big(\sum_i \hat f_i\big)\,(\vb{m}(\vb{x}) - \vb{x}) with f^i\hat f_i each datum’s contribution, summing to f^h(x)\hat f_h(\vb{x}): ∇f^h=f^hh2(m−x)\grad\hat f_h = \frac{\hat f_h}{h^2}(\vb{m} - \vb{x}), the identity.

Monotonicity (an EM step). Let ri=f^i(x)/f^h(x)r_i = \hat f_i(\vb{x})/\hat f_h(\vb{x}) be “responsibilities” (∑ri=1\sum r_i = 1). For any y\vb{y}, f^h(y)/f^h(x)=∑iri f^i(y)f^i(x)\hat f_h(\vb{y})/\hat f_h(\vb{x}) = \sum_i r_i\,\dfrac{\hat f_i(\vb{y})}{\hat f_i(\vb{x})}, and by Jensen’s inequality for logarithms (Jensen), log⁡f^h(y)−log⁡f^h(x)≥∑irilog⁡f^i(y)f^i(x)=12h2∑iri(∥x−xi∥2−∥y−xi∥2)\log\hat f_h(\vb{y}) - \log\hat f_h(\vb{x}) \ge \sum_i r_i\log\dfrac{\hat f_i(\vb{y})}{\hat f_i(\vb{x})} = \dfrac{1}{2h^2}\sum_i r_i\big(\norm{\vb{x} - \vb{x}_i}^2 - \norm{\vb{y} - \vb{x}_i}^2\big). Since ∑iri∥z−xi∥2=∥z−m∥2+const\sum_i r_i\norm{\vb{z} - \vb{x}_i}^2 = \norm{\vb{z} - \vb{m}}^2 + \text{const} with m=∑irixi=m(x)\vb{m} = \sum_i r_i\vb{x}_i = \vb{m}(\vb{x}), the right-hand side is 12h2(∥x−m∥2−∥y−m∥2)\frac{1}{2h^2}\big(\norm{\vb{x} - \vb{m}}^2 - \norm{\vb{y} - \vb{m}}^2\big). Setting y=m\vb{y} = \vb{m} yields the stated inequality. Summing over tt and since log⁡f^h\log\hat f_h is bounded above, the finite sum follows. ■\blacksquare

∎

What it does and does not say. The algorithm is stable ascent (without tuning learning rate, since geometry sets the step) and displacements tend to zero; limit points are stationary points of f^h\hat f_h. It does not say they are modes: they can be saddles, though unstable and practically reached only from exceptional points. Nor does it state speed. Carreira-Perpiñán (2007) proves Gaussian mean shift is an EM algorithm (the proof above is that Jensen bound) and analyzes its convergence: linear, with ratio near 1 (slow) for intermediate bandwidths and more favorable for very small or very large hh. Cell 4 prints the ratio between consecutive steps.

With a flat window (gg uniform in a ball of radius hh), the step is the mean of data within the window, the original version. It corresponds to ascending an Epanechnikov-kernel KDE: m(x)−x=h2d+2 ∇f^E(x)/f^G(x)\vb{m}(\vb{x}) - \vb{x} = \frac{h^2}{d+2}\,\grad\hat f_E(\vb{x})/\hat f_G(\vb{x}), with f^G\hat f_G the flat-window density (Comaniciu and Meer, 2002). Epanechnikov KDE is only continuous, not differentiable at the window edge, and with few points in the window has many spurious modes.

InteractiveParticles climbing to modes
step 0 of 40
Local KDE maxima on the grid versus h. The vertical line marks the current h.
  • particle (color shows destination cluster)
  • mode found
  • next probe step
  • probe window (h and 2h)
0.50
Kernel
Mean-shift clusters4
KDE modes (grid)4
Steps to converge (slowest particle)100
Mean displacement at this step0.2693
Probe: mean-shift step ‖m(x) − x‖0.39645
Probe: h²·‖∇f̂‖ / f̂0.39645
At h = 0.50, mean shift finds 4 clusters. The data were generated with 5. The two nearby clusters at the top left form one peak. Vary h and look at the curve below.
220 points from five Gaussian groups (two close together at upper left) on a KDE map. Each particle climbs in mean-shift steps and is colored by its destination group; large rings are modes. With h = 0.5 there are 4 groups: the two close groups are one hill. Lower h to 0.3 or 0.4 and all 5 appear; lower to 0.15 and KDE has 24 modes on the grid. Raise to 1.0 and 3 remain, to 1.2 there are 2, and at 1.3 only one. The lower curve is KDE mode count versus h: h is the clustering hyperparameter. Also inspect steps for the slowest particle: about 70 at h = 0.3, but 242 at h = 0.45, just before the pair merges. Click the map to place the probe: the magenta arrow is the next step, its length matching h²·‖∇f̂‖/f̂, the theorem's identity, with gradient computed by finite differences. Switch to flat window: much larger h is needed for stability.

The figure answers the key question: how many clusters? Mean shift does not ask for kk, but asks for hh, and hh determines how many modes KDE has. In one dimension with a Gaussian kernel this is monotone (Silverman, 1981): the number of modes of f^h\hat f_h does not grow with hh, because f^h\hat f_h as a function of h2h^2 solves the heat equation with empirical measure as initial condition, and the heat equation creates no maxima in one dimension. This yields the critical bandwidth, the smallest hh with at most kk modes, useful for testing modality. In d≥2d \ge 2 there is no such guarantee: modes can be created by smoothing. In the figure, with these data, the curve drops from 24 modes to 1 without rises. The figure also shows Carreira-Perpiñán’s predicted slowness: with h=0.45h = 0.45, the last value with 5 groups, the slowest particle needs 242 steps to converge, versus about 70 at h=0.3h = 0.3; at a bandwidth where two modes merge, the mode becomes degenerate and convergence ratio reaches 1.

What mean shift does offer over k-means: modes discover the number of groups at a given scale, groups can have arbitrary shapes (attraction basins rather than convex Voronoi regions), and there is no initialization. What it does not offer: (1) it still suffers with dimension (it is KDE); (2) cost is O(n2T)\bigO(n^2 T) for TT iterations because each step touches every datum; (3) it does not declare noise: every datum ends at a mode (the next lesson’s methods address that); and (4) one hh applies throughout space, so it cannot handle different density scales.

Connection with diffusion models. Mean shift has an exact probabilistic interpretation. If clean datum X0X_0 is chosen uniformly from the xix_i and you observe x=X0+h ε\vb{x} = X_0 + h\,\varepsilon, with ε∼N(0,I)\varepsilon \sim \Normal(\vb{0}, \mat{I}), then P(X0=xi∣x)∝exp⁡(−∥x−xi∥2/2h2)\Pr(X_0 = \vb{x}_i \given \vb{x}) \propto \exp(-\norm{\vb{x} - \vb{x}_i}^2/2h^2): these are the proof’s rir_i. Thus m(x)=E[X0∣x]\vb{m}(\vb{x}) = \E[X_0 \given \vb{x}] is the best denoiser for the empirical distribution, and m(x)−x=h2∇log⁡f^h(x)\vb{m}(\vb{x}) - \vb{x} = h^2\grad\log\hat f_h(\vb{x}) is Tweedie’s formula: the score of Gaussian-noise-smoothed density is the objective of denoising score matching and diffusion models. Mean shift is a diffusion model without a network: the exact score of a KDE.

Computational scale: trees, FFT and subsampling

Evaluating a KDE at mm points with nn data costs O(nmd)\bigO(nmd). Three ways to reduce it:

  • Trees. A tree (KD or ball tree) groups distant data and approximates their contribution in bulk with an error bound. sklearn.neighbors.KernelDensity does this with atol and rtol tolerances (Gray and Moore, 2003, develop the two-tree version). This scales to tens of thousands of data points in low or medium dimension; in high dimension trees lose their advantage, another face of the same curse.
  • Binning and FFT in one dimension. Count data on a fine grid of MM bins (O(n)\bigO(n)) and KDE is a convolution of the histogram with sampled kernel, computed by FFT in O(Mlog⁡M)\bigO(M\log M) (Silverman, 1982, algorithm AS 176). Binning moves each datum at most half a grid step, so error is negligible when that step is much smaller than hh. Cell 8 measures it.
  • Subsampling. A KDE with m≪nm \ll n randomly chosen data has the error of a sample of size mm, namely ∝m−4/5\propto m^{-4/5}. This helps with plotting or mean shift on millions of points if that error is acceptable.

For mean shift the O(n2T)\bigO(n^2T) cost is reduced by seeding from a coarse grid instead of every datum (scikit-learn’s bin_seeding) and using a tree for neighbor search. The problem is dimension rather than time: the KDE rule still applies.

Lab: from scratch and with libraries

Everything runs in the browser. The first cell implements one-dimensional Gaussian KDE with logsumexp (to avoid overflow with small hh) and compares it with SciPy and scikit-learn using bandwidth selectors.

[ ]Gaussian KDE from scratch, compared with SciPy and scikit-learnBrowser
import numpy as np
from scipy.special import logsumexp
from scipy.stats import gaussian_kde, norm
from sklearn.neighbors import KernelDensity

rng = np.random.default_rng(12)
# La misma mezcla bimodal de los interactivos: 0.45 N(-0.9, 0.55^2) + 0.55 N(0.7, 0.5^2)
W, M, S = np.array([0.45, 0.55]), np.array([-0.9, 0.7]), np.array([0.55, 0.5])
def true_pdf(x):
    return sum(w * norm.pdf(x, m, s) for w, m, s in zip(W, M, S))

n = 150
comp = rng.choice(2, size=n, p=W)
X = rng.normal(M[comp], S[comp])

def kde_logpdf(x_eval, X, h):
    """log f̂(x) = logsumexp_i(-(x - x_i)^2 / 2h^2) - log(n h sqrt(2 pi))"""
    z = (x_eval[:, None] - X[None, :]) / h
    return logsumexp(-0.5 * z**2, axis=1) - np.log(len(X) * h * np.sqrt(2 * np.pi))

grid = np.linspace(-3.5, 3.5, 281)
h = 0.3
mine = np.exp(kde_logpdf(grid, X, h))
sc = gaussian_kde(X, bw_method=h / X.std(ddof=1))(grid)          # scipy: h = factor * desviación típica
sk = np.exp(KernelDensity(bandwidth=h).fit(X[:, None]).score_samples(grid[:, None]))
print("max |mía - scipy|   =", np.abs(mine - sc).max())
print("max |mía - sklearn| =", np.abs(mine - sk).max())
print("integral de f̂ en [-3.5, 3.5]:", round(float(mine.sum() * (grid[1] - grid[0])), 4))

The second cell compares likelihood measured on the data themselves (escaping as h→0h \to 0) with leave-one-out likelihood, and applies four selectors to the same sample. It uses the previous cell’s sample.

[ ]Leave-one-out cross-validation: why each datum must be left outBrowser
def loo_loglik(X, h):
    n = len(X)
    L = -0.5 * ((X[:, None] - X[None, :]) / h) ** 2
    np.fill_diagonal(L, -np.inf)                                  # el punto no se cuenta a sí mismo
    return np.mean(logsumexp(L, axis=1) - np.log((n - 1) * h * np.sqrt(2 * np.pi)))

def insample_loglik(X, h):
    return np.mean(kde_logpdf(X, X, h))

print("  h      en la muestra   leave-one-out")
for hh in [0.005, 0.02, 0.05, 0.1, 0.2, 0.3, 0.5, 1.0]:
    print(f"{hh:6.3f}  {insample_loglik(X, hh):12.3f}  {loo_loglik(X, hh):12.3f}")

hs = np.geomspace(0.03, 1.5, 60)
h_cv = hs[np.argmax([loo_loglik(X, hh) for hh in hs])]
sd, iqr = X.std(ddof=1), np.subtract(*np.percentile(X, [75, 25]))
h_ref = (4 / 3) ** 0.2 * sd * n ** -0.2
h_silv = 0.9 * min(sd, iqr / 1.34) * n ** -0.2
ise = lambda hh: np.sum((np.exp(kde_logpdf(grid, X, hh)) - true_pdf(grid)) ** 2) * (grid[1] - grid[0])
h_or = hs[np.argmin([ise(hh) for hh in hs])]
print(f"\nn = {n}")
for nombre, hh in [("regla normal", h_ref), ("Silverman", h_silv), ("validación cruzada", h_cv), ("oráculo (mín. ISE)", h_or)]:
    print(f"{nombre:20s} h = {hh:.3f}   ISE = {ise(hh):.5f}")

In-sample likelihood keeps improving as hh falls (from −1.281-1.281 at h=0.3h = 0.3 to −0.292-0.292 at h=0.005h = 0.005), while leave-one-out plunges (−6.325-6.325 at h=0.005h = 0.005) and peaks around h=0.3h = 0.3 (−1.312-1.312). On this sample cross-validation chooses h=0.268h = 0.268, with ISE 0.00365, between the normal rule (0.00625 at h=0.364h = 0.364) and the oracle (0.00339 at h=0.234h = 0.234). This is one sample: results vary, and the benchmark below averages them.

The third cell covers the kk-neighbor estimator and divergence of its mass.

[ ]k neighbors: f̂ mass grows with range sizeBrowser
rng = np.random.default_rng(2)
n, k = 200, 10
Xn = rng.normal(size=n)

def knn_density(x, X, k):
    """f̂(x) = k / (2 n R_k(x)) en 1D, con R_k la distancia al k-ésimo vecino."""
    d = np.abs(x[:, None] - X[None, :])
    r = np.partition(d, k - 1, axis=1)[:, k - 1]
    return k / (2 * len(X) * r)

def integral(xs):
    f = knn_density(xs, Xn, k)
    return np.sum(0.5 * (f[1:] + f[:-1]) * np.abs(np.diff(xs)))

lo, hi = Xn.min(), Xn.max()
centro = integral(np.linspace(lo, hi, 4001))
print(f"masa en [mín, máx] de la muestra: {centro:.3f}")
for L in [10, 1e3, 1e5, 1e7]:
    cola_d = integral(hi + np.geomspace(1e-6, L, 4000))      # cola derecha, rejilla geométrica (f̂ decae como 1/x)
    cola_i = integral(lo - np.geomspace(1e-6, L, 4000))
    print(f"colas hasta ±{L:9.0e}: masa total = {centro + cola_d + cola_i:.3f}")
print(f"crecimiento por década y por cola, teórico k/(2n)·ln 10 = {k / (2 * n) * np.log(10):.4f}")

Mass exceeds 1 even within the data range (1.079) and, extending tails from ±10\pm 10 to ±107\pm 10^7, rises from 1.211 to 1.898: each length decade adds about 0.115, the 2⋅0.05762 \cdot 0.0576 of two tails with theoretical value k2nln⁡10\frac{k}{2n}\ln 10 per tail. It does not converge: this is the previous section’s logarithmic divergence. Now mean shift: implement it using the weighted mean, check theorem monotonicity and compare with sklearn.cluster.MeanShift.

[ ]Mean shift from scratch and with scikit-learnBrowser
from sklearn.cluster import MeanShift
from sklearn.metrics import adjusted_rand_score

rng = np.random.default_rng(1204)
centros = np.array([[-2.1, 0.9], [-0.7, 1.2], [1.9, 1.4], [0.9, -1.7], [-2.0, -1.7]])
sig = np.array([0.4, 0.35, 0.5, 0.45, 0.35])
tam = np.array([50, 40, 55, 45, 30])
P2 = np.vstack([c + s * rng.normal(size=(k, 2)) for c, s, k in zip(centros, sig, tam)])
y = np.repeat(np.arange(5), tam)

def log_kde(P, X, h):
    d2 = ((P[:, None, :] - X[None, :, :]) ** 2).sum(-1)
    return logsumexp(-0.5 * d2 / h**2, axis=1) - np.log(len(X) * 2 * np.pi * h**2)

def mean_shift(X, h, max_iter=1000, tol=1e-5, merge=0.25):
    """Mean shift gaussiano: cada punto sube a su moda; los destinos a menos de merge*h se funden."""
    P = X.copy()
    pasos, logf = [], []
    for _ in range(max_iter):
        d2 = ((P[:, None, :] - X[None, :, :]) ** 2).sum(-1)
        w = np.exp(-0.5 * d2 / h**2)
        nuevo = (w @ X) / w.sum(1, keepdims=True)                 # m(x): media ponderada de los datos
        pasos.append(np.linalg.norm(nuevo - P, axis=1).max())
        P = nuevo
        logf.append(log_kde(P, X, h))
        if pasos[-1] < tol:
            break
    modas, etiqueta = [], np.empty(len(X), dtype=int)
    for i, p in enumerate(P):
        for j, m in enumerate(modas):
            if np.linalg.norm(p - m) < merge * h:
                etiqueta[i] = j
                break
        else:
            modas.append(p)
            etiqueta[i] = len(modas) - 1
    return etiqueta, np.array(modas), np.array(pasos), np.array(logf)

for h in [0.3, 0.5, 1.0, 1.5]:
    lab, modas, pasos, logf = mean_shift(P2, h)
    print(f"h = {h:4.2f}: {len(modas)} grupos, {len(pasos)} iteraciones hasta un paso < 1e-5, ARI con los 5 grupos reales = {adjusted_rand_score(y, lab):.3f}")

lab, modas, pasos, logf = mean_shift(P2, 0.5)
print("\nlog f̂ de cada partícula no baja en ningún paso:", bool(np.all(np.diff(logf, axis=0) >= -1e-12)))
print("razón entre pasos consecutivos al final (convergencia lineal):", np.round(pasos[-4:][1:] / pasos[-4:][:-1], 3))

ms = MeanShift(bandwidth=0.8).fit(P2)
print(f"\nsklearn MeanShift (ventana plana, bandwidth=0.8): {len(ms.cluster_centers_)} grupos, ARI = {adjusted_rand_score(y, ms.labels_):.3f}")

With h=0.3h = 0.3 all 5 groups appear (ARI 0.899, not 1: groups overlap slightly at edges), with h=0.5h = 0.5 there are 4 (ARI 0.778: the pair is one hill), with h=1.0h = 1.0 there are 3 (ARI 0.542) and with h=1.5h = 1.5 just one (ARI 0). Note iterations: 114 with h=0.3h = 0.3 versus 43 at h=0.5h = 0.5 and 26 at h=1.0h = 1.0. With small and intermediate bandwidths convergence is slower, as Carreira-Perpiñán predicts, and slower still near hh values where two modes merge (the figure shows the nearby pair). Each particle’s log density never falls, as the theorem states, and the final ratio between consecutive steps is constant, 0.73: linear convergence. Scikit-learn’s MeanShift uses a flat window and merges centers less than bandwidth apart, obtaining 4 groups with bandwidth=0.8 (ARI 0.778, like ours at h=0.5h = 0.5). Group count depends on hh in both implementations.

The second part of the lab benchmarks reference rules against cross-validation.

[ ]Reference rules versus cross-validation on four densitiesBrowser
import time
from scipy.stats import lognorm, t as student

SQ2PI = np.sqrt(2 * np.pi)
n, R = 150, 8
hs = np.geomspace(0.02, 2.0, 28)

def mix_pdf(x):
    return 0.5 * norm.pdf(x, -1, 2 / 3) + 0.5 * norm.pdf(x, 1, 2 / 3)

def mix_rvs(g, size):
    c = g.integers(0, 2, size)
    return g.normal(np.where(c == 0, -1, 1), 2 / 3)

DENS = {
    "gaussiana": (norm.pdf, lambda g, s: g.normal(size=s), np.linspace(-4.5, 4.5, 360)),
    "bimodal": (mix_pdf, mix_rvs, np.linspace(-4, 4, 360)),
    "lognormal": (lambda x: lognorm.pdf(x, 0.8), lambda g, s: g.lognormal(0, 0.8, s), np.linspace(0.005, 12, 480)),
    "t de Student (3 g.l.)": (lambda x: student.pdf(x, 3), lambda g, s: g.standard_t(3, s), np.linspace(-12, 12, 480)),
}

def kde(grid, X, h):
    z = (grid[:, None] - X[None, :]) / h
    return np.exp(-0.5 * z**2).sum(1) / (len(X) * h * SQ2PI)

def loo(D2, h):
    L = -0.5 * D2 / h**2
    np.fill_diagonal(L, -np.inf)
    return np.mean(logsumexp(L, axis=1)) - np.log((len(D2) - 1) * h * SQ2PI)

def lscv(D2, h):
    m = len(D2)
    a = np.exp(-0.25 * D2 / h**2).sum() / (2 * h * np.sqrt(np.pi)) / m**2         # ∫ f̂² (núcleos de anchura sqrt(2) h)
    K = np.exp(-0.5 * D2 / h**2) / (h * SQ2PI)
    return a - 2 * (K.sum() - m * K[0, 0]) / (m * (m - 1))                          # 2/n ∑ f̂_{-i}(x_i)

def ise(est, truth, grid):
    return np.sum((est - truth) ** 2) * (grid[1] - grid[0])

g = np.random.default_rng(7)
t0 = time.time()
filas = []
for nombre, (pdf, rvs, grid) in DENS.items():
    truth = pdf(grid)
    acum = {k: [] for k in ["normal", "Silverman", "CV verosimilitud", "CV mín. cuadrados", "oráculo"]}
    hacum = {k: [] for k in acum}
    for _ in range(R):
        X = rvs(g, n)
        D2 = (X[:, None] - X[None, :]) ** 2
        sd, iqr = X.std(ddof=1), np.subtract(*np.percentile(X, [75, 25]))
        eleg = {"normal": 1.06 * sd * n**-0.2, "Silverman": 0.9 * min(sd, iqr / 1.34) * n**-0.2}
        eleg["CV verosimilitud"] = hs[np.argmax([loo(D2, h) for h in hs])]
        eleg["CV mín. cuadrados"] = hs[np.argmin([lscv(D2, h) for h in hs])]
        ises = [ise(kde(grid, X, h), truth, grid) for h in hs]
        eleg["oráculo"] = hs[np.argmin(ises)]
        for k, h in eleg.items():
            acum[k].append(ise(kde(grid, X, h), truth, grid))
            hacum[k].append(h)
    filas.append((nombre, acum, hacum))
print(f"n = {n}, {R} réplicas. ISE medio / ISE medio del oráculo (entre paréntesis, h medio ± desviación)")
cols = ["normal", "Silverman", "CV verosimilitud", "CV mín. cuadrados"]
print(f"{'':24s}" + "".join(f"{k:>26s}" for k in cols))
for nombre, acum, hacum in filas:
    orc = np.mean(acum["oráculo"])
    print(f"{nombre:24s}" + "".join(f"{np.mean(acum[k]) / orc:8.2f} (h={np.mean(hacum[k]):.2f}±{np.std(hacum[k]):.2f})" for k in cols) + f"   oráculo: ISE={orc:.4f}, h={np.mean(hacum['oráculo']):.2f}")

Each row is a density and each column a selector. Numbers are mean ISE divided by the oracle’s (the best grid hh for that same sample), so 1.00 would be perfect. With only 8 replications, 10% or 20% differences between columns are noise; large contrasts are what hold:

  • On the Gaussian, all selectors lie between 1.2 and 1.6, and the normal rule, exact for this family, is best (1.20).
  • On the bimodal mixture (with modes farther apart than in the interactives), likelihood cross-validation and Silverman’s rule reach 1.04 and 1.06. The normal rule, at 1.16, uses a larger hh (0.47 versus the oracle’s 0.34): dispersion created by two modes inflates σ^\hat\sigma.
  • On the lognormal, selectors based on standard deviation scale (normal rule, 3.38; likelihood CV, 3.09) lose by a factor of 3: the peak near 0 needs much smaller hh (the oracle’s is 0.15). Silverman’s minimum of σ^\hat\sigma and IQR/1.34\mathrm{IQR}/1.34 holds up (1.62), and least-squares cross-validation with h=0.19h = 0.19 is best (1.23).
  • On Student’s tt with 3 degrees of freedom, likelihood CV chooses h=0.82±0.38h = 0.82 \pm 0.38, twice the oracle (0.41), and loses by a factor of 3.57: the previous section’s heavy-tail inconsistency. LSCV is 3.98 with mean hh 0.37 but high dispersion (standard deviation 0.20), the variability theory predicted; Silverman at 1.23 is best in this row.

No column wins all four rows: there is no universal selector, so compare at least two.

[ ]Bounded support: reflection and logarithmic transformationBrowser
n, R = 150, 12
grid = np.linspace(0.005, 12, 480)
truth = lognorm.pdf(grid, 0.8)
hs = np.geomspace(0.02, 2.0, 28)

def kde1(x, X, h):
    z = (x[:, None] - X[None, :]) / h
    return np.exp(-0.5 * z**2).sum(1) / (len(X) * h * SQ2PI)

def loo1(X, h):
    L = -0.5 * ((X[:, None] - X[None, :]) / h) ** 2
    np.fill_diagonal(L, -np.inf)
    return np.mean(logsumexp(L, axis=1)) - np.log((len(X) - 1) * h * SQ2PI)

ise_ln = lambda est: np.sum((est - truth) ** 2) * (grid[1] - grid[0])
g = np.random.default_rng(3)
res = {"directa": [], "reflexión en 0": [], "log + vuelta": []}
fuga = []
for _ in range(R):
    X = g.lognormal(0, 0.8, n)
    h = 1.06 * X.std(ddof=1) * n**-0.2                              # regla normal sobre la escala original
    res["directa"].append(ise_ln(kde1(grid, X, h)))
    fuga.append(norm.cdf(-X / h).mean())                            # masa de f̂ en x < 0
    res["reflexión en 0"].append(ise_ln(kde1(grid, X, h) + kde1(-grid, X, h)))
    Y = np.log(X)
    hy = hs[np.argmax([loo1(Y, hh) for hh in hs])]                  # validación cruzada en la escala log
    res["log + vuelta"].append(ise_ln(kde1(np.log(grid), Y, hy) / grid))
print(f"lognormal(0, 0.8), n = {n}, {R} réplicas: regla normal (directa y reflexión) y CV en la escala log")
for k, v in res.items():
    print(f"{k:16s} ISE medio = {np.mean(v):.4f}")
print(f"masa media de la KDE directa en x < 0: {np.mean(fuga):.3f}")

With normal-rule hh on the original scale, direct KDE of 150 lognormal data points has mean ISE 0.0404 and puts 6.6% of mass at x<0x < 0. Reflection removes the leak but does not improve ISE (0.0451): it does not fix h=1.06 σ^ n−1/5h = 1.06\,\hat\sigma\,n^{-1/5} being too large for a lognormal peak (in the previous benchmark the oracle used h=0.15h = 0.15 versus the rule’s 0.49). Log transformation with hh selected by cross-validation on the log scale reduces ISE to 0.0122, three times lower.

[ ]Multivariate KDE: standardize or whitenBrowser
def kde_logpdf_nd(E, X, h):
    d = X.shape[1]
    d2 = ((E[:, None, :] - X[None, :, :]) ** 2).sum(-1)
    return logsumexp(-0.5 * d2 / h**2, axis=1) - np.log(len(X)) - d * np.log(h * np.sqrt(2 * np.pi))

def loo_nd(X, h):
    d = X.shape[1]
    L = -0.5 * ((X[:, None, :] - X[None, :, :]) ** 2).sum(-1) / h**2
    np.fill_diagonal(L, -np.inf)
    return np.mean(logsumexp(L, axis=1)) - np.log(len(X) - 1) - d * np.log(h * np.sqrt(2 * np.pi))

g = np.random.default_rng(11)
def muestra(m):
    z = g.normal(size=(m, 2))
    return np.c_[z[:, 0], 100 * (0.9 * z[:, 0] + np.sqrt(1 - 0.81) * z[:, 1])]    # escalas 1 y 100, correlación 0.9
Xtr, Xte = muestra(300), muestra(1000)

mu, C = Xtr.mean(0), np.cov(Xtr.T)
sd2 = np.sqrt(np.diag(C))
Lc = np.linalg.cholesky(C)
trans = {
    "isótropa sobre los datos crudos": (lambda X: X, 0.0),
    "estandarizada (una escala por variable)": (lambda X: (X - mu) / sd2, -np.log(sd2).sum()),
    "blanqueada (covarianza completa)": (lambda X: np.linalg.solve(Lc, (X - mu).T).T, -np.log(np.diag(Lc)).sum()),
}
verdadera = -(np.log(2 * np.pi * np.e) + 0.5 * np.log(100.0**2 * (1 - 0.81)))        # menos la entropía de la gaussiana real
print(f"log-verosimilitud media de test del modelo verdadero: {verdadera:.3f}")
for nombre, (f, jac) in trans.items():
    Ztr, Zte = f(Xtr), f(Xte)
    hs = Ztr.std(0).mean() * np.geomspace(0.03, 1.5, 24)
    h = hs[np.argmax([loo_nd(Ztr, hh) for hh in hs])]
    print(f"{nombre:42s} h = {h:8.3f}   {kde_logpdf_nd(Zte, Ztr, h).mean() + jac:8.3f}")

The true model (a bivariate Gaussian) would have mean test log likelihood −6.613-6.613. The best isotropic KDE on raw data reaches −8.815-8.815, with h=3.938h = 3.938 compromising between a variable of scale 1 and one of scale 100. Standardizing each variable raises it to −6.734-6.734, and whitening with full covariance to −6.673-6.673, only 0.06 nats per datum from the true model. With correlation 0.9, standardization still leaves a round kernel on a diagonally elongated cloud, and whitening corrects this.

[ ]Scale: binned FFT KDE versus direct and tree evaluationBrowser
from sklearn.neighbors import KernelDensity

g = np.random.default_rng(5)
N, Mg = 20000, 1024
c = g.integers(0, 2, N)
Xb = g.normal(np.where(c == 0, -0.9, 0.7), np.where(c == 0, 0.55, 0.5))
h = 0.1
gr = np.linspace(-4, 4, Mg)

t0 = time.time()
directa = np.exp(-0.5 * ((gr[:, None] - Xb[None, :]) / h) ** 2).sum(1) / (N * h * np.sqrt(2 * np.pi))
t_dir = time.time() - t0

t0 = time.time()
delta = gr[1] - gr[0]
cuentas, _ = np.histogram(Xb, bins=Mg, range=(gr[0] - delta / 2, gr[-1] + delta / 2))          # binado: O(N)
d = np.arange(-Mg, Mg) * delta
nucleo = np.exp(-0.5 * (d / h) ** 2) / (h * np.sqrt(2 * np.pi))                                # núcleo muestreado
Lf = 4096
conv = np.fft.irfft(np.fft.rfft(cuentas, Lf) * np.fft.rfft(nucleo, Lf), Lf)[Mg:2 * Mg] / N     # convolución por FFT: O(M log M)
t_fft = time.time() - t0

t0 = time.time()
arbol = KernelDensity(bandwidth=h, kernel="gaussian", rtol=1e-4).fit(Xb[:, None])
sk = np.exp(arbol.score_samples(gr[:, None]))
t_sk = time.time() - t0

print(f"N = {N}, {Mg} puntos de evaluación, h = {h}")
print(f"directa:        {t_dir:.3f} s")
print(f"binada + FFT:   {t_fft:.4f} s   error máximo {np.abs(conv - directa).max():.2e}  (pico de f̂: {directa.max():.3f})")
print(f"KernelDensity (árbol, rtol=1e-4): {t_sk:.3f} s   error máximo {np.abs(sk - directa).max():.2e}")

Both approximations reproduce direct evaluation: binned FFT with maximum error 2.3⋅10−42.3 \cdot 10^{-4} (0.06% of the peak, 0.403), and the tree with rtol=1e-4 with error 1.7⋅10−51.7 \cdot 10^{-5}. FFT is orders of magnitude faster than direct evaluation, moving from n mn\,m kernel evaluations to a 40964096-point FFT; the tree also beats direct evaluation in this run, but its advantage depends on tolerance and dimension.

Common mistakes

Exercises

ProofBias and variance of the KDE derivative
Prove: Mean shift follows the KDE gradient, so it is useful to know how well f^h\hat f_h estimates derivative f′f'. In one dimension with Gaussian kernel KK, f^h′(x)=1nh2∑iK′(x−Xih)\hat f_h'(x) = \frac{1}{nh^2}\sum_i K'\big(\frac{x - X_i}{h}\big). Suppose f′′′f''' is continuous, bounded and square-integrable, h→0h \to 0 and nh3→∞nh^3 \to \infty. Repeat the theorem's analysis to obtain asymptotic bias and variance of f^h′(x)\hat f_h'(x) and bandwidth minimizing its AMISE, ∫E[(f^h′−f′)2]\int \E[(\hat f_h' - f')^2].
0
Follow the theorem proof: substitute y=x−huy = x - hu, integrate by parts to remove the kernel derivative, use Taylor and symmetry of KK.

Step 1 of 4. What is E[f^h′(x)]\E[\hat f_h'(x)]?

ProofFrom AMISE to optimal bandwidth in dimension $d$
Prove: Suppose in dimension dd with a second-order kernel, pointwise KDE bias is O(h2)\bigO(h^2) and variance is O(1/(nhd))\bigO\big(1/(nh^d)\big), so AMISE(h)=A h4+B/(nhd)\mathrm{AMISE}(h) = A\,h^4 + B/(n h^d) with constants A,B>0A, B > 0. Prove the minimizing hh decreases as n−1/(d+4)n^{-1/(d+4)} and optimal AMISE decays as n−4/(d+4)n^{-4/(d+4)}.
0
Differentiate with respect to hh, set to zero and substitute. For the rate, observe the proportion between bias and variance at optimum.

Step 1 of 4. Differentiate AMISE(h)=Ah4+Bn−1h−d\mathrm{AMISE}(h) = A h^4 + B n^{-1} h^{-d} with respect to hh and set to zero. What equation results?

NumericThe normal reference rule
Apply the normal reference rule h=1.06 σ n−1/5h = 1.06\,\sigma\,n^{-1/5} with σ=2\sigma = 2 and n=1000n = 1000. What is hh?
ProofGaussian mean shift is gradient ascent
Prove: With a Gaussian kernel in Rd\R^d, f^h(x)=1n(2πh2)d/2∑ie−∥x−xi∥2/2h2\hat f_h(\vb{x}) = \frac{1}{n(2\pi h^2)^{d/2}}\sum_i e^{-\norm{\vb{x} - \vb{x}_i}^2/2h^2}. Prove the mean-shift update x←m(x)\vb{x} \leftarrow \vb{m}(\vb{x}), with m\vb{m} the data mean weighted by wi=e−∥x−xi∥2/2h2w_i = e^{-\norm{\vb{x} - \vb{x}_i}^2/2h^2}, is a gradient step on f^h\hat f_h with step size h2/f^h(x)h^2/\hat f_h(\vb{x}).
0
Calculate the gradient of one term and recognize the weighted mean in the sum.

Step 1 of 4. What is ∇x e−∥x−xi∥2/2h2\grad_{\vb{x}}\,e^{-\norm{\vb{x} - \vb{x}_i}^2/2h^2}?

NumericOne mean-shift step by hand
Three data points on a line: 00, 11 and 44. With a Gaussian kernel and h=1h = 1, what is m(x)m(x) at x=1x = 1 (one mean-shift step from the central point)?
CodeLeave-one-out bandwidth cross-validation
Implement loo_log_likelihood(X, h), returning the per-datum mean of log⁡f^h,−i(xi)\log\hat f_{h,-i}(x_i) for a one-dimensional Gaussian KDE (each f^h,−i\hat f_{h,-i} is constructed from the other n−1n-1 points), and select_bandwidth(X, hs), returning the element of grid hs maximizing it. Use logsumexp to avoid overflow.
import numpy as np
from scipy.special import logsumexp

def loo_log_likelihood(X, h):
  """Media por dato de log f̂_{h,-i}(x_i), con la KDE gaussiana de n-1 datos."""
  X = np.asarray(X, dtype=float)
  # tu código
  return 0.0

def select_bandwidth(X, hs):
  """Devuelve el h de la rejilla hs que maximiza loo_log_likelihood."""
  # tu código
  return float(hs[0])
Shift+Enter to run
QuizWhy likelihood on the same data always chooses small h
You maximize 1n∑ilog⁡f^h(Xi)\frac1n\sum_i\log\hat f_h(X_i) over hh, using the same XiX_i defining f^h\hat f_h (Gaussian kernel). What happens and why?
NumericHow much AMISE falls with more data
In dimension d=4d = 4 with optimal bandwidth, AMISE decays as n−4/(4+d)n^{-4/(4+d)}. If you multiply the number of data points by 10001000, by what factor is AMISE divided?
QuizWhat the k-neighbor estimator says
With fixed kk and nn data in R\R, which claim about f^k(x)=k/(2nRk(x))\hat f_k(x) = k/(2nR_k(x)) is correct?
QuizPositive long-tailed data
You estimate latency density (positive and long-tailed). Gaussian KDE puts around 7% of its mass at negative values and flattens the peak near 0. What do you do?
QuizVariables on different scales
You have two correlated variables with standard deviations 1 and 100, and fit Gaussian KDE with a common hh chosen by leave-one-out cross-validation. What do you expect compared with standardizing or whitening first?

Summary

Key idea
Nonparametric density estimation places a small smoothed mass at each datum and its error is a tradeoff: bias grows with h2h^2 and is largest at peaks and valleys, while variance decreases with nhnh and is relatively larger in tails. Optimal bandwidth scales as n−1/5n^{-1/5} and error as n−4/5n^{-4/5} in one dimension, but as n−4/(4+d)n^{-4/(4+d)} in dimension dd, the curse of dimensionality in its clearest form. Reference rules assume normality and oversmooth nearby modes; leave-one-out cross-validation estimates KL and is not fooled by its own sample, but suffers with heavy tails and repeated data. Mean shift is gradient ascent on log⁡f^h\log\hat f_h with step h2h^2, does not decrease density and converges to stationary points; it clusters by attraction basins, so hh, not kk, is the real clustering hyperparameter. The same step is the smoothed-density score learned by diffusion models.