TExcelTAD
Home › Math for Machine Learning › The EM Algorithm

The EM Algorithm

The expectation-maximization (EM) algorithm fits a Gaussian mixture by breaking the chicken-and-egg loop: guess the parameters, compute responsibilities (E-step), re-estimate the parameters from them as if they were known (M-step), and repeat. Each round can only increase the likelihood, and the updates are simple weighted averages.

The updates

Given current parameters, the E-step computes responsibilities:

rnk=πk N(xn∣μk,Σk)∑jπj N(xn∣μj,Σj)r_{nk} = \frac{\pi_k\,\mathcal{N}(\mathbf{x}_n \mid \boldsymbol{\mu}_k, \Sigma_k)}{\sum_j\pi_j\,\mathcal{N}(\mathbf{x}_n \mid \boldsymbol{\mu}_j, \Sigma_j)}

The M-step re-estimates each component from its weighted points, with Nk=∑nrnkN_k = \sum_n r_{nk} the effective number of points in component kk:

μk=1Nk∑nrnk xnΣk=1Nk∑nrnk (xn−μk)(xn−μk)Tπk=NkN\begin{aligned} \boldsymbol{\mu}_k &= \frac{1}{N_k}\sum_{n} r_{nk}\,\mathbf{x}_n \\ \Sigma_k &= \frac{1}{N_k}\sum_{n} r_{nk}\,(\mathbf{x}_n - \boldsymbol{\mu}_k)(\mathbf{x}_n - \boldsymbol{\mu}_k)^T \\ \pi_k &= \frac{N_k}{N} \end{aligned}

These are the maximum-likelihood formulas for one Gaussian, with each point counted fractionally. The πk\pi_k update comes from a Lagrange multiplier for ∑kπk=1\sum_k\pi_k = 1.

python · try it yourself
import numpy as np

rng = np.random.default_rng(0)
X = np.vstack([rng.multivariate_normal([0, 0], [[1, 0.5], [0.5, 1]], 300),
               rng.multivariate_normal([4, 3], [[0.6, 0], [0, 0.6]], 200),
               rng.multivariate_normal([0, 5], [[1.5, -0.4], [-0.4, 0.5]], 150)])
N, D = X.shape; K = 3

def log_gauss(X, mu, S):
    L = np.linalg.cholesky(S); Z = np.linalg.solve(L, (X - mu).T)
    return -0.5 * D * np.log(2 * np.pi) - np.log(np.diag(L)).sum() - 0.5 * np.sum(Z**2, axis=0)

mu = [X[rng.integers(N)]]                                            # farthest-point initialization
for _ in range(K - 1):
    d2 = np.min([np.sum((X - m)**2, axis=1) for m in mu], axis=0)
    mu.append(X[np.argmax(d2)])
pi = np.full(K, 1 / K); mu = np.array(mu); S = np.array([np.eye(D)] * K)
prev = -np.inf
for it in range(1000):
    logp = np.column_stack([np.log(pi[k]) + log_gauss(X, mu[k], S[k]) for k in range(K)])
    m = logp.max(axis=1, keepdims=True)
    ll = np.sum(m[:, 0] + np.log(np.exp(logp - m).sum(axis=1)))     # log-sum-exp
    r = np.exp(logp - m); r /= r.sum(axis=1, keepdims=True)          # E-step
    Nk = r.sum(axis=0)                                               # M-step
    mu = (r.T @ X) / Nk[:, None]
    S = np.array([((r[:, k, None] * (X - mu[k])).T @ (X - mu[k])) / Nk[k] + 1e-6 * np.eye(D) for k in range(K)])
    pi = Nk / N
    assert ll >= prev - 1e-9                                         # EM never decreases the likelihood
    if ll - prev < 1e-8:
        break
    prev = ll
order = np.argsort(mu[:, 0] + 10 * mu[:, 1])
print("iterations:", it, " final log-likelihood:", round(ll, 3))
print("weights:", np.round(pi[order], 3))
print("means:\n", np.round(mu[order], 2))
iterations: 25  final log-likelihood: -2297.083
weights: [0.461 0.305 0.234]
means:
 [[0.04 0.09]
 [3.95 2.93]
 [0.02 5.01]]

The initial means are spread out by farthest-point initialization (start from a random point, then repeatedly add the point farthest from those already chosen); with purely random starting points EM often ends in a poor local optimum that splits one cluster and merges two others. The weights come out near the true proportions 300/650300/650, 200/650200/650 and 150/650150/650 and the means near the true centres. The assert confirms the monotone increase of the likelihood at every iteration.

Why EM works

For any distribution qq over the hidden component labels, Jensen's inequality gives a lower bound on the log-likelihood (the ELBO). The E-step sets qq to the exact posterior (the responsibilities), making the bound tight; the M-step maximizes the bound over the parameters. The likelihood can therefore never go down. EM converges to a local maximum, so practitioners run it from several initializations (or initialize with k-means) and keep the best.

Pitfalls

  • Collapse. If a component shrinks onto a single point, its variance goes to 0 and the likelihood to infinity. Adding a small ϵI\epsilon I to each covariance (as above) prevents it.
  • Label switching. Components come out in arbitrary order; compare runs by matching means, not indices.
  • Choosing KK. The likelihood always increases with KK; use BIC or cross-validated likelihood (Model Selection).

In software

  • GaussianMixture(n_components=3, n_init=5, reg_covar=1e-6) in scikit-learn: reg_covar is the ϵ\epsilon above, n_init the restarts.
  • k-means is the limit of EM for spherical components with variance going to 0: responsibilities become hard 0/1 assignments (K-means).
  • EM also trains hidden Markov models (Baum-Welch) and fills in missing data.

Go further: Gaussian Mixtures and the EM Algorithm runs EM from scratch on data and chooses the number of components.

Exercises

Exercise 1: One M-step by hand

Three 1-D points 0,2,100, 2, 10 have responsibilities for component 1 of 1,0.5,01, 0.5, 0. Compute N1N_1, μ1\mu_1 and π1\pi_1.

Answer

N1=1.5N_1 = 1.5, μ1=23\mu_1 = \frac{2}{3}, π1=0.5\pi_1 = 0.5.

Solution

N1=1+0.5+0=1.5N_1 = 1 + 0.5 + 0 = 1.5; μ1=(0+0.5⋅2+0)/1.5=23\mu_1 = (0 + 0.5 \cdot 2 + 0)/1.5 = \frac{2}{3}; π1=1.5/3\pi_1 = 1.5/3.

Exercise 2: Monotonicity

Your EM implementation shows the log-likelihood decreasing from one iteration to the next. What does that indicate?

Answer

A bug (or numerical trouble).

Solution

Exact EM can never decrease the likelihood. Typical causes: responsibilities not normalized, a covariance update using the old mean, or computing the likelihood with stale parameters. Large regularization terms can also break strict monotonicity slightly.

Exercise 3: 1-D EM (code)

Run EM with K=2K = 2 on 1-D data drawn from N(−3,1)\mathcal{N}(-3, 1) and N(2,0.25)\mathcal{N}(2, 0.25) (300 points each) and print the estimated means.

Answer

Means close to −3-3 and 22.

Solution
python · try it yourself
import numpy as np
rng = np.random.default_rng(1)
x = np.concatenate([rng.normal(-3, 1, 300), rng.normal(2, 0.5, 300)])
pi, mu, var = np.array([0.5, 0.5]), np.array([-1.0, 1.0]), np.array([1.0, 1.0])
for _ in range(100):
    p = pi * np.exp(-(x[:, None] - mu)**2 / (2 * var)) / np.sqrt(2 * np.pi * var)
    r = p / p.sum(axis=1, keepdims=True)
    Nk = r.sum(axis=0)
    mu = (r * x[:, None]).sum(axis=0) / Nk
    var = (r * (x[:, None] - mu)**2).sum(axis=0) / Nk
    pi = Nk / len(x)
print(np.round(mu, 2), np.round(np.sqrt(var), 2), np.round(pi, 2))
[-3.11  2.01] [0.92 0.49] [0.5 0.5]

Test yourself

In the E-step of EM for a GMM we compute…

  1. the means
  2. the responsibilities rnkr_{nk}
  3. the number of components
  4. the gradient

Each EM iteration…

  1. can decrease the likelihood
  2. never decreases the likelihood
  3. finds the global maximum
  4. doubles the likelihood

Why add a small ϵI\epsilon I to each covariance?

  1. To speed up EM
  2. To prevent a component collapsing onto one point with zero variance and infinite likelihood
  3. To make the means exact
  4. To make KK smaller