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 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 .
- 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 . Density estimation asks for more: the whole distribution of the inputs. Given drawn i.i.d. from an unknown density on , produce an estimate with . 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, , with one density per class.
The oldest estimator is the histogram. Cut the line into bins of width and set
Dividing by 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.
| Family | Example | Assumes | Behavior |
|---|---|---|---|
| Parametric | one Gaussian | a fixed shape with a few parameters | fast and stable, but stuck if the shape is wrong |
| Mixture | a Gaussian mixture with components | the data blend simpler groups | flexible; fitted by EM; must be chosen |
| Nonparametric | histogram, kernel density estimate, -nearest-neighbor density | only smoothness | adapts to any shape, but needs far more data, especially in high dimension |
| Deep | autoregressive models, normalizing flows, VAEs, diffusion | structure built into a neural network | scales to images and audio; likelihoods can mislead |
You draw a histogram of 50 points with very narrow bins. What do you see, and which kind of error dominates?
- A smooth curve close to the true density
- A flattened version of the true density: high bias
- Spikes and gaps that change completely with a new sample: high variance
- 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:
The smoothing kernel is itself a density, usually the standard Gaussian, and the bandwidth sets the width of every bump. Because integrates to 1, so does : it is an equal-weight mixture of bumps. There are no bins and no origin. Only remains, and it controls almost everything.
Write , so is an average of i.i.d. terms, and its mean is the mean of one term. Substitute :
Expand . A symmetric kernel has ; write . The bias is
The variance of an average of i.i.d. terms is one term's variance over . With , the second moment of one term is , and the squared mean is bounded, so as
Square the bias, add the variance and integrate over . The asymptotic mean integrated squared error trades against , 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 () and valleys filled in (). The variance is largest where the data are dense. Halving divides the squared bias by 16 and doubles the variance, the bias–variance trade-off in its purest form. Note the rate: is slower than the that a correctly specified parametric model achieves. Flexibility has a price.
Exam scores have sample standard deviation points, and 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
, so points: each score is smeared over roughly points. With 50,000 students the same rule gives . More data buys narrower bumps, but slowly, because shrinks only like .
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 ). If the data really are Gaussian, the expected KL divergence from the truth shrinks like for 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:
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 with covariance contributes a density value of order at , so shrinking 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 every point sits on its own spike, and . The cure is to score each model on points it never saw:
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?
- The first: it has the highest training log-likelihood
- The third: it has the smallest gap between training and held-out scores
- None: log-likelihoods of different models cannot be compared
- 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 , 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 grows. A histogram with 10 bins per axis has cells: a hundred in two dimensions, ten billion in ten, nearly all of them empty. Kernel estimates fare little better. Redo the derivation in dimensions and the variance becomes , because each bump spreads its mass over a volume of order , while the bias stays of order . Balancing the two gives and an error of order . 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 | Points needed |
|---|---|
| 1 | 4 |
| 2 | 19 |
| 3 | 67 |
| 5 | 768 |
| 8 | 43,700 |
| 10 | 842,000 |
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 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 , an anomaly detector takes one line: flag when , or equivalently when the anomaly score exceeds . 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 by the false alarms you can afford. Score held-out normal data and put at, say, its 1% quantile: about 1% of normal traffic is then flagged, whatever the anomalies look like. The region 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.
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 tauKernelDensity.score returns the total log-likelihood, so the grid search picks the bandwidth with the best held-out likelihood; score_samples returns at each point.
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 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, , with a neural network computing each conditional; language models are exactly this, with tokens as the . Normalizing flows push a simple density through an invertible network; with the inverse map, from data back to noise, the change-of-variables formula gives exact likelihoods, . Variational autoencoders train a latent-variable model through a lower bound on , the ELBO. Diffusion models learn to undo a gradual noising process. GANs generate samples without any density that can be evaluated.
| Model | Sampling | Catch | |
|---|---|---|---|
| Autoregressive | exact | sequential, one variable at a time | slow to sample in high dimension |
| Normalizing flow | exact | one pass through the network | every layer must be invertible with a cheap Jacobian determinant |
| VAE | lower bound (ELBO) | one pass | samples are often blurrier than the data |
| Diffusion | lower bound, or exact by solving an ODE | tens to hundreds of passes | slow sampling, though distillation cuts the steps |
| GAN | none | one pass | unstable training; may miss modes of the data |
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 and variance make the bandwidth a bias–variance knob, with the best and error in one dimension.
- Compare density models by held-out log-likelihood, which estimates . Training likelihood can be driven to infinity by shrinking a bandwidth or collapsing a mixture component.
- Nonparametric rates degrade to , so density estimation in high dimension needs structure: parametric forms, independence, or the low-dimensional structure that deep models exploit.
- Thresholding 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.
You halve the bandwidth of a kernel density estimate. What happens to the leading terms of the squared bias and the variance at a point?
- Both fall, so a smaller is always better
- The squared bias doubles and the variance falls by a factor of 16
- The squared bias falls by a factor of 16 and the variance doubles
- 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 , so the squared bias scales like and falls by . The variance is , so it doubles. The best balances the two, which is why it shrinks with , like .
Why can you not choose a KDE's bandwidth by maximizing its log-likelihood on the training data?
- As each training point sits on its own spike, so the training log-likelihood grows without bound
- The training log-likelihood always prefers the largest bandwidth
- The log-likelihood of a KDE is not differentiable in
- A KDE is nonparametric, so it has no likelihood
Show the answer
A. As each training point sits on its own spike, so the training log-likelihood grows without bound
includes the bump centered on itself, which contributes and blows up as . Score on held-out points instead, or use the leave-one-out likelihood , which removes each point's own bump.
The best kernel density estimate of a twice-differentiable density has mean integrated squared error of order . How many times more data does halving the error take in dimensions, compared with ?
- The same factor: the rate does not depend on the dimension
- About 5.7 times more data in , against about 2.4 times in
- Less data in , because each point carries six numbers
- Halving is impossible once , because the KDE stops converging
Show the answer
B. About 5.7 times more data in , against about 2.4 times in
Halving needs multiplied by . In , gives ; in , gives . The exponent tends to 0 as grows: the curse of dimensionality.
You flag a point as anomalous when , with set at the 1% quantile of on held-out normal data. What does this choice control?
- The fraction of anomalies that will be missed
- The fraction of normal points that will be flagged, about 1%
- The fraction of flagged points that are normal
- 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.
Why does maximum likelihood for a Gaussian mixture with components have no maximum?
- Because EM can decrease the likelihood
- Because the components can be relabeled in ways
- Because a component can sit on a single data point and shrink its variance toward zero, sending the likelihood to infinity
- 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 and , the term grows like , 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
- Kernel Density Estimation · Bandwidths, bias–variance and convergence rates.
- Anomaly & Out-of-Distribution Detection · Isolation forests, one-class methods and OOD detection.
- Normalizing Flows & Deep Density Models · Exact likelihoods through invertible maps.
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).