What is density estimation in ML?
Density estimation is the unsupervised task of estimating the underlying probability density function (PDF) of a dataset from observed samples. Parametric approaches fit fixed-form distributions such as Gaussians or Gaussian Mixture Models, whereas non-parametric methods such as histograms and Kernel Density Estimation infer smooth densities directly from local sample concentrations. It underpins anomaly detection, Bayesian inference, and probabilistic generative modeling.
Study Card: What is density estimation in ML?
Direct Answer
Density estimation is the unsupervised learning task of estimating the probability density function (PDF) of an unobserved underlying data-generating distribution from a finite set of observed samples . It quantifies how probability mass concentrates across feature space.
Common methods span three families:
- Parametric density estimation: Assumes a specific functional form (e.g., a Gaussian or exponential family) and estimates parameters via Maximum Likelihood Estimation (MLE) or Bayesian inference; Gaussian Mixture Models (GMMs) extend this to multimodal densities.
- Non-parametric density estimation: Avoids rigid distributional assumptions using histograms or Kernel Density Estimation (KDE):
where is a non-negative kernel integrating to and is the bandwidth.
- Deep generative density estimators: Autoregressive models and normalizing flows learn exact tractable likelihoods in high dimensions.
Key Terms
- Probability Density Function (PDF): A non-negative function integrating to whose integral over a region gives the probability of a continuous random variable falling in that region.
- Kernel Density Estimation (KDE): A non-parametric estimator placing a smooth kernel (often Gaussian) centered at each training sample and averaging the contributions.
- Bandwidth (): The smoothing parameter in KDE controlling the bias–variance tradeoff; too small yields spiky overfitting, while too large oversmooths distinct modes.
- Parametric vs. Non-Parametric: Parametric models fix a finite parameter count (low variance, higher bias if misspecified); non-parametric models grow in complexity with data size .
Example
Consider analyzing the ages of 500 store customers. Using KDE, we might uncover a bimodal distribution with peaks around ages 28 and 53, revealing two primary customer segments. With a tiny bandwidth , the curve develops noisy spikes around individual observed ages; with an overly large bandwidth , the two peaks merge into a single unimodal hump, hiding the customer segmentation.
Code Implementation
import numpy as np
import matplotlib.pyplot as plt
from sklearn.neighbors import KernelDensity
# Generate bimodal customer age data
rng = np.random.default_rng(0)
ages = np.concatenate([
rng.normal(28, 2, 200),
rng.normal(53, 3, 300),
]).reshape(-1, 1)
# Fit Gaussian Kernel Density Estimation
kde = KernelDensity(kernel="gaussian", bandwidth=1.2)
kde.fit(ages)
# Evaluate estimated density on a grid
x_plot = np.linspace(15, 65, 1000)[:, np.newaxis]
log_dens = kde.score_samples(x_plot)
plt.figure(figsize=(8, 5))
plt.plot(x_plot, np.exp(log_dens), color="blue", lw=2, label="Gaussian KDE (h=1.2)")
plt.hist(ages.ravel(), bins=25, density=True, alpha=0.5, color="grey", label="Histogram")
plt.title("Density Estimation of Customer Ages")
plt.xlabel("Age")
plt.ylabel("Density")
plt.legend()
plt.grid(True)
plt.show()
print("Estimated density at age 30:", np.exp(kde.score_samples([[30]]))[0])
Related Concepts
- Anomaly Detection: Observations falling in regions with very low estimated density can be flagged as outliers or anomalies.
- Generative Models: Normalizing flows and autoregressive models estimate explicit densities, whereas VAEs optimize a tractable lower bound (ELBO) and GANs learn implicit samplers without explicit likelihoods.
- Bias–Variance Tradeoff in Bandwidth Selection: Choosing via cross-validation or Silverman’s rule of thumb balances under-smoothing and over-smoothing.
- Curse of Dimensionality: Non-parametric KDE requires exponentially more samples as dimensionality increases because local neighborhoods become sparse; dimensionality reduction or structured deep density models are needed in high dimensions.