Gaussian Mixtures and EM
🫧 What is a Gaussian mixture? A Gaussian mixture says each point was drawn from one of
kGaussians, each with its own mean, covariance and share of the data. Expectation-maximization (EM) fits it by alternating two steps: work out how much each Gaussian is responsible for each point, then refit each Gaussian to the points weighted by those responsibilities.
It is the usual next question after k-means in a classic-ML coding round: the same loop with soft assignments, and a much better test of whether you can keep probabilities from underflowing.
The Prompt
The two EM steps are short; the round is decided by log-space arithmetic, a covariance that stays invertible, and a stopping rule you can defend.
"Fit a Gaussian mixture model with EM. Given
Xof shape(n, d)andk, return the weights, means, covariances and each point's responsibilities."
Clarifying Questions
You: Full covariances, or diagonal?
Interviewer: Full. We can talk about diagonal after.
You: How do I initialize? I'd pick k distinct data points as means, use the data covariance for every
component, and equal weights, with a seed.
Interviewer: Fine. Also accept initial means as an argument.
You: When do I stop?
Interviewer: Your call. Explain it.
You: A component can collapse onto a single point, and its covariance becomes singular. May I add a small constant to the diagonal?
Interviewer: Yes, make it a parameter.
What You'll Build
log_gaussian(X, mu, cov) -> (n,): the log density of every point under one Gaussian.e_step(X, w, mu, cov) -> (resp, loglik): responsibilities(n, k)whose rows sum to one, and the total log likelihood.m_step(X, resp, reg) -> (w, mu, cov): weights(k,), means(k, d), covariances(k, d, d).gmm_em(X, k, ...) -> (w, mu, cov, resp, history): the loop, with the log likelihood per iteration.