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 , 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 ‘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 : require 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 as in a parametric problem, but as in one dimension and in dimension .
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; -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 in and estimator , global error is integrated squared error and its expectation . By the mean squared error decomposition, at each point , and MISE is the integral of that sum.
Histograms: the simplest estimator already contains the whole problem
Divide the line into intervals (bins) of width and origin . Probability of is , estimated by the fraction of data falling in it. Distributing that mass uniformly within the bin yields the estimator.
Since , mean and variance follow directly. Let be the center of bin . For :
The first equality is a Taylor expansion of around (Taylor in one variable): . Bias is order , not : it depends on where falls in its bin and the slope of there. Integrating the square, with uniform on and thus mean square , and writing (the roughness of ):
Here AMISE is asymptotic MISE (leading terms as and ), and 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 . Second, rate is worse than the obtained with smooth kernels, precisely because of the steps: a piecewise-constant estimator has order- rather than order- bias. For a normal distribution, and , Scott’s rule (1979).
Besides its slow rate there are two defects familiar from any histogram: the result depends on origin (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 with a histogram bin centered at , count data at distance less than from . 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 copies of the kernel, one centered on each datum and all weighted . It inherits good properties from : if , is a density (), and is as smooth as (with the Gaussian it is infinitely differentiable). Common kernels:
| Kernel | Efficiency | |||
|---|---|---|---|---|
| Epanechnikov | on | |||
| Biweight | on | |||
| Triangular | on | |||
| Gaussian | ||||
| Uniform | on |
Efficiency is the ratio of sample sizes at which two kernels reach the same optimal AMISE (below you will see it follows from ): the Gaussian kernel needs 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 loses an order of magnitude.
An interpretation useful twice: is the convolution of empirical measure with (density convolution): it is the density of , where you choose a random datum and add noise . And in expectation, : the estimator is systematically blurred by that kernel. This produces bias, so bias does not disappear as grows with fixed .
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 , the next section’s AMISE is times optimum: 3.6 times with and 1.6 with , because squared bias grows as and variance only as ; (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 (), the normal rule gives , and the KDE of the expected density ceases to have two modes when ; this happens for . 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 is , clearly below.
Asymptotic analysis: bias, variance and optimal bandwidth
Now the analysis explaining the valley. Complete assumptions: is twice differentiable with continuous, bounded, square-integrable ; is a bounded kernel as defined; and bandwidth satisfies and (data must fill each window of width ).
Proof
Bias. Substituting , . Second-order Taylor: , with uniform remainder since is continuous and bounded. Since and (symmetry), this gives .
Variance. is the mean of iid variables , so . With the same substitution, , and . Then , and since , .
Integrate and minimize. and, since , . Differentiating AMISE, , giving . At the optimum, the bias term is one quarter of the variance term ( gives of that value), so , the stated formula. To compare kernels, , giving table efficiency .
∎What the theorem says, without overreaching:
- Bias is . At a peak and KDE lies below (flattens the top); in a valley and it lies above (fills it). Bias grows with and does not depend on .
- Variance is proportional to and decreases with . In absolute terms it is greater where density is higher, at peaks. What explodes in tails is relative variance: grows as , 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 : slower than for a parametric estimator. With a positive kernel it gets no better; higher-order kernels (with ) improve the rate, but cease to be densities and the estimate can be negative.
- depends on , the roughness of the density to estimate: densities with narrow peaks need small . It is unknown, motivating all the next section’s selection methods.
One detail in the figure qualifies the theorem: is asymptotic. At moderate , 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 as an exact law to extrapolate bandwidth from a small sample to a large one without recalculation.
Bandwidth selection
Choosing 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 in the theorem with that of a normal distribution with the data’s standard deviation, . With a Gaussian kernel this gives . Silverman’s rule (1986) uses : factor 0.9 and the minimum provide some protection against bimodality or outliers. In dimensions, Scott gives for each coordinate, and Silverman multiplies by (returning to at ). They cost one line and are exact if is normal. Terrell (1990) provides context: for any density of variance , AMISE with Gaussian kernel does not exceed , so is near that ceiling: these rules err on the high side (oversmooth) when has more structure than a normal distribution, and nearby modes are the first thing lost.
Likelihood cross-validation. Evaluate each using each datum’s likelihood under the estimator constructed without it:
Proof
is independent of the other data points, on which depends. Conditioning on them, . Take expectations; all terms have the same expectation because is the KDE of iid data.
∎Notice why the datum must be left out. In sample, includes the datum’s own term, worth . Then as : likelihood evaluated on data defining the estimate has no maximum and escapes toward the smallest , a delta peak on each datum. (Cell 2 prints this.) KL also severely penalizes places where is near zero and data exist: with heavy tails and a light-tailed kernel, extremes drag to overly large values (Schuster and Gregory, 1981, study this inconsistency). Cell 5 shows it with a Student .
Least-squares cross-validation. Target ISE directly: , with the last term independent of , and estimate by . With a Gaussian kernel the first term has closed form, and
where is the 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 converges to at relative rate (Hall and Marron, 1987), sometimes with multiple local minima. Second-generation plug-in selectors, such as Sheather and Jones (1991), estimate with another bandwidth and reach ; 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 because the window is cut off. Two common remedies. Reflection mirrors data at the boundary, for : it loses no mass, but forces and thus remains biased of order near 0 if . Transformation: estimate with (on the whole line) and transform back, , 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 , with a symmetric positive-definite bandwidth matrix . Gaussian kernel and (isotropic) are common, but dangerous: the same in every direction makes sense only when scales are comparable. If one variable is measured in thousands and another in units, an small enough for the second is ridiculously narrow for the first, and an appropriate for the first erases the second. Two solutions: standardize each variable (one per coordinate, Scott’s rule), or whiten using sample covariance, with , and use isotropic in ; SciPy does this by default in gaussian_kde, using . Cell 7 shows the difference in test likelihood.
The same analysis, with in dimensions, gives bias and variance : a window of side in contains a fraction of mass, not . AMISE is , minimized at For this is the previous . To divide error by 10 you must multiply by : with , but with . 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 are needed for relative mean squared error of Gaussian KDE at the origin, with the best possible , to be 0.1. Error has closed form (bias , and variance follows from ), which the figure calculates exactly.
Two reading clarifications. First, this is a best-case result: optimal , Gaussian , one point (the origin). Rougher or evaluation in a tail is worse. Second, the exponent uses the dimension in which data have mass at scale . If data live near a manifold of dimension (intrinsic dimension, lesson 1), , not , matters at small scales; but if ambient noise is wider than , ambient dimension counts again. And if data lie exactly on the manifold, no density exists with respect to Lebesgue measure on : KDE merely draws increasingly narrow ridges as falls.
-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 is approximately , with the unit-ball volume. If the smallest ball centered at containing of the data points has radius , its probability is of order ; solving gives:
This is a uniform-kernel KDE with variable bandwidth, : 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, and , whose integral over is proportional to , which diverges (logarithmically). It is not a density. Cell 3 measures this: with , , mass inside the data range is already 1.079 and each tail decade adds more.
- It is not smooth: is not differentiable where the counted neighbor changes, so has corners and mean shift or another gradient method has no gradient to follow there.
- Consistency. Convergence requires and . Pointwise squared error is of order (squared bias plus relative variance, Mack and Rosenblatt, 1979), minimized at and giving the same as KDE: local scale adjustment does not improve the rate, only the allocation of error. Rule 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 -NN classification (the ratio of two such class densities). Distance to the th 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 .
Mean shift: climb density to its modes
Now use what you built for clustering. If estimates well, modes of are group centers and each datum belongs to the hill it climbs. An algorithm is still needed to climb. With radial kernel , the KDE gradient in is and since weights form a profile decreasing with distance, the gradient is a positive number times the weighted mean of data minus :
With the Gaussian kernel, and is proportional to , so weights are and the result is clean.
Proof
Identity. . Summing with factors , with each datum’s contribution, summing to : , the identity.
Monotonicity (an EM step). Let be “responsibilities” (). For any , , and by Jensen’s inequality for logarithms (Jensen), . Since with , the right-hand side is . Setting yields the stated inequality. Summing over and since is bounded above, the finite sum follows.
∎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 . 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 . Cell 4 prints the ratio between consecutive steps.
With a flat window ( uniform in a ball of radius ), the step is the mean of data within the window, the original version. It corresponds to ascending an Epanechnikov-kernel KDE: , with 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.
The figure answers the key question: how many clusters? Mean shift does not ask for , but asks for , and determines how many modes KDE has. In one dimension with a Gaussian kernel this is monotone (Silverman, 1981): the number of modes of does not grow with , because as a function of 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 with at most modes, useful for testing modality. In 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 , the last value with 5 groups, the slowest particle needs 242 steps to converge, versus about 70 at ; 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 for 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 applies throughout space, so it cannot handle different density scales.
Connection with diffusion models. Mean shift has an exact probabilistic interpretation. If clean datum is chosen uniformly from the and you observe , with , then : these are the proof’s . Thus is the best denoiser for the empirical distribution, and 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 points with data costs . 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.KernelDensitydoes this withatolandrtoltolerances (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 bins () and KDE is a convolution of the histogram with sampled kernel, computed by FFT in (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 . Cell 8 measures it.
- Subsampling. A KDE with randomly chosen data has the error of a sample of size , namely . This helps with plotting or mean shift on millions of points if that error is acceptable.
For mean shift the 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 ) and compares it with SciPy and scikit-learn using bandwidth selectors.
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 ) with leave-one-out likelihood, and applies four selectors to the same sample. It uses the previous cell’s sample.
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 falls (from at to at ), while leave-one-out plunges ( at ) and peaks around (). On this sample cross-validation chooses , with ISE 0.00365, between the normal rule (0.00625 at ) and the oracle (0.00339 at ). This is one sample: results vary, and the benchmark below averages them.
The third cell covers the -neighbor estimator and divergence of its mass.
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 to , rises from 1.211 to 1.898: each length decade adds about 0.115, the of two tails with theoretical value 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.
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 all 5 groups appear (ARI 0.899, not 1: groups overlap slightly at edges), with there are 4 (ARI 0.778: the pair is one hill), with there are 3 (ARI 0.542) and with just one (ARI 0). Note iterations: 114 with versus 43 at and 26 at . With small and intermediate bandwidths convergence is slower, as Carreira-Perpiñán predicts, and slower still near 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 ). Group count depends on in both implementations.
The second part of the lab benchmarks reference rules against cross-validation.
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 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 (0.47 versus the oracle’s 0.34): dispersion created by two modes inflates .
- 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 (the oracle’s is 0.15). Silverman’s minimum of and holds up (1.62), and least-squares cross-validation with is best (1.23).
- On Student’s with 3 degrees of freedom, likelihood CV chooses , 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 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.
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 on the original scale, direct KDE of 150 lognormal data points has mean ISE 0.0404 and puts 6.6% of mass at . Reflection removes the leak but does not improve ISE (0.0451): it does not fix being too large for a lognormal peak (in the previous benchmark the oracle used versus the rule’s 0.49). Log transformation with selected by cross-validation on the log scale reduces ISE to 0.0122, three times lower.
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 . The best isotropic KDE on raw data reaches , with compromising between a variable of scale 1 and one of scale 100. Standardizing each variable raises it to , and whitening with full covariance to , 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.
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 (0.06% of the peak, 0.403), and the tree with rtol=1e-4 with error . FFT is orders of magnitude faster than direct evaluation, moving from kernel evaluations to a -point FFT; the tree also beats direct evaluation in this run, but its advantage depends on tolerance and dimension.
Common mistakes
Exercises
Step 1 of 4. What is ?
Step 1 of 4. Differentiate with respect to and set to zero. What equation results?
Step 1 of 4. What is ?
loo_log_likelihood(X, h), returning the per-datum mean of for a one-dimensional Gaussian KDE (each is constructed from the other 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])