Simple Algorithm
Machine Learning · Descent · 22 min

Density Estimation & Anomalies

Modeling where data lives, and spotting what doesn’t belong.

A card network handles millions of ordinary payments a day and a trickle of fraud it has never seen before. You cannot learn fraud from examples you do not have, but you can learn where ordinary payments live and flag whatever lands far from them. This lesson builds that idea from histograms to kernel density estimates and mixtures, shows why the bandwidth is a bias–variance knob and why dimension makes everything harder, and turns a density into an anomaly detector.

What you’ll learn

  • Build histogram and kernel density estimates, and derive the bias and variance that make the bandwidth a bias–variance knob, with best bandwidth h∝n−1/5h\propto n^{-1/5} in one dimension.
  • Fit parametric and mixture densities by maximum likelihood, and compare density models by held-out log-likelihood, never by training likelihood.
  • Explain why nonparametric density estimation degrades with dimension, at the rate n−4/(4+d)n^{-4/(4+d)}.
  • Turn a density estimate into an anomaly detector with a chosen false-alarm rate, and explain why base rates and the choice of representation matter.
  • Place autoregressive models, normalizing flows, VAEs and diffusion models on the map of density estimators.

From data to a density

Supervised learning estimates p(y∣x)p(y\mid\mathbf x). Density estimation asks for more: the whole distribution of the inputs. Given x1,…,xn\mathbf x_1,\dots,\mathbf x_n drawn i.i.d. from an unknown density pp on Rd\R^d, produce an estimate p^≥0\hat p\ge0 with ∫p^=1\int\hat p=1. It is the most complete form of unsupervised learning. A good density model can score how typical a point is, generate new samples, fill in missing features, and classify through Bayes' rule, p(y∣x)∝p(x∣y) p(y)p(y\mid\mathbf x)\propto p(\mathbf x\mid y)\,p(y), with one density per class.

The oldest estimator is the histogram. Cut the line into bins of width hh and set

p^(x)=#{i: xi lies in the bin containing x}nh.\hat p(x)=\frac{\#\{i:\ x_i\text{ lies in the bin containing }x\}}{nh}.

Dividing by nhnh makes the bars integrate to 1. Wide bins blur real features. Narrow bins leave most bins with zero or one point, so the picture changes with every new sample. Even the bin origin matters: shifting every bin by half a width can turn one peak into two.

FamilyExampleAssumesBehavior
Parametricone Gaussian N(μ,Σ)\mathcal N(\boldsymbol\mu,\Sigma)a fixed shape with a few parametersfast and stable, but stuck if the shape is wrong
Mixturea Gaussian mixture with KK componentsthe data blend KK simpler groupsflexible; fitted by EM; KK must be chosen
Nonparametrichistogram, kernel density estimate, kk-nearest-neighbor densityonly smoothnessadapts to any shape, but needs far more data, especially in high dimension
Deepautoregressive models, normalizing flows, VAEs, diffusionstructure built into a neural networkscales to images and audio; likelihoods can mislead
Four families of density estimators, from most to least assumption-laden (the deep family builds its assumptions into the architecture). This lesson visits all four.
Check your understanding

You draw a histogram of 50 points with very narrow bins. What do you see, and which kind of error dominates?

  1. A smooth curve close to the true density
  2. A flattened version of the true density: high bias
  3. Spikes and gaps that change completely with a new sample: high variance
  4. An estimate that no longer integrates to 1
Show the answer

C. Spikes and gaps that change completely with a new sample: high variance

With many bins and few points, most bins hold zero or one point, so the estimate is a row of spikes placed wherever this particular sample happened to fall. Averaged over samples it is nearly unbiased, but it varies wildly from sample to sample. Wide bins make the opposite error.

Kernel density estimation

A histogram attaches each point to a fixed bin. A kernel density estimate (KDE) centers a small bump on every point instead and adds the bumps up:

p^h(x)=1nhd∑i=1nK(x−xih).\hat p_h(\mathbf x)=\frac1{nh^d}\sum_{i=1}^nK\Big(\frac{\mathbf x-\mathbf x_i}h\Big).

The smoothing kernel KK is itself a density, usually the standard Gaussian, and the bandwidth h>0h>0 sets the width of every bump. Because KK integrates to 1, so does p^h\hat p_h: it is an equal-weight mixture of nn bumps. There are no bins and no origin. Only hh remains, and it controls almost everything.

DerivationBias and variance at a point (one dimension)
  1. E p^h(x)=∫1hK(x−yh)p(y) dy=∫K(u) p(x−hu) du\E\,\hat p_h(x)=\int\frac1hK\Big(\frac{x-y}h\Big)p(y)\,dy=\int K(u)\,p(x-hu)\,du

    Write Kh(u)=K(u/h)/hK_h(u)=K(u/h)/h, so p^h(x)=1n∑iKh(x−xi)\hat p_h(x)=\frac1n\sum_iK_h(x-x_i) is an average of nn i.i.d. terms, and its mean is the mean of one term. Substitute y=x−huy=x-hu:

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

    Expand p(x−hu)=p(x)−hu p′(x)+12h2u2p′′(x)+o(h2)p(x-hu)=p(x)-hu\,p'(x)+\tfrac12h^2u^2p''(x)+o(h^2). A symmetric kernel has ∫uK(u) du=0\int uK(u)\,du=0; write μ2(K)=∫u2K(u) du\mu_2(K)=\int u^2K(u)\,du. The bias is

  3. Var⁡ p^h(x)=R(K) p(x)nh+o(1nh)\Var\,\hat p_h(x)=\frac{R(K)\,p(x)}{nh}+o\Big(\frac1{nh}\Big)

    The variance of an average of nn i.i.d. terms is one term's variance over nn. With R(K)=∫K(u)2 duR(K)=\int K(u)^2\,du, the second moment of one term is 1h∫K(u)2p(x−hu) du≈R(K)p(x)/h\frac1h\int K(u)^2p(x-hu)\,du\approx R(K)p(x)/h, and the squared mean is bounded, so as h→0h\to0

  4. AMISE(h)=h44 μ2(K)2 ⁣∫p′′(x)2dx+R(K)nh,h⋆∝n−1/5,AMISE(h⋆)∝n−4/5\mathrm{AMISE}(h)=\frac{h^4}4\,\mu_2(K)^2\!\int p''(x)^2dx+\frac{R(K)}{nh},\qquad h^\star\propto n^{-1/5},\qquad\mathrm{AMISE}(h^\star)\propto n^{-4/5}

    Square the bias, add the variance and integrate over xx. The asymptotic mean integrated squared error trades h4h^4 against 1/(nh)1/(nh), and setting its derivative to zero gives the best bandwidth and the best error:

The bias is largest where the density curves: peaks get shaved down (p′′<0p''<0) and valleys filled in (p′′>0p''>0). The variance is largest where the data are dense. Halving hh divides the squared bias by 16 and doubles the variance, the bias–variance trade-off in its purest form. Note the rate: n−4/5n^{-4/5} is slower than the 1/n1/n that a correctly specified parametric model achieves. Flexibility has a price.

Predict before you look

Exam scores have sample standard deviation σ^=10\hat\sigma=10 points, and n=500n=500 students took the exam. What bandwidth does Silverman's rule give for a Gaussian-kernel KDE of the scores?

Show the answer

3.1 points

500−1/5=e−(ln⁡500)/5≈0.289500^{-1/5}=e^{-(\ln500)/5}\approx0.289, so h≈1.06×10×0.289≈3.06h\approx1.06\times10\times0.289\approx3.06 points: each score is smeared over roughly ±3\pm3 points. With 50,000 students the same rule gives h≈1.22h\approx1.22. More data buys narrower bumps, but slowly, because hh shrinks only like n−1/5n^{-1/5}.

Mixtures, likelihood and honest comparison

Parametric models trade flexibility for efficiency. Fit a multivariate Gaussian by maximum likelihood and you get the sample mean and the sample covariance (dividing by nn). If the data really are Gaussian, the expected KL divergence from the truth shrinks like k/(2n)k/(2n) for kk free parameters, faster than any nonparametric rate. If they are not, more data only pins down the closest Gaussian, not the truth.

A Gaussian mixture sits in between:

p(x)=∑k=1Kπk N(x∣μk,Σk),πk≥0,∑kπk=1.p(\mathbf x)=\sum_{k=1}^K\pi_k\,\mathcal N(\mathbf x\mid\boldsymbol\mu_k,\Sigma_k),\qquad\pi_k\ge0,\quad\sum_k\pi_k=1.

With enough components it can approximate any continuous density as closely as you like, and each component often means something: a cluster. There is no closed-form maximum-likelihood fit, but the EM algorithm alternates soft assignments of points to components with weighted refits, and it never decreases the log-likelihood. The Descent lesson Latent Variables & EM derives it.

Why do extra components keep paying? A component centered on one data point xi\mathbf x_i with covariance σ2I\sigma^2I contributes a density value of order σ−d\sigma^{-d} at xi\mathbf x_i, so shrinking σ\sigma sends the likelihood to infinity: the likelihood of a mixture has no global maximum at all, and what EM finds, and practice uses, are well-behaved local maxima. Training likelihood cannot choose a bandwidth either. As h→0h\to0 every point sits on its own spike, and p^h(xi)≥K(0)/(nhd)→∞\hat p_h(\mathbf x_i)\ge K(\mathbf 0)/(nh^d)\to\infty. The cure is to score each model on points it never saw:

1m∑j=1mlog⁡p^(xj′) → m→∞  Ex∼p[log⁡p^(x)]=−H(p)−DKL(p ∥ p^)\frac1m\sum_{j=1}^m\log\hat p(\mathbf x'_j)\ \xrightarrow{\ m\to\infty\ }\ \E_{\mathbf x\sim p}\big[\log\hat p(\mathbf x)\big]=-H(p)-\KL\big(p\,\|\,\hat p\big)
The held-out points x1′,…,xm′\mathbf x'_1,\dots,\mathbf x'_m are fresh draws from pp. The differential entropy H(p)H(p) is the same for every model, so a higher held-out log-likelihood means a smaller KL divergence from the truth. Bandwidths, numbers of components and whole model families are compared this way, usually by cross-validation; information criteria such as BIC are an alternative for parametric models.
Check your understanding

Three density models fitted to the same data reach average log-likelihoods of −1.10, −1.25 and −1.32 on the training set, and −1.48, −1.31 and −1.35 on a held-out set. Which should you prefer?

  1. The first: it has the highest training log-likelihood
  2. The third: it has the smallest gap between training and held-out scores
  3. None: log-likelihoods of different models cannot be compared
  4. The second: it has the highest held-out log-likelihood
Show the answer

D. The second: it has the highest held-out log-likelihood

Average held-out log-likelihood estimates −H(p)−DKL(p ∥ p^)-H(p)-\KL(p\,\|\,\hat p), so the second model is closest to the truth in KL divergence. The first has overfit: best on the points it was fitted to, worst on new ones.

The curse of dimensionality

Everything above gets harder, and fast, as the dimension dd grows. A histogram with 10 bins per axis has 10d10^d cells: a hundred in two dimensions, ten billion in ten, nearly all of them empty. Kernel estimates fare little better. Redo the derivation in dd dimensions and the variance becomes R(K)p(x)/(nhd)R(K)p(\mathbf x)/(nh^d), because each bump spreads its mass over a volume of order hdh^d, while the bias stays of order h2h^2. Balancing the two gives h⋆∝n−1/(d+4)h^\star\propto n^{-1/(d+4)} and an error of order n−4/(d+4)n^{-4/(d+4)}. The Convergence lesson Kernel Density Estimation shows that no estimator can do better for densities known only to be twice differentiable. This is the curse of dimensionality.

Dimension ddPoints needed
14
219
367
5768
843,700
10842,000
Sample size needed to estimate a standard normal density at its center with relative mean squared error below 0.1, using a Gaussian kernel at the best bandwidth (Silverman, 1986). Because data and kernel are both Gaussian, the bias and variance have exact formulas, so these numbers involve no approximation. The target is about as easy as density estimation gets: one point, the best possible bandwidth and a perfectly smooth density.

Density estimation in high dimension therefore leans on structure. A parametric family fixes the shape. Independence assumptions factor the density: naive Bayes multiplies one-dimensional densities, one per feature. Or the data may lie near a low-dimensional surface, the manifold hypothesis, which deep generative models exploit.

Think first A 64×64 color image is a point in a space of 12,288 dimensions. Why is modeling the density of natural images not hopeless?

Natural images fill a tiny, highly structured part of that space. Neighboring pixels are strongly correlated, and the meaningful variation (objects, pose, lighting) has far fewer degrees of freedom than the pixel count. Models that build this structure in, such as convolutional or transformer networks trained as autoregressive models, flows or diffusion models, need not pay the generic n−4/(4+d)n^{-4/(4+d)} price. No theorem guarantees that the structure is there; the evidence is empirical, in the samples these models produce.

Anomalies live where the density is low

Once you have p^\hat p, an anomaly detector takes one line: flag x\mathbf x when p^(x)<τ\hat p(\mathbf x)<\tau, or equivalently when the anomaly score −log⁡p^(x)-\log\hat p(\mathbf x) exceeds −log⁡τ-\log\tau. Training needs only normal data, or data that are mostly normal, and no examples of anomalies. That is the point: fraud, equipment faults and intrusions are rare and keep changing.

Choose τ\tau by the false alarms you can afford. Score held-out normal data and put τ\tau at, say, its 1% quantile: about 1% of normal traffic is then flagged, whatever the anomalies look like. The region {x:p(x)≥τ}\{\mathbf x:p(\mathbf x)\ge\tau\} is a density level set, and the Convergence lesson Anomaly & Out-of-Distribution Detection proves that it is the smallest region, by volume, holding a given share of the normal data.

Anomalies come in kinds (Chandola, Banerjee & Kumar, 2009). A point anomaly is unusual on its own, like a $9,000 coffee purchase. A contextual anomaly is unusual only in its context, like a heating bill that would be normal in January but not in July. A collective anomaly is a group of individually ordinary points that is unusual together, like a burst of small transfers. A density over single points catches the first kind; the others need the context or the sequence built into the features.

python
import numpy as np
from sklearn.neighbors import KernelDensity
from sklearn.model_selection import GridSearchCV

# X_train, X_val: normal data only, standardized; X_new: incoming points
search = GridSearchCV(KernelDensity(kernel='gaussian'),
                      {'bandwidth': np.logspace(-1.5, 0.5, 30)}, cv=5)
search.fit(X_train)            # each fold is scored by its held-out log-likelihood
kde = search.best_estimator_   # refit on all of X_train at the best bandwidth

# Set the threshold on held-out normal data: in-sample densities are
# inflated, because every training point sits on its own bump.
tau = np.quantile(kde.score_samples(X_val), 0.01)   # about 1% false alarms
flags = kde.score_samples(X_new) < tau              # log density below tau

KernelDensity.score returns the total log-likelihood, so the grid search picks the bandwidth with the best held-out likelihood; score_samples returns log⁡p^\log\hat p at each point.

Predict before you look

A detector flags 1% of normal transactions and catches 90% of fraudulent ones. Fraud is 0.1% of all transactions. What percentage of the flagged transactions are fraudulent?

Show the answer

8 %

Per million transactions, 1,000 are fraud and 900 of those are flagged; 999,000 are normal and 9,990 of those are flagged. So 900/(900+9,990)≈8%900/(900+9{,}990)\approx8\% of alarms are real. A detector that sounds excellent in isolation still buries investigators in false alarms when anomalies are rare. Cutting the false-alarm rate to 0.1% while still catching 90% of fraud would lift the share to about 47%.

Deep density models

Modern density models put neural networks inside a few exact identities. Autoregressive models use the chain rule, p(x)=∏jp(xj∣x1,…,xj−1)p(\mathbf x)=\prod_jp(x_j\mid x_1,\dots,x_{j-1}), with a neural network computing each conditional; language models are exactly this, with tokens as the xjx_j. Normalizing flows push a simple density pZp_Z through an invertible network; with ff the inverse map, from data back to noise, the change-of-variables formula gives exact likelihoods, p(x)=pZ(f(x)) ∣det⁡Jf(x)∣p(\mathbf x)=p_Z(f(\mathbf x))\,\abs{\det J_f(\mathbf x)}. Variational autoencoders train a latent-variable model through a lower bound on log⁡p(x)\log p(\mathbf x), the ELBO. Diffusion models learn to undo a gradual noising process. GANs generate samples without any density that can be evaluated.

Modellog⁡p(x)\log p(\mathbf x)SamplingCatch
Autoregressiveexactsequential, one variable at a timeslow to sample in high dimension
Normalizing flowexactone pass through the networkevery layer must be invertible with a cheap Jacobian determinant
VAElower bound (ELBO)one passsamples are often blurrier than the data
Diffusionlower bound, or exact by solving an ODEtens to hundreds of passesslow sampling, though distillation cuts the steps
GANnoneone passunstable training; may miss modes of the data
Five families of deep generative models. As of the mid-2020s, diffusion models and autoregressive transformers produce the most convincing images and text; flows are prized where exact likelihoods or exact inverses are needed.

Key takeaways

  • A density estimate answers every question about the inputs: how typical a point is, what new samples look like, and, with one density per class, how to classify. Histograms, kernel estimates, parametric families, mixtures and deep models trade assumptions for data.
  • A KDE puts one bump on each point. Its bias h22μ2(K)p′′(x)\tfrac{h^2}2\mu_2(K)p''(x) and variance R(K)p(x)/(nh)R(K)p(x)/(nh) make the bandwidth a bias–variance knob, with the best h∝n−1/5h\propto n^{-1/5} and error ∝n−4/5\propto n^{-4/5} in one dimension.
  • Compare density models by held-out log-likelihood, which estimates −H(p)−DKL(p ∥ p^)-H(p)-\KL(p\,\|\,\hat p). Training likelihood can be driven to infinity by shrinking a bandwidth or collapsing a mixture component.
  • Nonparametric rates degrade to n−4/(4+d)n^{-4/(4+d)}, so density estimation in high dimension needs structure: parametric forms, independence, or the low-dimensional structure that deep models exploit.
  • Thresholding p^\hat p gives an anomaly detector whose false-alarm rate you set on normal data. At low base rates most alarms can still be false, and "low density" depends on the representation.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

You halve the bandwidth hh of a kernel density estimate. What happens to the leading terms of the squared bias and the variance at a point?

  1. Both fall, so a smaller hh is always better
  2. The squared bias doubles and the variance falls by a factor of 16
  3. The squared bias falls by a factor of 16 and the variance doubles
  4. Neither changes; only the shape of the kernel matters
Show the answer

C. The squared bias falls by a factor of 16 and the variance doubles

The bias is h22μ2(K)p′′(x)\tfrac{h^2}2\mu_2(K)p''(x), so the squared bias scales like h4h^4 and falls by 24=162^4=16. The variance is R(K)p(x)/(nh)R(K)p(x)/(nh), so it doubles. The best hh balances the two, which is why it shrinks with nn, like n−1/5n^{-1/5}.

Question 2

Why can you not choose a KDE's bandwidth by maximizing its log-likelihood on the training data?

  1. As h→0h\to0 each training point sits on its own spike, so the training log-likelihood grows without bound
  2. The training log-likelihood always prefers the largest bandwidth
  3. The log-likelihood of a KDE is not differentiable in hh
  4. A KDE is nonparametric, so it has no likelihood
Show the answer

A. As h→0h\to0 each training point sits on its own spike, so the training log-likelihood grows without bound

p^h(xi)\hat p_h(\mathbf x_i) includes the bump centered on xi\mathbf x_i itself, which contributes K(0)/(nhd)K(\mathbf 0)/(nh^d) and blows up as h→0h\to0. Score on held-out points instead, or use the leave-one-out likelihood ∑ilog⁡p^h,−i(xi)\sum_i\log\hat p_{h,-i}(\mathbf x_i), which removes each point's own bump.

Question 3

The best kernel density estimate of a twice-differentiable density has mean integrated squared error of order n−4/(4+d)n^{-4/(4+d)}. How many times more data does halving the error take in d=6d=6 dimensions, compared with d=1d=1?

  1. The same factor: the rate does not depend on the dimension
  2. About 5.7 times more data in d=6d=6, against about 2.4 times in d=1d=1
  3. Less data in d=6d=6, because each point carries six numbers
  4. Halving is impossible once d>4d>4, because the KDE stops converging
Show the answer

B. About 5.7 times more data in d=6d=6, against about 2.4 times in d=1d=1

Halving n−an^{-a} needs nn multiplied by 21/a2^{1/a}. In d=1d=1, a=4/5a=4/5 gives 25/4≈2.42^{5/4}\approx2.4; in d=6d=6, a=2/5a=2/5 gives 25/2≈5.72^{5/2}\approx5.7. The exponent tends to 0 as dd grows: the curse of dimensionality.

Question 4

You flag a point as anomalous when p^(x)<τ\hat p(\mathbf x)<\tau, with τ\tau set at the 1% quantile of p^\hat p on held-out normal data. What does this choice control?

  1. The fraction of anomalies that will be missed
  2. The fraction of normal points that will be flagged, about 1%
  3. The fraction of flagged points that are normal
  4. It guarantees that at least 99% of anomalies are caught
Show the answer

B. The fraction of normal points that will be flagged, about 1%

The threshold is calibrated on normal data only, so it fixes the false-alarm rate. How many anomalies are caught depends on where the anomalies fall, which is unknown, and the share of alarms that are real depends on the base rate as well.

Question 5

Why does maximum likelihood for a Gaussian mixture with K≥2K\ge2 components have no maximum?

  1. Because EM can decrease the likelihood
  2. Because the components can be relabeled in K!K! ways
  3. Because a component can sit on a single data point and shrink its variance toward zero, sending the likelihood to infinity
  4. Because the mixing weights must sum to 1
Show the answer

C. Because a component can sit on a single data point and shrink its variance toward zero, sending the likelihood to infinity

With μk=xi\boldsymbol\mu_k=\mathbf x_i and Σk=σ2I\Sigma_k=\sigma^2I, the term πkN(xi∣xi,σ2I)\pi_k\mathcal N(\mathbf x_i\mid\mathbf x_i,\sigma^2I) grows like σ−d\sigma^{-d}, while the other components keep every other point's density positive. The supremum is infinite. EM finds useful local optima; in practice a floor on the variances or a prior keeps them away from the singularities.

Go deeper

Further reading

  • B. W. Silverman, Density Estimation for Statistics and Data Analysis (Chapman & Hall, 1986).
  • C. M. Bishop, Pattern Recognition and Machine Learning (Springer, 2006), §2.5 and chapter 9.
  • V. Chandola, A. Banerjee & V. Kumar, "Anomaly detection: a survey," ACM Computing Surveys 41(3), 1–58 (2009).
  • E. Nalisnick, A. Matsukawa, Y. W. Teh, D. Gorur & B. Lakshminarayanan, "Do deep generative models know what they don't know?," ICLR (2019).