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:
The M-step re-estimates each component from its weighted points, with the effective number of points in component :
These are the maximum-likelihood formulas for one Gaussian, with each point counted fractionally. The update comes from a Lagrange multiplier for .
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 , and 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 over the hidden component labels, Jensen's inequality gives a lower bound on the log-likelihood (the ELBO). The E-step sets 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 to each covariance (as above) prevents it.
- Label switching. Components come out in arbitrary order; compare runs by matching means, not indices.
- Choosing . The likelihood always increases with ; 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_covaris the above,n_initthe 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 have responsibilities for component 1 of . Compute , and .
Answer
, , .
Solution
; ; .
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 on 1-D data drawn from and (300 points each) and print the estimated means.
Answer
Means close to and .
Solution
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…
- the means
- the responsibilities
- the number of components
- the gradient
Each EM iteration…
- can decrease the likelihood
- never decreases the likelihood
- finds the global maximum
- doubles the likelihood
Why add a small to each covariance?
- To speed up EM
- To prevent a component collapsing onto one point with zero variance and infinite likelihood
- To make the means exact
- To make smaller