Gaussian Mixture Models and EM algorithm
Overview
Gaussian Mixture Models (GMM) are probabilistic models that assume data comes from a mixture of several Gaussian distributions, each representing a cluster. The Expectation-Maximization (EM) algorithm is an iterative method to find the parameters of these Gaussians when we don't know which data point belongs to which cluster.
Think of it like genres: a movie isn't purely "action" or "drama" — it's 60% action, 40% drama. GMMs capture this blend naturally.
The Mathematical Foundation
where:
- = number of mixture components (clusters)
- = mixing coefficient for component (satisfies , )
- = Gaussian distribution with mean and covariance
WHY this form? We're saying: "Pick cluster with probability , then generate a point from that cluster's Gaussian." The sum marginalizes over all possible cluster choices.
Deriving the Gaussian Component
The multivariate Gaussian distribution is:
WHY this formula?
- The exponent is the Mahalanobis distance squared — it measures how far is from accounting for correlations (captured by )
- The normalizing constant ensures
- comes from integrating the Gaussian over dimensions
- accounts for the "volume" of the covariance ellipsoid
The EM Algorithm: From First Principles
THE PROBLEM: We have data but we don't know which cluster generated each point. We need to estimate .
WHY is this hard? If we knew cluster assignments, estimating parameters would be easy (just compute means and covariances). If we knew parameters, computing assignments would be easy (just use Bayes' rule). We know neither! This is a chicken-and-egg problem.
Introducing Latent Variables
Let be the hidden cluster label for . The complete-data log-likelihood would be:
WHY this form? The indicator picks out which cluster belongs to, and we log the probability of that choice () times the probability of under that Gaussian.
But we don't observe ! So we maximize the incomplete-data log-likelihood:
This is hard to maximize directly because the log of a sum has no closed form.
By Jensen's inequality, for any distribution :
WHY does this help? The lower bound is easier to maximize. We alternate:
- E-step: Fix , choose to make the bound tight:
- M-step: Fix , maximize with respect to to get
E-Step: Computing Responsibilities
We need , called the responsibility .
By Bayes' rule:
WHY this step? Numerator: prior probability of cluster times likelihood of under cluster . Denominator: total probability over all clusters (normalization).
WHAT does mean? The probability that point was generated by cluster . If , point is 80% likely from cluster 3.
M-Step: Updating Parameters
We maximize the expected complete-data log-likelihood:
Substituting responsibilities:
Deriving update:
WHY this derivative? Only the quadratic term in the Gaussian depends on .
Setting to zero:
where is the effective number of points in cluster .
WHAT does this mean? The new mean is the weighted average of all points, weighted by their responsibility to cluster . Points strongly in cluster () pull the mean toward them; points weakly in have little effect.
Deriving update:
Similarly (taking derivative of log-determinant and quadratic terms):
WHY? Weighted average of squared deviations from the mean — the definition of covariance, responsibility-weighted.
Deriving update:
We maximize subject to using a Lagrange multiplier :
Suming over :
WHAT does this mean? The mixing coefficient is the fraction of all responsibility assigned to cluster .
Initialize: Choose , initialize , , randomly or via K-means
Repeat until convergence:
E-step: Compute responsibilities for all :
M-step: Update parameters for all :
Convergence: Stop when log-likelihood change < threshold or max iterations reached.
Worked Examples
Data: ,
Initialize:
- (from data endpoints)
- (arbitrary small variance)
E-step iteration 1:
For :
WHY these values? Plug into the Gaussian formula. Point 1 is very close to (distance 0.5) but far from (distance 8.5).
WHAT does this mean? Point 1 is essentially100% assigned to cluster 1.
Similarly:
- (point 2 → cluster 1)
- (point 9 → cluster 2)
- (point 10 → cluster 2)
M-step iteration 1:
WHY? Two points strongly in cluster 1, two in cluster 2.
WHY this step? Weighted average of all points, but only points 1 and 2 have non-zero weight for cluster 1.
WHY? Variance is the weighted average of squared deviations. Both points are0.5 away from mean 1.5.
Result: After one iteration, the clusters have tightened ( decreased from 1 to 0.25), means are stable. The algorithm would converge quickly since the data is well-separated.
Data:
- Cluster 1:
- Cluster 2:
- Ambiguous point:
After convergence:
- For the ambiguous point :
WHY 50/50? The point is equidistant from both cluster centers, so it has equal responsibility to both. This is the key advantage of GMM: soft assignments capture uncertainty.
If we forced hard assignment (like K-means), we'd arbitrarily put it in one cluster, losing information. GMM says "this point is genuinely ambiguous — it's half from each cluster."
For convergence checking, we compute:
For point with :
If , , and the Gaussians evaluate to and $0.001:
WHY sum? Total probability is the mixture of both components.
Sum over all points to get total log-likelihood. If it changes by less than between iterations, we've converged.
Common Mistakes and Fixes
Wrong: Compute and use directly.
Why it feels right: We computed the probability of under cluster , that should be the responsibility!
Why it's wrong: Without the denominator, . Responsibilities are conditional probabilities and must sum to 1 for each point.
Fix: Always include the normalizing sum:
Wrong: A cluster colapses to a single point, making , which breaks the Gaussian evaluation (divide by zero).
Why it happens: If all points in a cluster have identical coordinates (or nearly identical due to numerical issues), the covariance becomes singular.
Why it's dangerous: The algorithm crashes or produces NaN values.
Fix: Add regularization by adding a small diagonal term: where is a small constant. This ensures is always positive definite.
Steel-man: "I don't want to add artificial variance — it's not in the data!" True, but with zero variance, the model is saying "this cluster generates only one exact point with infinite precision," which is physically unrealistic. The regularization represents measurement noise or model uncertainty.
Wrong: Initialize all randomly from a uniform distribution without looking at the data.
Why it feels right: Random initialization works for gradient descent on neural networks, so it should work here too!
Why it's wrong: EM is sensitive to initialization. If two means start very close together, they may stay close (both trying to model the same cluster) while another cluster is missed entirely.
Fix: Use K-means++ for initialization:
- Run K-means to convergence (fast, simple)
- Use K-means cluster centers as
- Use K-means cluster covariances as
- Use K-means cluster sizes to initialize
Why this works: K-means gives a good rough clustering, and EM refines it with soft assignments.
Wrong: Run EM once, get result, assume it's the best possible clustering.
Why it feels right: EM is guaranteed to increase the likelihood each iteration, so it must converge to the global maximum!
Why it's wrong: EM is guaranteed to converge to a local maximum, not necessarily the global one. Different initializations lead to different local maxima.
Fix: Run EM multiple times (5-10) with different random initializations, pick the result with highest final log-likelihood.
Steel-man: "But that's computationally expensive!" Yes, but it's necessary. The log-likelihood landscape is non-convex with many local maxima. Think of it like training neural networks: you try different random seeds and pick the best.
Choosing the Number of Clusters K
Unlike K-means, GMM is probabilistic, so we can use model selection criteria:
Akaike Information Criterion (AIC):
where is the number of parameters, is the maximum likelihood.
Bayesian Information Criterion (BIC):
WHY BIC over AIC? BIC penalizes model complexity more heavily (factor of vs. 2). For GM, BIC often performs better at avoiding overfitting.
HOW to use: Fit GMMs with and plot BIC. Choose with the lowest BIC.
Parameter count for GMM:
- mixing coefficients (constraint: sum to 1)
- means
- covariance parameters (symmetric matrices)
Total:
Connections
- K-Means Clustering: GM is a soft version of K-means; K-means is GM with spherical covariances and hard assignments
- Maximum Likelihood Estimation: EM maximizes the likelihood of observed data under the mixture model
- Bayes Theorem: Responsibilities are computed via Bayes' rule
- Expectation Maximization Algorithm: GM is the most common application of the general EM framework
- Principal Component Analysis: GMM covariances capture data spread like PCA, but per-cluster
- Hidden Markov Models: HMMs useEM with similar E-step (forward-backward) and M-step updates
- Variational Inference: Modern Bayesian GMs use variational EM (more robust, automatic selection)
- Anomaly Detection: Points with low probability under all mixture components are outliers
- Density Estimation: GMs model the full probability density, useful for generative modeling
Or think: Evaluate, then Modify. You evaluate where points belong, then modify the cluster parameters accordingly.
Recall Explain to a 12-year-old
Imagine you have a bag of red and blue marbles mixed together, but someone painted them all gray so you can't tell which is which. You know there are about half red and half blue, and you want to figure out which gray marble was originally which color.
You start by guessing: "I think the smaller marbles were red and the bigger ones were blue."
Then you look at each marble and say: "This is medium-sized... it's probably 60% likely to be red and 40% likely to be blue." You're not sure, so you hedge your bets.
Now you update your guess: "Okay, if I treat this marble as 60% red, then the average size of red marbles is probably this much..." You recalculate the average size of reds and blues based on these partial assignments.
Then you go back and look at each marble again with your new averages: "Hmm, with this new average, maybe this marble is actually 70% red, not 60%."
You keep going back and forth — updating your guess about which marbles are which color, then updating your guess about what the average red and blue sizes are — until your guesses stop changing. That's the EM algorithm! You're alternating between estimating assignments (E-step) and updating parameters (M-step).
GMs do this with data points and clusters instead of marbles and colors.
Flashcards
#flashcards/ai-ml
What does GMM stand for and what is its key advantage over K-means? :: Gaussian Mixture Model. Key advantage: soft assignments — each point has a probability of belonging to each cluster, capturing uncertainty, rather than hard assignment to one cluster.
What are the three parameters of a GMM component?
What is the formula for the responsibility γ_ik?
What does the E-step compute inEM for GMM?
What does the M-step update in EM for GMM?
What is N_k in the EM M-step?
Why does EM converge to a local maximum, not global?
What is the update formula for the GM mean μ_k?
What is the update formula for GM mixing coefficient π_k?
How do you prevent singular covariance matrices in GMM?
What
Concept Map
Hinglish (regional understanding)
Intuition Hinglish mein samjho
Chalo, is concept ko simple tarike se samajhte hain. Socho tumhare paas kaafi saara data hai, jaise students ke marks ya movies ki ratings, aur tumhe pata hai ki ye alag-alag groups ya clusters mein aata hai. K-means jaisa method har point ko sirf ek hi cluster mein daal deta hai — "hard assignment". Lekin real life mein cheezein itni clear-cut nahi hoti. Ek movie 60% action aur 40% drama ho sakti hai, na? Yahi pe Gaussian Mixture Models (GMM) kaam aate hain. Ye maan lete hain ki data kai saare Gaussian distributions (bell curves) ka mixture hai, aur har point ko probability deta hai ki wo kis cluster ka hai — yani "soft assignment". Isse real-world ki uncertainty naturally capture ho jaati hai.
Ab problem ye hai ki humein data toh dikhta hai, par ye nahi pata ki kaunsa point kis Gaussian se aaya. Ye ek chicken-and-egg problem hai — agar cluster assignments pata hote toh parameters (mean, covariance) nikalna easy hota, aur agar parameters pata hote toh assignments nikalna easy hota. Par dono mein se kuch bhi pata nahi! Isko solve karne ke liye EM (Expectation-Maximization) algorithm use hota hai. Ye iterative tarike se kaam karta hai: pehle E-step mein current parameters use karke guess karta hai ki har point kis cluster ka kitna hai (probabilities), phir M-step mein un guesses ke basis pe parameters update karta hai. Ye process repeat hoti rehti hai jab tak cheezein stable na ho jaayein.
Ye concept matter isliye karta hai kyunki real-world data aksar simple, clear boundaries wala nahi hota — overlap hota hai, uncertainty hoti hai. GMM tumhe flexibility deta hai clusters ke shapes aur sizes ke saath (covariance matrix ki wajah se ellipse-shaped clusters bhi ban sakte hain, sirf round nahi). Aur EM algorithm ek powerful general technique hai jo tab kaam aati hai jab tumhare paas hidden ya missing information ho — isliye ye sirf clustering mein nahi, balki bahut saare probabilistic models mein use hoti hai. Toh yaad rakhna: GMM = soft, probabilistic clustering, aur EM = wo smart trick jo hidden variables ke saath parameters seekhne mein madad karti hai.