Exercise: the multivariate Gaussian and the mixture model

Goal

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

  • read a 2D Gaussian from its picture: the mean, the covariance ellipse with the eigenvectors of \Sigma as axes and \sqrt{\lambda_i} as half-lengths;
  • compute and interpret the Mahalanobis distance;
  • count the parameters of a mixture for each covariance type;
  • describe a mixture as a recipe for data, and compute responsibilities by Bayes’ rule;
  • (math) derive the maximum-likelihood mean of one Gaussian and the linear boundary of tied covariances.

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

Background

Word Meaning
Covariance \Sigma variances on the diagonal, covariances off it; symmetric, positive definite
1σ ellipse points with d_M = 1: axes along the eigenvectors of \Sigma, half-lengths \sqrt{\lambda_1}, \sqrt{\lambda_2}
Mahalanobis distance d_M^2 = (\mathbf x - \boldsymbol\mu)^\top\Sigma^{-1}(\mathbf x - \boldsymbol\mu)
Mixture p(\mathbf x) = \sum_k \pi_k\mathcal N(\mathbf x \mid \boldsymbol\mu_k, \Sigma_k), weights \pi_k \ge 0 summing to 1
Responsibility r_k(\mathbf x) = \pi_k\mathcal N_k(\mathbf x)/p(\mathbf x)
Covariance types spherical (\sigma_k^2I), diagonal, full, tied (one \Sigma for all)

By hand

B1. \Sigma = \begin{pmatrix} 5 & 2 \\ 2 & 2\end{pmatrix}, \boldsymbol\mu = \mathbf 0. (a) Find the eigenvalues and unit eigenvectors. (Check: they must add up to the trace and multiply to the determinant.) (b) Sketch the 1σ and 2σ ellipses. What are the half-axes, and at what angle is the long axis?

B2. Same Gaussian. The inverse is \Sigma^{-1} = \frac16\begin{pmatrix} 2 & -2 \\ -2 & 5\end{pmatrix}. (a) Compute the Euclidean and the Mahalanobis distance of P = (2, 1) and of Q = (-1, 2). (b) Which of the two would you call unusual? Explain with your sketch from B1.

B3. You fit a mixture with K = 3 components to colour pixels (d = 3). Count the parameters for spherical, diagonal, full and tied covariances. Which would you try first with 500 pixels? With 50 000?

B4. A 1D mixture of two components: \pi = (0.7, 0.3), \mu = (100, 160), \sigma = (20, 20). (a) Compute r_1 at x = 120, 130 and 140. (b) Where is the boundary r_1 = r_2? Why is it not at 130? (c) What happens to the boundary if \pi = (0.5, 0.5)?

B5. Four points: (0, 0), (2, 2), (1, 3), (3, 1). (a) Compute the maximum-likelihood mean and covariance (divide by n = 4). (b) Give the eigenvalues and eigenvectors of your covariance and sketch the 1σ ellipse over the points.

B6. Predict, with a sketch, the boundary between two equally weighted 2D components when (a) both have \Sigma = I; (b) both have the same tilted, elongated \Sigma; (c) one is a small circle and the other a large circle around a nearby centre.

B7. A microscope image contains 70 % background pixels (dark), 25 % cytoplasm (grey) and 5 % nuclei (bright). (a) Write down the mixture that could have produced the grey values, in words and as a formula. (b) A grey value lies exactly halfway between the cytoplasm and nucleus means, and both components have the same σ. Which label does Bayes’ rule give it, and why?

B1. (a) \det(\Sigma - \lambda I) = (5 - \lambda)(2 - \lambda) - 4 = \lambda^2 - 7\lambda + 6 = 0: \lambda_1 = 6, \lambda_2 = 1 (sum 7 = trace, product 6 = determinant). For \lambda = 6: (5 - 6)v_1 + 2v_2 = 0, so \mathbf v_1 = (2, 1)/\sqrt5; \mathbf v_2 = (-1, 2)/\sqrt5. (b) 1σ: half-axes \sqrt6 = 2.45 along \mathbf v_1 and 1 along \mathbf v_2; 2σ: twice that (4.90 and 2). The long axis is at \arctan(1/2) = 26.6°.

B2. (a) Both have Euclidean distance \sqrt5 = 2.24. d_M(P)^2 = \frac16(2 \cdot 4 - 2 \cdot 2 \cdot 2 \cdot 1 + 5 \cdot 1) = \frac56, d_M(P) = 0.91. d_M(Q)^2 = \frac16(2 \cdot 1 + 2 \cdot 2 \cdot 1 \cdot 2 + 5 \cdot 4) = 5, d_M(Q) = 2.24. (b) Q: it lies along the short axis, beyond the 2σ ellipse. P lies along the long axis and inside the 1σ ellipse: in the direction the data spread most, 2.24 units is less than one standard deviation.

B3. Weights 2 and means 9 in every case. Covariances: spherical 3, diagonal 9, full 18, tied 6. Totals: 14, 20, 29, 17. With 500 pixels, all are well determined, but full covariances with 29 numbers are already fine; with very few pixels per component (say 20), spherical or tied is safer. With 50 000 pixels, full covariances are no problem, and they can describe correlated channels (shadows, stains). (Unit 3 gives a criterion: BIC.)

B4. (a) r_1 = 0.91, 0.70, 0.34 at 120, 130, 140. At 130 the two densities are equal, so r_1 = 0.7/(0.7 + 0.3). (b) x = 130 + \frac{20^2}{60}\ln\frac{0.7}{0.3} = 130 + 5.65 = 135.6. The more frequent component wins near the midpoint, so the boundary moves towards the rarer one. (c) It moves to the midpoint, 130.

B5. (a) Mean (1.5, 1.5). Centred: (-1.5, -1.5), (0.5, 0.5), (-0.5, 1.5), (1.5, -0.5). S_{11} = (2.25 + 0.25 + 0.25 + 2.25)/4 = 1.25, S_{22} = 1.25, S_{12} = (2.25 + 0.25 - 0.75 - 0.75)/4 = 0.25. (b) \lambda_1 = 1.25 + 0.25 = 1.5 along (1, 1)/\sqrt2, \lambda_2 = 1 along (1, -1)/\sqrt2. A slightly elongated ellipse along the diagonal, half-axes 1.22 and 1.

B6. (a) The perpendicular bisector of the two means (as in k-means). (b) Still a straight line through the midpoint, but in general no longer perpendicular to the line joining the means: its normal is \Sigma^{-1}(\boldsymbol\mu_1 - \boldsymbol\mu_2), not \boldsymbol\mu_1 - \boldsymbol\mu_2. (c) A closed curve (a circle) around the small component; outside it, on all sides, the large component wins.

B7. (a) Pick background with probability 0.70, cytoplasm 0.25, nucleus 0.05; then draw the grey value from that class’s Gaussian: p(x) = 0.70\,\mathcal N(x \mid \mu_b, \sigma_b^2) + 0.25\,\mathcal N(x \mid \mu_c, \sigma_c^2) + 0.05\,\mathcal N(x \mid \mu_n, \sigma_n^2). (b) Cytoplasm: at the midpoint the two densities are equal, and cytoplasm is five times more frequent (r = 0.25/0.30 = 0.83). The boundary to “nucleus” lies further up, towards the nucleus mean.

Math questions

B8. (math) Show that the 1σ ellipse \{\mathbf x : d_M(\mathbf x) = 1\} has its axes along the eigenvectors of \Sigma with half-lengths \sqrt{\lambda_i}. (Write \Sigma = Q\Lambda Q^\top and change coordinates.)

B9. (math) Derive the maximum-likelihood mean of one Gaussian with known \Sigma from n points: set the gradient of \sum_i\log\mathcal N(\mathbf x_i \mid \boldsymbol\mu, \Sigma) to zero.

B10. (math) Show that two Gaussians with the same covariance \Sigma and weights \pi_1, \pi_2 have a linear Bayes boundary. Give its 1D form and check it against B4(b).

B11. (math) Show that |\Sigma| = \lambda_1\lambda_2, and explain why the peak height of a 2D Gaussian is 1/(2\pi\sqrt{\lambda_1\lambda_2}). What happens to the peak height when the ellipse collapses to a line (\lambda_2 \to 0)?

B8. \Sigma^{-1} = Q\Lambda^{-1}Q^\top. With \mathbf y = Q^\top(\mathbf x - \boldsymbol\mu) (a rotation: coordinates along the eigenvectors), d_M^2 = \mathbf y^\top\Lambda^{-1}\mathbf y = y_1^2/\lambda_1 + y_2^2/\lambda_2. d_M = 1 is the standard ellipse y_1^2/\lambda_1 + y_2^2/\lambda_2 = 1 in these coordinates: half-axes \sqrt{\lambda_1} and \sqrt{\lambda_2} along \mathbf v_1, \mathbf v_2.

B9. \sum_i\log\mathcal N(\mathbf x_i) = \text{const} - \frac12\sum_i(\mathbf x_i - \boldsymbol\mu)^\top\Sigma^{-1}(\mathbf x_i - \boldsymbol\mu). Its gradient in \boldsymbol\mu is \Sigma^{-1}\sum_i(\mathbf x_i - \boldsymbol\mu); since \Sigma^{-1} is invertible this is zero iff \sum_i(\mathbf x_i - \boldsymbol\mu) = 0, i.e. \hat{\boldsymbol\mu} = \frac1n\sum_i\mathbf x_i. The function is concave in \boldsymbol\mu (Hessian -n\Sigma^{-1}), so this is the maximum.

B10. Equal \pi_1\mathcal N_1 = \pi_2\mathcal N_2, take logs; the constants -\frac d2\log2\pi - \frac12\log|\Sigma| cancel, and so does -\frac12\mathbf x^\top\Sigma^{-1}\mathbf x, leaving \mathbf x^\top\Sigma^{-1}(\boldsymbol\mu_1 - \boldsymbol\mu_2) = \frac12(\boldsymbol\mu_1^\top\Sigma^{-1}\boldsymbol\mu_1 - \boldsymbol\mu_2^\top\Sigma^{-1}\boldsymbol\mu_2) + \log(\pi_2/\pi_1), linear in \mathbf x. In 1D: x(\mu_1 - \mu_2)/\sigma^2 = (\mu_1^2 - \mu_2^2)/(2\sigma^2) + \log(\pi_2/\pi_1), i.e. x = \frac{\mu_1 + \mu_2}{2} + \frac{\sigma^2}{\mu_2 - \mu_1}\log\frac{\pi_1}{\pi_2}. B4: 130 + \frac{400}{60}\ln\frac73 = 135.6.

B11. The determinant is the product of the eigenvalues (\det Q\Lambda Q^\top = \det\Lambda). At \mathbf x = \boldsymbol\mu the exponent is 0, so the density is 1/((2\pi)^{d/2}|\Sigma|^{1/2}) = 1/(2\pi\sqrt{\lambda_1\lambda_2}) for d = 2. As \lambda_2 \to 0 the peak height goes to infinity: the same total probability is squeezed onto a line. (This is how a mixture component “collapses” in unit 3.)

Explore

The demo shows one Gaussian (or a mixture of 2–3) with draggable handles: the circle moves the mean, the squares are the ends of the two 1σ half-axes (they rotate and stretch the ellipse). Drawn: the 1σ (solid), 2σ and 3σ (dashed) ellipses and 300 samples with a fixed seed. The probes P and Q can be dragged; the readout gives \Sigma, its eigenvalues and the angle, and the Euclidean and Mahalanobis distances of the probes. Σ restricts the shape (spherical, diagonal, full). In a mixture, the samples are coloured by the component that made them (hide colours removes that), the background shows the density or the most probable component, and the bar gives the responsibilities of P.

E1. Preset same Euclidean distance, different Mahalanobis. Check your answers to B1 and B2 in the readout. Drag P along the long axis until d_M = 1: where is it? Then drag Q onto the 2σ ellipse: what does the readout say?

E2. Preset tilted cigar. Read \Sigma, the eigenvalues and the angle. Now choose diagonal. What happens to the ellipse, and which entry of \Sigma is forced to zero? Choose spherical: what is left?

E3. Preset circle. For a spherical Gaussian with σ = 1.5, what is the relation between the Euclidean distance and the Mahalanobis distance of P? Check it.

E4. Preset two overlapping components: the hidden labels. Read the responsibilities of P. Tick hide colours: could you still tell which sample came from which component? Move the weight of component 1 from 0.6 to 0.3: how do the responsibilities of P change, although P did not move?

E5. Preset same covariance: straight boundary (background: most probable component). Describe the boundary. Where is P, and what are its responsibilities? Change one weight: what happens to the boundary?

E6. Preset different covariances: curved boundary. Describe the region of the narrow component. Drag P from (0, 0) to the left along the x axis, through the narrow component and beyond: how does the bar change? Explain with Q7 of the quiz.

E1. The readout gives \lambda_1 = 6.00, \lambda_2 = 1.00, angle 26.6°; P: Euclidean 2.24, Mahalanobis 0.91; Q: Euclidean 2.24, Mahalanobis 2.24. Along the long axis, d_M = 1 is at the end of the half-axis, about (2.19, 1.10), where the orange square is. Q on the 2σ ellipse shows Mahalanobis 2.00, whatever direction.

E2. \Sigma = [4.78\ 2.55;\ 2.55\ 1.83], \lambda_1 = 6.25, \lambda_2 = 0.36 (half-axes 2.5 and 0.6), angle 30°. Diagonal: the ellipse snaps to the axes (\Sigma_{12} = 0), keeping its half-axes: it can no longer describe the correlation. Spherical: a circle with one radius (the geometric mean of the two half-axes, \sqrt{2.5 \cdot 0.6} = 1.22).

E3. d_M = d_{\text{Euclid}}/\sigma: P has Euclidean 2.24 and Mahalanobis 2.24/1.5 = 1.49.

E4. P = (0.3, 0.3): 75 % component 1, 25 % component 2. With hidden colours the two clouds merge into one blob with a slightly irregular outline: you cannot tell which point came from which component, only that the density has two bumps. With weights 0.3 and 0.4 (normalised 0.43 and 0.57), P’s responsibility for component 1 drops to about 60 %: the responsibility combines the density at P with how frequent each component is.

E5. A straight line through the midpoint (0, 0), almost vertical (about 94°). The perpendicular bisector of the two means, which k-means would use, would be tilted at about 117°: the shared, tilted ellipse turns the boundary. P at (0, 0), halfway, has responsibilities 50 % / 50 %. Changing one weight shifts the line parallel to itself, away from the more frequent component.

E6. The narrow component (σ = 0.6) owns a closed, roughly circular island around its mean; the wide component (half-axes 2.2 and 1.4) owns everything else. At (0, 0), P is 57 % narrow. Moving left, the narrow share rises to about 100 % near its centre, then falls again: 77 % at x = -2.5, 37 % at x = -3 and almost 0 at x = -4. Far away, the wide Gaussian’s tails are heavier, so it wins on both sides: a curved (closed) boundary.

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/gaussian_mixture/exercise.rs. A Gaussian in 2D is its centre \boldsymbol\mu and its covariance matrix \Sigma.

C1. mahalanobis(x, g): the Mahalanobis distance, with the inverse of the 2 \times 2 matrix written out:

Σ = [[a, b], [b, d]]                    u = x1 − μ1,  v = x2 − μ2
d_M² = (d·u² − 2b·u·v + a·v²) / (a·d − b²)

The check is B2: d_M(P) = 0.91, d_M(Q) = 2.24.

C2. density(x, g): \mathcal N(\mathbf x \mid \boldsymbol\mu, \Sigma) = e^{-d_M^2/2} / (2\pi\sqrt{|\Sigma|}). The checks are the peak height of B11 and the demo’s densities at P and Q (0.043 and 0.005).

C3. responsibilities(x, weights, components): r_k = \pi_k\mathcal N_k(\mathbf x) / \sum_j \pi_j\mathcal N_j(\mathbf x). The check is B4, written in 2D.

C4. fit_gaussian(points): the maximum-likelihood mean and covariance (divide by n). The check is B5.

C5. sample_mixture(weights, components, n, rng): the recipe of the lecture. To draw from one Gaussian, turn two independent standard normal numbers into a point with the right covariance:

repeat n times:
    pick k with probability π_k                       # add up the π until they pass a uniform number
    z1, z2 = two standard normal numbers
    L11 = √a;   L21 = b / L11;   L22 = √(d − L21²)       # L Lᵀ = Σ = [[a, b], [b, d]]
    x = (μ1 + L11·z1,  μ2 + L21·z1 + L22·z2)
    output x, and k (the hidden label)

The check draws 20 000 points and refits each component with C4.

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

C6. The program draws 300 points from the lecture’s Gaussian \Sigma = \begin{pmatrix}5 & 2\\2 & 2\end{pmatrix} and counts those inside the 1σ and the 2σ ellipse (one-gaussian.png). Compare with what you expect: the share of a 2D Gaussian within d_M \le r is 1 - e^{-r^2/2} (math: derive it, in the coordinates of B8, with polar coordinates).

C7. A mixture of three components (mixture-coloured.png, mixture-hidden.png, mixture-most-probable.png). Are the fitted weights, means and covariances (with the labels known) close to the true ones? In the last picture, which component wins in the bottom right corner, far from all points, and why?

C8. Compare boundary-tied.png and boundary-different.png with the slide “Bayes boundaries: straight or curved” and with B6.

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

C6. 122 of 300 points (41 %) lie inside the 1σ ellipse and 257 (86 %) inside the 2σ ellipse. Expected: 1 - e^{-1/2} = 39.3 % and 1 - e^{-2} = 86.5 %. (Not the 68 % and 95 % of 1D.) Derivation: in the rotated and scaled coordinates y_i/\sqrt{\lambda_i} the Gaussian is round and standard, with density \frac{1}{2\pi}e^{-\rho^2/2}; the probability of \rho \le r is \int_0^r \rho\, e^{-\rho^2/2}\,d\rho = 1 - e^{-r^2/2}.

C7. Yes, within the noise of 600 points: 289, 196 and 115 points (weights 0.48, 0.33, 0.19 against 0.5, 0.3, 0.2), means within 0.2 of the true ones, covariances such as \begin{pmatrix}2.06 & 1.23\\1.23 & 0.99\end{pmatrix} against \begin{pmatrix}2 & 1.2\\1.2 & 1\end{pmatrix}. At the point (4, 3), between components 1 and 2, the responsibilities are 0.78, 0.22 and 0.00. In the bottom right corner component 1 (the round one, blue) wins, although the elongated component 2 is nearer: component 2 is very narrow across its long axis, so its density falls off fastest in that direction. Far away the broadest component in that direction wins.

C8. With the same (tilted) covariance the boundary is a straight line, not perpendicular to the line between the two means (B6(b)). With a small round and a large round component the small one wins only inside a closed curve; the large one wins on every side (B6(c)).

Where this leads

We can now describe each group by a Gaussian and say how likely each point is to belong to it, if we know the parameters. Unit 3 finds the parameters from unlabelled data with the EM algorithm: guess soft labels, refit the Gaussians, repeat. The Mahalanobis distance of this unit is the gate around a predicted position in tracking.