Gaussian mixtures and the EM algorithm
K-means on the penguins' bills: the 25 ringed birds are in another species' cluster
Last time k-means sorted 342 penguins by their bills, with nobody telling it the species, and got 93% of them right. The 25 it got wrong are not random: they sit where the species' clouds, which are tilted ellipses, cross the straight borders k-means draws. Today we replace each round cluster by a Gaussian with a shape of its own, fit it with the EM algorithm, and see how many birds it gives back.
By the end you can
About 75 minutes, with a duel between k-means and the mixture, and EM by hand on six points.
It builds on k-means and on Gaussian discriminant analysis.
Both see only the standardized bill length and depth, k = 3. K-means' circles are the round, equal clusters it assumes; the mixture's ellipses are fitted, one shape per cluster.
Over all birds, longer bills are shallower (correlation −0.24); inside each species they are deeper (+0.39, +0.65, +0.64). That is what tilts the three clouds.
Dataset
| \(x_1\) | \(x_2\) |
|---|---|
| -0.5 | -0.4 |
| 0.6 | 0.1 |
| -0.7 | 0.8 |
| … | … |
How to find \(\mu_1, \mu_2, \Sigma_1, \Sigma_2\)?
Part 2 of 5
What process could have produced these birds?
Dataset
| \(x\) |
|---|
| 181 |
| 186 |
| 195 |
| 193 |
| … |
Assume:
Observations \(x^{(i)} \in \mathbb{R}\). Each dot is a bird; flippers are measured in whole millimetres, so birds stack. The curves are the two Gaussians EM finds, \(\mu = 191, 216\) mm and \(\sigma = 6.5, 7.3\) mm: Adelie and Chinstrap together, then Gentoo.
Soft assignment: find \(P(z^{(i)} = j \mid x^{(i)})\)
the probability that point \(i\) belongs to cluster \(j\), once we have seen the point \(x^{(i)}\)
\(z^{(i)}\), the cluster of point \(i\), is never observed: it is a latent (hidden) variable
K-means gave each point one cluster, \(c^{(i)}\). A mixture gives each a probability for every cluster. A bird with a 204 mm flipper is about as likely to be in either.
Observations: \(x^{(i)} \in \mathbb{R}\). Number of clusters: \(k > 0\).
The hidden cluster of point \(i\): \(z^{(i)} \in \{1, \dots, k\}\).
The parameters are \(\phi \in \mathbb{R}^k\) with \(\sum_{j=1}^k \phi_j = 1\) (how common each cluster is), and for each cluster a mean and a variance. In \(d\) dimensions \(\mu_j \in \mathbb{R}^d\) and \(\sigma_j^2\) becomes a covariance matrix \(\Sigma_j \in \mathbb{R}^{d \times d}\).
This is the model of Gaussian discriminant analysis (GDA), from the classification lectures, with one difference: there \(z\) was the species, written in the data. Here it is hidden.
\(\phi_1 =\) 0.30 \(\xrightarrow{\text{sample}} \mathcal{N}(\mu_1, \sigma_1^2) \xrightarrow{} x^{(i)}\)
\(\phi_2 =\) 0.70 \(\xrightarrow{\text{sample}} \mathcal{N}(\mu_2, \sigma_2^2) \xrightarrow{} x^{(i)}\)
With \(\mu_1 = 1\), \(\sigma_1 = 1.3\), \(\mu_2 = 3\), \(\sigma_2 = 1.6\). First choose a cluster with probability \(\phi_j\), then draw \(x\) from its Gaussian.
Each bar shows the samples from one cluster (cluster 1 in teal, cluster 2 in red), under that cluster's dashed curve; the white curve is their sum, the density of the data. In real data the colors are gone: we see only the total, and EM's job is to guess the colors back.
Each made bird: a component \(j\) with probability \(\phi_j\) (0.46, 0.18, 0.35), then a bill from \(\mathcal{N}(\mu_j, \Sigma_j)\). The species' true shares are 0.44, 0.20, 0.36.
A generative model is judged by whether what it makes looks like the data. These look like penguins' bills: three tilted clouds, overlapping where the real ones do.
| \(x^{(i)} \in \mathbb{R}^d\) | point \(i\), for \(i = 1, \ldots, n\) (here \(d = 2\): bill length and depth, standardized) |
| \(k\) | the number of clusters (components), chosen by us |
| \(z^{(i)} \in \{1, \ldots, k\}\) | the hidden cluster of point \(i\); k-means guessed it as \(c^{(i)}\) |
| \(\phi_j = P(z = j)\) | how common cluster \(j\) is; \(\phi \in \mathbb{R}^k\), \(\sum_j \phi_j = 1\) |
| \(\mu_j \in \mathbb{R}^d,\ \Sigma_j \in \mathbb{R}^{d \times d}\) | the mean and covariance of cluster \(j\) |
| \(w_j^{(i)} = P(z^{(i)} = j \mid x^{(i)})\) | the responsibility of cluster \(j\) for point \(i\); \(W \in \mathbb{R}^{n \times k}\), rows sum to 1 |
| \(\ell(\phi, \mu, \Sigma)\) | the log-likelihood of the data, next slide |
| \(J(c, \mu)\) | k-means' distortion, as before |
We want the parameters that make \(\ell\) largest. For GDA this had a closed form, because each point's cluster was known. Here each term is the log of a sum over the unknown cluster, and setting the gradient to zero ties every \(\mu_j\) to all the others. EM is a way around that.
Part 3 of 5
How do you fit a model whose labels are hidden?
E-Step: Guess \(z^{(i)}\) given \(\phi, \mu, \sigma\). Compute \(P(z^{(i)} \mid x^{(i)}; \phi, \mu, \sigma)\)
M-Step: Estimate \(\phi, \mu, \sigma\) using Maximum Likelihood Estimation
The green factor is the Gaussian density of cluster \(j\) at the point, the purple one how common cluster \(j\) is. Their product, divided by the same product summed over all clusters, is a number between 0 and 1, and the \(k\) of them for one point add up to 1.
The penguin highlighted in the k-means lecture, a Chinstrap, was 1.09 standard deviations from the Gentoo center and 1.11 from the Chinstrap one, so k-means gave it to the Gentoo. The Chinstrap Gaussian is tilted towards it, and its responsibility is 0.97.
Maximum Likelihood Estimation
This is Gaussian discriminant analysis (GDA), from the classification lectures. When every bird's species \(z^{(i)}\) is known, each Gaussian is fitted to its own birds. The indicator \(1\{z^{(i)} = j\}\) is 1 if bird \(i\) is in cluster \(j\) and 0 otherwise, so each sum runs over the birds of cluster \(j\) only. Inside each species longer bills are deeper (correlations +0.39, +0.65, +0.64), which tilts the ellipses.
Compare with GDA on the previous slide: the formulas are the same, with the responsibility \(w_j^{(i)}\) where GDA had the indicator \(1\{z^{(i)} = j\}\). In GDA each bird counts fully in one cluster (weight 1) and not at all in the others (weight 0); here it counts with weight \(w_j^{(i)}\) in every cluster. Found without the species, EM's ellipses come out close to the species' own, with a higher \(\ell\).
From this start \(\ell\) climbs from −1069 to −822.0 (dashed) in 46 iterations, never falling; from k-means' clusters it takes 39.
So \(\ell\) rises or stays, and stops at a stationary point: a local maximum, not always the highest one. The CS229 notes on EM (cs229.stanford.edu) give the general argument.
The points are \(1, 2, 3, 7, 8, 12\). Start with \(\mu_1 = 2\), \(\mu_2 = 3\), \(\phi_1 = \phi_2 = \tfrac12\), and keep \(\sigma_1 = \sigma_2 = 1\) fixed.
Hint: with equal \(\phi\) and \(\sigma\), \(w_1 = \dfrac{1}{1 + e^{x - 2.5}}\) (work it out from the E-step formula). A phone calculator is enough.
| \(x\) | \(w_1\) | \(w_2\) |
|---|---|---|
| 1 | 0.82 | 0.18 |
| 2 | 0.62 | 0.38 |
| 3 | 0.38 | 0.62 |
| 7 | 0.01 | 0.99 |
| 8 | 0.00 | 1.00 |
| 12 | 0.00 | 1.00 |
\(\phi = (0.30,\ 0.69), \quad \mu_1 = 1.80, \quad \mu_2 = 7.13\)
\(\mu_1\) is a weighted mean that leans on 1, 2 and 3 (weights 0.82, 0.62, 0.38) and barely on the rest. \(\mu_2\) takes 3 at weight 0.62 and the right group almost fully, so it jumps to 7.13, close to k-means' 7.5: with \(\sigma = 1\) the points far from the start are already nearly hard.
Repeated, EM stops after 4 iterations at \(\mu = (2,\ 9)\) with \(\phi = (0.5,\ 0.5)\), where k-means stopped too: the groups are far apart compared with \(\sigma\).
With equal round Gaussians the E-step compares only distances:
$$w_j^{(i)} = \frac{e^{-\lVert x^{(i)} - \mu_j \rVert^2 / 2\sigma^2}}{\sum_s e^{-\lVert x^{(i)} - \mu_s \rVert^2 / 2\sigma^2}}$$
As \(\sigma\) shrinks the nearest center takes all the weight: \(w\) becomes \(1\{c^{(i)} = j\}\) (1 if k-means puts point \(i\) in cluster \(j\), 0 otherwise) and the M-step is k-means' update. From \(\sigma = 0.2\) down, every bird is assigned as k-means does.
Part 4 of 5
What does the mixture see that k-means did not?
The mixture misplaces 12 birds, k-means 25. It also says where it might be wrong: 25 birds have no responsibility above 0.9, and 7 of the 12 mistakes are among them. K-means' \(c^{(i)}\) is equally confident about every bird.
| with their species | bills | all four |
|---|---|---|
| k-means | 93% | 92% |
| spherical | 92% | 94% |
| diag | 84% | 64% |
| tied | 96% | 99% |
| full | 96% | 99% |
Round clusters do no better than k-means, and clusters stretched only along the axes do worse: the species are tilted. The gain comes from the tilt. On all four measurements a full mixture misplaces 5 of 342 birds.
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import multivariate_normal
# Seed for reproducibility
np.random.seed(42)
# Generate synthetic data from 3 Gaussian distributions
mean1, cov1 = [5, 5], [[1, 0], [0, 1]]
mean2, cov2 = [0, 0], [[1, 0], [0, 1]]
mean3, cov3 = [8, 1], [[1, 0], [0, 1]]
data1 = np.random.multivariate_normal(mean1, cov1, 100)
data2 = np.random.multivariate_normal(mean2, cov2, 100)
data3 = np.random.multivariate_normal(mean3, cov3, 100)
# Combine all data
data = np.vstack((data1, data2, data3))
# Number of clusters
k = 3
n, d = data.shape
print(n, 'points in', d, 'dimensions')
It prints 300 points in 2 dimensions. Run this block, then the next two.
# Initialize parameters
phi = np.ones(k) / k # equal mixing weights
mu = np.random.rand(k, d) * 10 # random means in the square [0, 10]^2
Sigma = np.array([np.eye(d) for _ in range(k)]) # identity covariance matrices
# EM algorithm parameters
max_iter = 100
tol = 1e-6
log_likelihoods = []
print('starting means:', np.round(mu, 2).tolist())
It prints the three starting means: [[2.29, 7.22], [7.2, 6.41], [6.94, 5.43]].
for iteration in range(max_iter):
# E-step: compute responsibilities w_j^(i)
p = np.zeros((n, k))
for j in range(k):
p[:, j] = phi[j] * multivariate_normal.pdf(data, mean=mu[j], cov=Sigma[j])
log_likelihood = np.sum(np.log(p.sum(axis=1))) # l(phi, mu, Sigma) before this update
w = p / p.sum(axis=1, keepdims=True)
# M-step: update phi (mixing weights), mu (means) and Sigma (covariances)
Nk = w.sum(axis=0)
phi = Nk / n
mu = (w.T @ data) / Nk[:, np.newaxis]
for j in range(k):
diff = data - mu[j]
Sigma[j] = (w[:, j, np.newaxis] * diff).T @ diff / Nk[j]
log_likelihoods.append(log_likelihood)
# Check for convergence
if iteration > 0 and abs(log_likelihood - log_likelihoods[-2]) < tol:
print(f'Converged at iteration {iteration}')
break
print('log-likelihood:', ' '.join(f'{v:.1f}' for v in log_likelihoods[:6]), '...', f'{log_likelihoods[-1]:.2f}')
print('means:', np.round(mu, 2).tolist())
fig, ax = plt.subplots(1, 2, figsize=(9, 4))
ax[0].scatter(data[:, 0], data[:, 1], c=w.argmax(axis=1), s=10)
ax[0].plot(mu[:, 0], mu[:, 1], 'kx', markersize=12)
ax[1].plot(log_likelihoods, 'o-')
ax[1].set_xlabel('iteration'); ax[1].set_ylabel('log-likelihood')
plt.show()
It prints Converged at iteration 17; log-likelihood: -5185.3 -1315.4 -1266.9 -1233.7 -1203.9 -1198.6 ... -1157.42; means: [[0.13, 0.04], [4.89, 5.03], [7.95, 0.87]].
import numpy as np
import pandas as pd
d = pd.read_csv('penguins.csv').dropna(subset=['bill_length_mm', 'bill_depth_mm'])
X = d[['bill_length_mm', 'bill_depth_mm']].values
X = (X - X.mean(axis=0)) / X.std(axis=0) # standardize, as for k-means
n, dim = X.shape
def log_gauss(X, mu, S): # log N(x; mu, S) for every row of X
diff = X - mu
q = np.sum(diff @ np.linalg.inv(S) * diff, axis=1)
return -0.5 * (dim * np.log(2 * np.pi) + np.log(np.linalg.det(S)) + q)
def em(X, k, rng, iters=500):
phi = np.ones(k) / k
mu = X[rng.choice(n, k, replace=False)] # k random birds as the first means
S = np.array([np.eye(dim)] * k)
for _ in range(iters):
lp = np.stack([np.log(phi[j]) + log_gauss(X, mu[j], S[j]) for j in range(k)], axis=1)
ll = np.logaddexp.reduce(lp, axis=1) # log p(x(i)), summed in logs
w = np.exp(lp - ll[:, None]) # E-step: responsibilities, n by k
Nk = w.sum(axis=0) # M-step
phi, mu = Nk / n, (w.T @ X) / Nk[:, None]
S = np.array([((w[:, j, None] * (X - mu[j])).T @ (X - mu[j])) / Nk[j] + 1e-6 * np.eye(dim) for j in range(k)])
return w, ll.sum()
rng = np.random.default_rng(0)
runs = [em(X, 3, rng) for _ in range(10)] # 10 starts, keep the highest log-likelihood
w, ll = max(runs, key=lambda r: r[1])
print(f'log-likelihood = {ll:.1f}')
print(pd.crosstab(w.argmax(axis=1), d.species)) # the species were never used above
print('birds with no responsibility above 0.9:', int((w.max(axis=1) < 0.9).sum()))
It prints log-likelihood = -822.0, a table with 330 of 342 birds on the matched diagonal, and birds with no responsibility above 0.9: 25.
Part 5 of 5
How many components, and when does EM go wrong?
\(\text{BIC} = -2\,\ell + p \log n\)
\(p\) counts \(k - 1\) weights, \(k d\) means and \(k\, d(d+1)/2\) covariances. BIC is lowest at k = 3 on the bills (1951, 1795, 1743, 1761, 1786, 1801, 1809 for k = 1 to 7) and on all four measurements. The notebook's AIC, \(-2\ell + 2p\), charges less per parameter.
159 of 200 end at \(\ell = −822.0\). The others stop at \(\ell = −862.1, −858.2\): Chinstrap and Gentoo share one component and the spare one goes elsewhere, mostly to part of the Adelie (205 to 278 birds with their species). The notebook's fixes: start from k-means' clusters, or run several starts and keep the highest \(\ell\).
At its own mean a Gaussian's density is \(1/(\sigma_j\sqrt{2\pi})\), so as \(\sigma_j\) shrinks onto a shared value, \(\ell\) grows without bound.
Out of 100 random starts it happens 0, 0, 4, 22, 32, 59 times for k = 2, 3, 4, 5, 6, 8. The notebook's fixes: add a small number to every variance (scikit-learn adds \(10^{-6}\)), use fewer components, restart.