Exercise: fitting a mixture with EM

Goal

By the end of this exercise you should be able to:

  • run EM by hand on a small 1D example: E-step (responsibilities) and M-step (weighted means, variances, weights);
  • explain why the log-likelihood never decreases, why EM finds a local maximum, and why a component that collapses onto one point makes the likelihood infinite;
  • relate k-means to EM (hard versus soft assignments);
  • choose K and the covariance type with BIC and AIC, in words and with numbers.

Do the pen-and-paper part first, then the two demos. Questions marked (math) are for those who want the derivations; the concept questions do not depend on them.

Background

Word Meaning
E-step r_{ik} = \pi_k\mathcal N(\mathbf x_i \mid \boldsymbol\mu_k, \Sigma_k) / \sum_j\pi_j\mathcal N(\mathbf x_i \mid \boldsymbol\mu_j, \Sigma_j)
M-step N_k = \sum_i r_{ik}, \pi_k = N_k/n, \boldsymbol\mu_k = \frac1{N_k}\sum_i r_{ik}\mathbf x_i, \Sigma_k = \frac1{N_k}\sum_i r_{ik}(\mathbf x_i - \boldsymbol\mu_k)(\mathbf x_i - \boldsymbol\mu_k)^\top
Log-likelihood \log p(\mathcal D) = \sum_i\log\sum_k\pi_k\mathcal N_k(\mathbf x_i); never decreases under EM
Collapse a component on one point with \sigma \to 0: \log p(\mathcal D) \to \infty
Variance floor add \varepsilon to every variance after the M-step
BIC, AIC -2\log p(\mathcal D) + p\ln n and -2\log p(\mathcal D) + 2p; smaller is better

By hand

B1. Data 1, 2, 4, 7, 9, 10 (the k-means example). Start \mu = (2, 8), \sigma^2 = (4, 4), \pi = (0.5, 0.5). (a) Show that with equal variances and weights r_1(x) = 1/(1 + e^{-a}) with a = [(x - 8)^2 - (x - 2)^2]/8. Compute r_1(4) and r_1(7). (The others are 1.00, 0.99, 0.00, 0.00 for x = 1, 2, 9, 10; more precisely 0.998, 0.989, 0.002, 0.001.) (b) M-step: compute N_1, \mu_1, \mu_2 and \pi_1. (c) Compare with the k-means result (2.33, 8.67). Which point is “shared”, and how does that show in \mu_1 and \mu_2? (d) The log-likelihood over the first iterations is -14.94, -14.22, -14.03, -13.99. What would a decrease tell you?

B2. A smaller example: points 0, 2, 3; start \mu = (0, 4), \sigma^2 = (1, 1), \pi = (0.5, 0.5). (a) E-step: compute all responsibilities. (Use r_1(x) = 1/(1 + e^{-a}) with a = [(x - 4)^2 - x^2]/2.) (b) M-step: N_k, \mu_k, \sigma_k^2, \pi_k.

B3. Two groups of points overlap in the middle. A point lies exactly halfway between the two current means; both components have the same variance and weight. (a) What does k-means do with it, and what does EM do? (b) In the M-step, how much does the point pull on each mean in k-means, and in EM?

B4. BIC and AIC. You fitted 1D mixtures to n = 1000 pixel intensities and got \log p(\mathcal D) = -4210, -4020, -4012, -4010 for K = 1, 2, 3, 4. (a) Give the number of parameters p for each K. (b) Compute BIC and AIC. Which K does each choose? (c) Explain in words why they differ.

B5. Choosing the covariance type. Two components fitted to n = 200 points in 2D give \log p(\mathcal D) = 273.0 with diagonal covariances and 274.7 with full covariances. Compute both BICs. Which model does BIC prefer, and what does that say about the shape of the groups?

B6. Predict and explain: you start EM with one component placed exactly on an outlier point, far from the rest, with a small variance. What happens in the next few iterations? What would you see in the log-likelihood plot? How do you fix it?

B1. (a) With equal \sigma^2 and \pi, the constants cancel: r_1 = \frac{e^{-(x-2)^2/8}}{e^{-(x-2)^2/8} + e^{-(x-8)^2/8}} = \frac{1}{1 + e^{-[(x-8)^2 - (x-2)^2]/8}}. At x = 4: a = (16 - 4)/8 = 1.5, r_1 = 0.82. At x = 7: a = (1 - 25)/8 = -3, r_1 = 0.05. (b) N_1 = 0.998 + 0.989 + 0.818 + 0.047 + 0.002 + 0.001 = 2.85; \mu_1 = (0.998 + 2 \cdot 0.989 + 4 \cdot 0.818 + 7 \cdot 0.047 + \dots)/2.85 = 2.31; N_2 = 3.15, \mu_2 = 8.39; \pi_1 = 2.85/6 = 0.48. (Variances: \sigma^2 = (1.87, 2.83).) (c) The point 4 is shared: 82 % of it goes to component 1, 18 % to component 2. It pulls \mu_2 down from 8.67 to 8.39 and \mu_1 slightly down (2.31 instead of 2.33, since 4 counts only 0.82 while 7 adds a little). After convergence EM ends at (2.34, 8.66): close to k-means, because the groups are well separated. (d) A bug (or a modified algorithm): exact EM can never decrease the log-likelihood.

B2. (a) x = 0: a = 8, r_1 = 0.9997. x = 2: a = 0, r_1 = 0.5. x = 3: a = -4, r_1 = 0.018. (b) N_1 = 1.518, N_2 = 1.482; \mu_1 = (0 + 1 + 0.054)/1.518 = 0.69, \mu_2 = (0.001 + 1 + 2.946)/1.482 = 2.66; \sigma_1^2 = 0.94, \sigma_2^2 = 0.23; \pi = (0.51, 0.49).

B3. (a) k-means gives it fully to one of the two (whichever wins the tie). EM gives it responsibility 0.5 to each. (b) k-means: weight 1 on one mean, 0 on the other. EM: weight 0.5 on each; it pulls both means a little towards the middle.

B4. (a) p = 3K - 1: 2, 5, 8, 11. (b) BIC = -2\log p + p\ln 1000 (\ln 1000 = 6.91): 8433.8, 8074.5, 8079.3, 8096.0: K = 2. AIC = -2\log p + 2p: 8424, 8050, 8040, 8042: K = 3. (c) Going from 2 to 3 components improves -2\log p by 16 at the cost of 3 parameters. AIC charges 2 \times 3 = 6 and accepts; BIC charges 3 \times 6.91 = 20.7 and refuses. BIC’s penalty grows with n, so for large data sets it prefers simpler models.

B5. p = 9 (diagonal: 1 + 4 + 4) and p = 11 (full: 1 + 4 + 6); \ln 200 = 5.30. BIC: -546.0 + 47.7 = -498.3 (diagonal) and -549.4 + 58.3 = -491.1 (full). BIC prefers the diagonal model: the two extra covariance numbers improve the fit by only 1.7 in \log p. The groups are (close to) axis-aligned ellipses; their correlations are not needed.

B6. The component owns the outlier with responsibility close to 1 and almost nothing else. The M-step puts its mean on the outlier and its variance becomes (almost) zero; its density at the outlier explodes and the log-likelihood shoots up to a huge value in one or two iterations, then stays there (in practice limited by a numerical minimum variance). The plot shows a sudden jump, not a gentle rise. Fix: a variance floor, removing or restarting the component, starting from k-means(++) or from several starts, or a robust model (heavy-tailed components).

Math questions

B7. (math) Starting from \log p(\mathcal D) = \sum_i\log\sum_k\pi_k\mathcal N(\mathbf x_i \mid \boldsymbol\mu_k, \Sigma_k), derive the M-step for \boldsymbol\mu_k (set the gradient to zero) and for \pi_k (with a Lagrange multiplier for \sum_k\pi_k = 1).

B8. (math) Prove Jensen’s bound \log p(\mathbf x_i) \ge \sum_k q_i(k)\log\frac{\pi_k\mathcal N_k(\mathbf x_i)}{q_i(k)} for any distribution q_i, show that it is tight for q_i(k) = r_{ik}, and use it to show that one EM iteration cannot decrease \log p(\mathcal D).

B9. (math) Take \Sigma_k = \sigma^2 I for all k, fixed, and \pi_k = 1/K, fixed. Show that as \sigma \to 0 the responsibilities become 0 or 1 (for points with a unique nearest centre), and that EM becomes k-means.

B10. (math) Show that the likelihood of a 1D mixture with two components is unbounded: put \mu_2 = x_1 and let \sigma_2 \to 0 while component 1 is fixed. Why does this not happen with a single Gaussian (unless all points are equal)?

B7. \partial/\partial\boldsymbol\mu_k of \log\sum_j\pi_j\mathcal N_j(\mathbf x_i) is \frac{\pi_k\mathcal N_k(\mathbf x_i)}{\sum_j\pi_j\mathcal N_j(\mathbf x_i)}\Sigma_k^{-1}(\mathbf x_i - \boldsymbol\mu_k) = r_{ik}\Sigma_k^{-1}(\mathbf x_i - \boldsymbol\mu_k). Summing over i and setting to zero (multiply by \Sigma_k): \sum_i r_{ik}(\mathbf x_i - \boldsymbol\mu_k) = 0, so \boldsymbol\mu_k = \sum_i r_{ik}\mathbf x_i/N_k. For \pi_k: \partial/\partial\pi_k[\log p(\mathcal D) - \lambda(\sum_j\pi_j - 1)] = \sum_i\mathcal N_k(\mathbf x_i)/p(\mathbf x_i) - \lambda = \sum_i r_{ik}/\pi_k - \lambda = 0, so \pi_k = N_k/\lambda; \sum_k\pi_k = 1 and \sum_k N_k = n give \lambda = n. The r_{ik} depend on the parameters, so these are fixed-point equations; EM iterates them.

B8. \log is concave, so \log\sum_k q_k y_k \ge \sum_k q_k\log y_k for weights q_k \ge 0 summing to 1 (Jensen). With y_k = \pi_k\mathcal N_k(\mathbf x_i)/q_i(k), the left side is \log p(\mathbf x_i). For q_i(k) = r_{ik}, y_k = p(\mathbf x_i) for all k, and both sides are \log p(\mathbf x_i). Write \mathcal L(q, \theta) = \sum_i\sum_k q_i(k)\log\frac{\pi_k\mathcal N_k(\mathbf x_i)}{q_i(k)}. E-step: q = r^{\text{old}}, so \mathcal L(q, \theta^{\text{old}}) = \log p(\mathcal D \mid \theta^{\text{old}}). M-step: \theta^{\text{new}} maximises \mathcal L(q, \theta) over \theta (only \sum_i\sum_k q_i(k)[\log\pi_k + \log\mathcal N_k(\mathbf x_i)] depends on \theta: weighted one-Gaussian fits). Then \log p(\mathcal D \mid \theta^{\text{new}}) \ge \mathcal L(q, \theta^{\text{new}}) \ge \mathcal L(q, \theta^{\text{old}}) = \log p(\mathcal D \mid \theta^{\text{old}}).

B9. r_{ik} = \frac{\exp(-\lVert\mathbf x_i - \boldsymbol\mu_k\rVert^2/2\sigma^2)}{\sum_j\exp(-\lVert\mathbf x_i - \boldsymbol\mu_j\rVert^2/2\sigma^2)} (the constants and equal weights cancel). Divide numerator and denominator by the term of the nearest centre k^*: r_{ik} = 1/\sum_j\exp(-(d_j^2 - d_k^2)/2\sigma^2). For k = k^* all other exponents are negative and \to -\infty: r_{ik^*} \to 1; for k \ne k^* the term j = k^* has a positive exponent \to +\infty: r_{ik} \to 0. The M-step mean with 0/1 weights is the mean of the points nearest to \boldsymbol\mu_k: exactly k-means’ update.

B10. p(x_1) \ge \pi_2\mathcal N(x_1 \mid x_1, \sigma_2^2) = \pi_2/(\sqrt{2\pi}\sigma_2) \to \infty, and for i \ne 1, p(x_i) \ge \pi_1\mathcal N_1(x_i) > 0, a fixed positive number. So \prod_i p(x_i) \to \infty. With one Gaussian, shrinking \sigma to fit x_1 makes every other point’s density go to zero (like e^{-(x_i - \mu)^2/2\sigma^2}, much faster than 1/\sigma grows), so the likelihood goes to 0, not infinity; its maximum is at the sample variance, which is positive unless all points are equal.

Explore: EM step by step

The demo shows 6–12 points on a line (drag them) and the current mixture: each weighted component \pi_k\mathcal N(x \mid \mu_k, \sigma_k^2) dashed, their sum in black, the means as vertical lines. Points are coloured by their responsibilities. The tables give r_{ik} for every point and N_k, \mu_k, \sigma_k^2, \pi_k per component; the readout gives \log p(\mathcal D) after every M-step. E-step and M-step do one half-step each. Options: hard assignments, equal variances and weights, and a variance floor \varepsilon = 0.1.

P1. Preset the by-hand example. Do one E-step and one M-step and compare the tables with B1. Then alternate until nothing changes. Is \log p always increasing? Where does it end?

P2. Preset an ambiguous point in the middle. What is the responsibility of the point 5.5 at the start and at the end? Why does it not change?

P3. Preset collapse: one component on one point. Alternate E and M. Write down \log p after each M-step. What happens to \sigma_2^2? Now tick variance floor and repeat (reset first).

P4. Preset hard EM = k-means. Run to convergence. Compare the means with B1 of the k-means unit. Untick hard assignments (keep equal variances and weights), reset and run again: does the result change?

P1. After the E-step: r_{i1} = 1.00, 0.99, 0.82, 0.05, 0.00, 0.00; after the M-step N = (2.85, 3.15), \mu = (2.31, 8.39), \sigma^2 = (1.87, 2.83), \pi = (0.48, 0.52). \log p: -14.94 \to -14.22 \to -14.03 \to -13.99, always increasing, and it converges at -13.99 with \mu = (2.34, 8.66), \sigma^2 = 1.57 for both, \pi = (0.5, 0.5).

P2. 0.50 at the start and 0.50 at the end. The data and the start are symmetric about 5.5 (points 1, 2, 3 and 8, 9, 10; means 2 and 9; equal variances and weights), so every iteration keeps the symmetry: the point is always exactly halfway, with equal densities and equal weights. EM ends at \mu = (2.50, 8.50), \sigma^2 = 2.08 for both.

P3. Without the floor: \log p = -16.59 \to -14.58 \to -14.24 \to -12.97 \to -2.13. Component 2 sits on the single point 10; its variance shrinks from 8 to 10^{-10} (the demo’s numerical minimum) and the spike makes \log p jump. With a smaller numerical minimum the jump would be larger still: the likelihood is unbounded. With the floor \varepsilon = 0.1: -16.59 \to -14.59 \to -14.27 \to -13.20 \to -12.50, and \sigma_2^2 stops at 0.1: still a narrow component on one point, but with finite likelihood. (Is one point a “group”? Unit 4 calls such points anomalies.)

P4. The means end at (2.33, 8.67), exactly the k-means answer. \log p goes -29.41 \to -16.40 \to -15.27 \to -13.99. With soft assignments (equal variances and weights still fixed to be equal) EM ends at (2.34, 8.66), \log p = -13.99: almost the same here, because the groups are well separated; it takes more iterations (13 M-steps instead of 4), since the start (1, 2) makes both components share all points at first.

Explore: EM in 2D

The main demo of the day. The points come from a dataset (seeded); click to add points, drag them, or remove them. Choose K, the covariance type (spherical, diagonal, full, tied) and the start (random points, k-means, k-means++ seeds, or by hand: drag the centres). E-step, M-step, step and run fit the mixture; points are coloured by their responsibilities, ellipses are 1σ (solid) and 2σ (dashed), and the background shows the regions of the most probable component (or the density). Right: \log p(\mathcal D) per iteration (a red ring would mark a decrease), 20 restarts (histogram of the final \log p), BIC / AIC for K = 1..6, and the variance floor \varepsilon. k-means (hard) switches to Lloyd’s algorithm for comparison.

E1. Preset well separated. Press run. What are the final \log p and weights? Press 20 restarts: do all runs end at the same value?

E2. Preset elongated: k-means fails, full GMM works. It starts in k-means mode: run and describe the groups. Switch to EM (soft) and run. Compare the groups, and look at the ellipses.

E3. Preset one big, one small: weights matter. Run. Where is the boundary (background) compared with the k-means bisector? What are the weights?

E4. Preset bad start: local maximum. Run. What is the final \log p, compared with E1 (same data)? Describe the solution. Press new start, then run.

E5. Preset collapse (floor off). Run and watch the \log p plot and the readout. Then set the floor to 10^{-4} (reset and run). Compare.

E6. Preset K too large: BIC says no. Read the BIC and AIC bars. Which K does each choose? Relate to B4.

E7. Presets diagonal is enough and diagonal is not enough. In each, compare the BIC values for diagonal and full covariances (switch Σ and press BIC / AIC). When are the extra parameters worth it?

E8. Preset heavy overlap: soft labels near 0.5. Run. Which points have mixed colours? Would a hard label be trustworthy there?

E1. \log p(\mathcal D) = 179.7 with weights 0.33, 0.33, 0.33 (three blobs of 50 points). (The log-likelihood is positive because the points live in the unit square, where densities are larger than 1.) Of 20 restarts from k-means, 19 end at 179.7 and one at 140.4, a local maximum.

E2. k-means cuts across both cigars (J = 3.079; only 125 of 160 points grouped as in the cigars). EM with full covariances ends at \log p = 245.6 with two long, thin, tilted ellipses, one per cigar: 146 of the 160 points are grouped as in the two cigars. The covariance lets each component follow the shape of its group.

E3. Weights 0.80 and 0.20; the wide component’s region extends around the small, tight group, and the boundary lies close to the small group, not halfway between the centres. All 150 points get the label of the group they came from (k-means: 138).

E4. \log p = 123.4, far below 179.7: one component covers two blobs (weight 0.67), the other two share one blob (0.08 and 0.25). No single EM step can move a component across the empty gap. A new start (k-means) finds 179.7 again.

E5. Without a floor the third component sits on the outlier at (0.88, 0.15): after one iteration \log p jumps from -62.0 to 203.1 and then 203.9; its variance is at the numerical minimum 10^{-10}, and the readout reports a collapse. With \varepsilon = 10^{-4}, \log p = 190.1 and the component is a small circle (variance 10^{-4}, i.e. σ = 0.01) on the outlier: finite, and visibly an “outlier component” with weight 0.01.

E6. BIC is smallest at K = 2 (the two blobs), AIC at K = 4. As in B4, AIC’s penalty (2 per parameter) is smaller than BIC’s (\ln 100 = 4.6 per parameter), so AIC accepts extra components that improve the fit only slightly.

E7. Diagonal is enough (axis-aligned clouds): BIC at K = 2 is -498.3 for diagonal and -491.0 for full: the two correlations are not worth their cost. Diagonal is not enough (tilted cigars): with diagonal covariances BIC is smallest at K = 4 (-361.1): it needs a staircase of axis-aligned blobs to cover each tilted cigar. With full covariances BIC is -439.9 at K = 1 and -435.3 at K = 2: far better than any diagonal model, and one tilted ellipse (or two) suffices. (BIC slightly prefers one big ellipse around both cigars here: the cigars are close together.)

E8. The points in the overlap region, between the two centres, have mixed colours: 26 of the 100 points have responsibilities between 0.3 and 0.7. A hard label there is close to a coin toss; the soft label says so honestly.

Code

Write the algorithms of this unit yourself, in Rust. Setup, and how to run and check your code: coding exercises: getting started. Your code goes in gmm/src/em/exercise.rs. The code works in 1D, like the by-hand exercises: a mixture is its weights \pi_k, means \mu_k and variances \sigma_k^2.

C1. e_step(data, m): the responsibilities r_{ik} and the log-likelihood \sum_i \log p(x_i) of the current mixture. The checks are B1(a), B2(a) and the first log-likelihood of B1(d), -14.94.

log p = 0
for every point i:
    for every k:  q_k = π_k · N(x_i | μ_k, σ_k²)
    p = Σ_k q_k;   log p = log p + log(p)
    for every k:  r_ik = q_k / p

C2. m_step(data, r, floor): N_k = \sum_i r_{ik}, \pi_k = N_k/n, the weighted mean and the weighted variance of every component, and the variance at least floor. The checks are B1(b) and B2(b).

C3. em(data, start, floor, tol, max_iterations): alternate C1 and C2 until the log-likelihood rises by less than tol, and record it after every E-step. The checks: the trace of B1(d), -14.94, -14.22, -14.03, -13.99, the converged means (2.34, 8.66), and a log-likelihood that never goes down.

C4. bic_aic(log_likelihood, p, n): \text{BIC} = -2\log p(\mathcal D) + p\ln n and \text{AIC} = -2\log p(\mathcal D) + 2p. The checks are your tables of B4 and B5.

Then cargo run -p gmm -- em and open the pictures in out/em/.

C5. The program starts EM on the points of B1 with a third component on the point 10, with variance 0.1: once with a variance floor of 10^{-6}, once with a floor of 0.5. Read the log-likelihood traces and the final mixtures. Which run collapses, and how does it show? Is the collapsed fit better?

C6. 1000 grey values drawn from the lecture’s three classes (background: weight 0.6, mean 60, \sigma = 15; cytoplasm: 0.3, 130, 20; nucleus: 0.1, 200, 15). The program fits K = 1, \dots, 5, each from 10 random starts, and keeps the best. Which K do BIC and AIC choose? How close is the fit for K = 3 to the truth? What does “worst start” tell you? Look at grey-k3.png and grey-k4.png (the histogram, the components in colour, their sum in black).

The model solution is gmm/src/em/solution.rs in the download.

C5. With the floor 10^{-6} the third component collapses onto the point 10: its variance falls to the floor (\sigma^2 = 0.000) and the log-likelihood jumps from -14.43 to -13.16, -7.96, -7.84, far above the -13.99 of the two-component fit. Only the floor stops it from rising without bound (B10). The fit is not better, it is nonsense: a spike on one data point, while the second component covers 7 and 9 alone. With the floor 0.5 the log-likelihood rises gently (-14.43, -13.97, -13.75, \dots) and the third component shares the right-hand group: means 7.03 and 9.50, both variances at the floor of 0.5.

C6. BIC: 10639.0, 10195.9, 10110.5, 10131.2, 10151.9; AIC: 10629.2, 10171.4, 10071.2, 10077.2, 10083.2. Both choose K = 3: from 3 to 4 components the log-likelihood does not improve at all (-5027.6). The fit for K = 3: weights 0.59, 0.31, 0.10, means 60.4, 127.9, 200.6, standard deviations 14.9, 17.9, 16.4 (variances 221.0, 321.9, 269.1), close to the truth. For K = 3 the worst of the 10 starts ended at -5080.7, the value of the best two-component fit: a local maximum, in which one group is covered by two components or two groups by one. Restarts are needed. With K = 4 the picture shows the same sum curve as for K = 3, with the background peak split between two components.

Where this leads

EM fits mixtures to any points: pixels in a feature space, or objects in a feature table. Unit 4 applies it to images: mixtures of grey levels (the thresholding day’s minimum-error threshold for K classes), colour segmentation, populations of cells, and anomalies.