Skip to content

MLDay 18 of 50Supervised and Unsupervised Learning

Gaussian Mixtures and EM

7 min read

A scooter company logs where 300 riders parked, and wants to know how many scooters sit on each of two crossing streets. k-means cuts the map into round patches, so each patch grabs pieces of both streets. The groups are long and thin, and they overlap where the streets meet.

The idea

A Gaussian is a bell-shaped cloud of points: dense at its centre, the mean, and thinning out from there. Its covariance sets the cloud's shape: round, stretched or tilted. A Gaussian mixture models the data as a few such clouds, each with a weight π\pi: its share of the points.

Instead of one hard label, each point gets a responsibility for each cluster: the chance that this cluster produced it. A scooter in the middle of one street gets 1.00 and 0.00. A scooter at the crossing might get 0.56 and 0.44.

The fitting method, EM (expectation–maximization), repeats two steps, like k-means' assign and update:

  1. E-step: hold the clusters fixed and compute every point's responsibilities.
  2. M-step: hold the responsibilities fixed and refit each cluster's weight, mean and covariance. Each point counts towards a cluster in proportion to its responsibility.

No round can lower the log-likelihood, a score of how well the mixture explains the points (higher is better). EM stops when the score stops rising. Like k-means, it can settle on a poor answer from a bad start.

k-means behaves like a mixture whose clouds are all round, the same size and the same weight, with every responsibility rounded to 0 or 1.

A tiny example

Two clusters, A and B, with equal weights of 0.5. Three scooters sit along one road, at positions 2, 4 and 9.

E-step for the scooter at 4. A cluster's density at a point is the height of its bell curve there: taller means more typical. Say A's density at 4 is 0.3 and B's is 0.1. Then

  • A's share: 0.5 × 0.3 = 0.15, and B's: 0.5 × 0.1 = 0.05.
  • The responsibility of A is 0.15 / (0.15 + 0.05) = 0.75, and B gets the other 0.25.

Say the scooter at 2 is deep in A (responsibility 1.0), and the one at 9 is deep in B (0.0 for A).

M-step for A. Its new mean weights each position by A's responsibility: (1.0 × 2 + 0.75 × 4 + 0 × 9) / (1.0 + 0.75 + 0) = 5 / 1.75 ≈ 2.86. Its new weight is 1.75 out of 3 points, about 0.58. k-means would hand the scooter at 4 wholly to A, putting A's centre at 3.

The formula

The E-step gives each point its responsibilities:

rik=πk pk(xi)∑jπj pj(xi)r_{ik} = \frac{\pi_k \, p_k(x_i)}{\sum_j \pi_j \, p_j(x_i)}
Symbol Meaning
rikr_{ik} the responsibility of cluster kk for point ii, between 0 and 1
πk\pi_k cluster kk's weight: its share of the points
pk(xi)p_k(x_i) cluster kk's density at point xix_i
∑j\sum_j a sum over all the clusters, so each point's responsibilities add up to 1

Worked: r=0.5×0.30.5×0.3+0.5×0.1=0.150.20=0.75r = \frac{0.5 \times 0.3}{0.5 \times 0.3 + 0.5 \times 0.1} = \frac{0.15}{0.20} = 0.75.

The M-step moves each mean to the responsibility-weighted average of the points:

μk=∑irik xi∑irik\mu_k = \frac{\sum_i r_{ik} \, x_i}{\sum_i r_{ik}}
Symbol Meaning
μk\mu_k cluster kk's new mean
∑i\sum_i a sum over all nn points
∑irik\sum_i r_{ik} cluster kk's share of the points, counted fractionally; divided by nn, it's the new weight πk\pi_k

Worked: μA=1.0×2+0.75×4+0×91.75=51.75≈2.86\mu_A = \frac{1.0 \times 2 + 0.75 \times 4 + 0 \times 9}{1.75} = \frac{5}{1.75} \approx 2.86, and πA=1.75/3≈0.58\pi_A = 1.75 / 3 \approx 0.58.

Try it

Scooters on two crossing streets

E-step: each point shares itself among the clusters by how likely each one makes it (its colour blends). M-step: each cluster refits its weight, centre and spread from those shares.

24682468East (100 m)North (100 m)(1, 5.2), not assigned yet(2, 4.8), not assigned yet(3, 5.1), not assigned yet(4, 4.9), not assigned yet(5.5, 5), not assigned yet(6, 5.2), not assigned yet(7, 4.8), not assigned yet(8, 5.1), not assigned yet(9, 4.9), not assigned yet(5.2, 1), not assigned yet(4.8, 2), not assigned yet(5.1, 3), not assigned yet(4.9, 4), not assigned yet(5, 4.5), not assigned yet(5.2, 6), not assigned yet(4.8, 7), not assigned yet(5.1, 8), not assigned yet(4.9, 9), not assigned yetcluster 1 mean (4.8, 2), weight 0.5cluster 2 mean (9, 4.9), weight 0.5

log-likelihood -93.003steps 0

The log-likelihood measures how well the mixture explains the points; each E-step plus M-step can only raise it.

The two clusters start as wide, round clouds. Press Assign (E-step) and Update (M-step) a few times: the clouds barely move at first. Keep going, or press Run. After about 15 rounds each cloud snaps into a thin ellipse along one street, and the log-likelihood climbs from −93 to −46 without ever falling. These ellipses can only stretch along the axes; scikit-learn's default, covariance_type="full", also lets them tilt.

In code

scikit-learn's GaussianMixture runs EM. This parks 150 scooters along each of two diagonal streets, then compares k-means with a 2-cluster mixture and asks BIC (a score where lower is better) how many clusters there are.

# script_id: day_018_gaussian_mixtures_em/streets
import os
from pathlib import Path

import matplotlib.pyplot as plt
import numpy as np
from sklearn.cluster import KMeans
from sklearn.mixture import GaussianMixture

rng = np.random.default_rng(42)

def street(angle, n=150):                       # scooters parked along one street through (0, 0)
    t = np.radians(angle)
    along, across = rng.normal(0, 3.0, n), rng.normal(0, 0.3, n)   # long and thin; units of 100 m
    return np.column_stack([along * np.cos(t) - across * np.sin(t), along * np.sin(t) + across * np.cos(t)])

X = np.vstack([street(45), street(-45)])        # two streets crossing at right angles
street_id = np.repeat([0, 1], 150)

def match(labels):                              # cluster numbers are arbitrary, so allow a swap
    return max((labels == street_id).mean(), (labels != street_id).mean())

km = KMeans(n_clusters=2, random_state=42).fit(X)
gm = GaussianMixture(n_components=2, random_state=42).fit(X)   # covariance_type="full"
print(f"k-means puts {match(km.predict(X)):.0%} of scooters on the right street")
print(f"the mixture puts {match(gm.predict(X)):.0%} there")
spots = np.array([[3, 3], [0, 0], [3, -3]])     # on one street, at the crossing, on the other
print("responsibilities:\n", gm.predict_proba(spots).round(2))
bics = [GaussianMixture(n_components=k, random_state=42).fit(X).bic(X) for k in range(1, 6)]
print("BIC for 1 to 5 clusters:", np.round(bics).astype(int))
k-means puts 65% of scooters on the right street
the mixture puts 95% there
responsibilities:
 [[1.   0.  ]
 [0.56 0.44]
 [0.   1.  ]]
BIC for 1 to 5 clusters: [2543 2023 2044 2078 2108]

Each row of predict_proba holds one point's responsibilities. The scooter at the crossing is split 0.56 / 0.44, and all 14 of the mixture's misses lie within about 100 m of it. BIC (Bayesian information criterion) scores a fit by how badly it explains the data plus a penalty for each parameter, so lower is better. It's lowest at 2 clusters: a third cluster costs more parameters than it gains.

# script_id: day_018_gaussian_mixtures_em/streets
FIG_DIR = Path(os.environ.get("ML_FIG_DIR", "figures"))
FIG_DIR.mkdir(exist_ok=True)
fig, axes = plt.subplots(1, 2, figsize=(6, 4), sharey=True)
axes[0].scatter(X[:, 0], X[:, 1], c=km.predict(X), cmap="coolwarm", s=8)
axes[1].scatter(X[:, 0], X[:, 1], c=gm.predict_proba(X)[:, 0], cmap="coolwarm", s=8)
axes[0].set(title="k-means", xlabel="East (100 m)", ylabel="North (100 m)")
axes[1].set(title="Gaussian mixture", xlabel="East (100 m)")
fig.suptitle("k-means cuts across the streets; the mixture follows them")
fig.tight_layout()
fig.savefig(FIG_DIR / "kmeans_vs_mixture.png", dpi=120)
plt.close(fig)

k-means cuts across the streets; the mixture follows them

On the right, colour is the responsibility, so scooters near the crossing fade to pale shades.

Quick check

Quick check

1. Cluster A has weight 0.2 and density 0.3 at a point; B has weight 0.8 and density 0.1. What is A's responsibility?

2. What does the M-step do?

3. BIC for 1, 2 and 3 clusters is 2543, 2023 and 2044. How many clusters should you pick?

Next

Day 19: Compress Features with PCA finds the few directions that hold most of the variation in many columns.

Next · Day 19 · 7 minCompress Features with PCA← Previous: Day 17 · Group Unlabeled Data with k-Means
Not tapped yet