What is EM algorithm?
The Expectation-Maximization (EM) algorithm is an iterative optimization method for finding maximum likelihood (or MAP) parameter estimates in statistical models with latent variables or missing data. It alternates between an E-step, which computes the posterior distribution over latent variables to form the expected complete-data log-likelihood, and an M-step, which maximizes that expectation with respect to the model parameters. By Jensen's inequality, each EM iteration guarantees that the observed-data log-likelihood never decreases.
Study Card: Expectation-Maximization (EM) Algorithm
Direct Answer
The Expectation-Maximization (EM) algorithm is an iterative method for finding Maximum Likelihood Estimation (MLE) or Maximum A Posteriori (MAP) parameters in models with unobserved latent variables (or missing data), where directly maximizing the marginal log-likelihood has no closed form.
EM alternates two steps starting from initial parameters :
- E-step (Expectation): Compute the posterior distribution over latent variables given current parameters, and form the expected complete-data log-likelihood (the -function):
- M-step (Maximization): Update the parameters to maximize :
By Jensen’s inequality (tightening the Evidence Lower Bound, ELBO), every iteration guarantees , converging to a local optimum or stationary point.
Key Terms
- Maximum Likelihood Estimation (MLE): Selecting parameters that maximize for observed data .
- Latent Variables (): Unobserved variables (such as cluster assignments in a GMM or hidden states in an HMM) that simplify the joint distribution .
- E-step: Computes soft posterior responsibilities over under to construct .
- M-step: Solves a tractable weighted MLE problem over the complete-data objective .
- Local Optima Sensitivity: Because EM is guaranteed only to climb monotonically, multiple random restarts (
n_init) are used to avoid poor local maxima.
Example
Suppose we observe 1D data drawn from two Gaussian clusters without knowing which cluster generated each point (latent cluster indicator ). Directly differentiating couples all parameters inside the logarithm. In the E-step, EM computes each point’s posterior responsibility . In the M-step, each cluster’s weight, mean, and variance update via simple weighted averages using , monotonically increasing the marginal log-likelihood until convergence.
Code Implementation
import numpy as np
from scipy.stats import norm
# Generate 1D data from two Gaussian components (latent cluster labels hidden)
rng = np.random.default_rng(42)
X = np.concatenate([rng.normal(0.0, 1.0, 120), rng.normal(5.0, 1.2, 180)])
# Initialize parameters for 2-component 1D GMM
weights = np.array([0.5, 0.5])
means = np.array([1.0, 4.0])
stds = np.array([1.5, 1.5])
log_likelihoods = []
for step in range(15):
# E-step: compute posterior responsibilities gamma[i, k]
weighted_pdfs = np.column_stack([
weights[k] * norm.pdf(X, loc=means[k], scale=stds[k])
for k in range(2)
])
total_pdf = np.sum(weighted_pdfs, axis=1, keepdims=True)
gamma = weighted_pdfs / total_pdf
ll = float(np.sum(np.log(total_pdf)))
log_likelihoods.append(ll)
# M-step: update mixing weights, means, and stds
Nk = np.sum(gamma, axis=0)
weights = Nk / len(X)
means = np.sum(gamma * X[:, None], axis=0) / Nk
variances = np.sum(gamma * (X[:, None] - means) ** 2, axis=0) / Nk
stds = np.sqrt(np.maximum(variances, 1e-6))
print(f"Iter {step + 1:2d}: log-likelihood = {ll:.4f}, means = {np.round(means, 3)}")
print("Monotonically non-decreasing log-likelihood:",
all(b >= a - 1e-9 for a, b in zip(log_likelihoods, log_likelihoods[1:])))
Related Concepts
- Gaussian Mixture Models (GMMs): The canonical application of EM for soft clustering and density estimation.
- K-means Clustering: Corresponds to the hard-assignment, isotropic equal-variance () limit of EM on a GMM.
- Hidden Markov Models (HMMs) & Baum–Welch: Baum–Welch is EM specialized to sequential discrete-state HMMs using forward–backward posteriors.
- Jensen’s Inequality & ELBO: Formalizes why maximizing raises a tight lower bound on .
- Variational Inference (VI): Generalizes EM when exact E-step posteriors are intractable and must be approximated by a tractable variational family .