Skip to content
E
Educatum

What is EM algorithm?

Curated by Educatum AI teamLast updated:
Basic Concepts
Direct Answer

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 ZZ (or missing data), where directly maximizing the marginal log-likelihood log⁡p(X∣θ)=log⁡∑Zp(X,Z∣θ)\log p(X \mid \theta) = \log \sum_Z p(X, Z \mid \theta) has no closed form.

EM alternates two steps starting from initial parameters θ(0)\theta^{(0)}:

  1. E-step (Expectation): Compute the posterior distribution p(Z∣X,θ(t))p(Z \mid X, \theta^{(t)}) over latent variables given current parameters, and form the expected complete-data log-likelihood (the QQ-function):
Q(θ∣θ(t))=EZ∼p(Z∣X,θ(t)) ⁣[log⁡p(X,Z∣θ)]Q(\theta \mid \theta^{(t)}) = \mathbb{E}_{Z \sim p(Z \mid X, \theta^{(t)})}\!\left[\log p(X, Z \mid \theta)\right]
  1. M-step (Maximization): Update the parameters to maximize QQ:
θ(t+1)=arg⁡max⁡θQ(θ∣θ(t))\theta^{(t+1)} = \arg\max_{\theta} Q(\theta \mid \theta^{(t)})

By Jensen’s inequality (tightening the Evidence Lower Bound, ELBO), every iteration guarantees log⁡p(X∣θ(t+1))≥log⁡p(X∣θ(t))\log p(X \mid \theta^{(t+1)}) \ge \log p(X \mid \theta^{(t)}), converging to a local optimum or stationary point.

Key Terms

  • Maximum Likelihood Estimation (MLE): Selecting parameters θ\theta that maximize log⁡p(X∣θ)\log p(X \mid \theta) for observed data XX.
  • Latent Variables (ZZ): Unobserved variables (such as cluster assignments in a GMM or hidden states in an HMM) that simplify the joint distribution p(X,Z∣θ)p(X, Z \mid \theta).
  • E-step: Computes soft posterior responsibilities over ZZ under θ(t)\theta^{(t)} to construct Q(θ∣θ(t))Q(\theta \mid \theta^{(t)}).
  • M-step: Solves a tractable weighted MLE problem over the complete-data objective Q(θ∣θ(t))Q(\theta \mid \theta^{(t)}).
  • 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 zi∈{1,2}z_i \in \{1, 2\}). Directly differentiating ∑ilog⁡(π1N(xi∣μ1,σ12)+π2N(xi∣μ2,σ22))\sum_i \log(\pi_1 \mathcal{N}(x_i \mid \mu_1, \sigma_1^2) + \pi_2 \mathcal{N}(x_i \mid \mu_2, \sigma_2^2)) couples all parameters inside the logarithm. In the E-step, EM computes each point’s posterior responsibility γik=P(zi=k∣xi,θ(t))\gamma_{ik} = P(z_i = k \mid x_i, \theta^{(t)}). In the M-step, each cluster’s weight, mean, and variance update via simple weighted averages using γik\gamma_{ik}, 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:])))
  • 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 (σ2→0\sigma^2 \to 0) 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 Q(θ∣θ(t))Q(\theta \mid \theta^{(t)}) raises a tight lower bound on log⁡p(X∣θ)\log p(X \mid \theta).
  • Variational Inference (VI): Generalizes EM when exact E-step posteriors p(Z∣X,θ)p(Z \mid X, \theta) are intractable and must be approximated by a tractable variational family q(Z)q(Z).
View all →

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