Skip to content
E
Educatum

What is density estimation in ML?

Curated by Educatum AI teamLast updated:
Basic Concepts
Direct Answer

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) p(x)p(\mathbf{x}) of an unobserved underlying data-generating distribution from a finite set of observed samples {x1,…,xn}\{x_1, \dots, x_n\}. 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 N(μ,Σ)\mathcal{N}(\mu, \Sigma) 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):
f^h(x)=1nh∑i=1nK ⁣(x−xih)\hat{f}_h(x) = \frac{1}{n h} \sum_{i=1}^{n} K\!\left(\frac{x - x_i}{h}\right)

where KK is a non-negative kernel integrating to 11 and h>0h > 0 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 p(x)p(x) integrating to 11 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 KK (often Gaussian) centered at each training sample and averaging the contributions.
  • Bandwidth (hh): 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 nn.

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 hh, the curve develops noisy spikes around individual observed ages; with an overly large bandwidth hh, 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])
  • Anomaly Detection: Observations falling in regions with very low estimated density p(x)p(\mathbf{x}) 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 hh 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 dd increases because local neighborhoods become sparse; dimensionality reduction or structured deep density models are needed in high dimensions.
View all →

Try keywords like RoPE, FlashAttention, DPO, or Blind 75.