Machine Learning

Gaussian Mixture Models and EM

Gaussian mixtures replace k-means hard assignments with posterior responsibilities, then EM turns those soft counts into weighted parameter updates.

status: reviewimportance: importantdifficulty 4/5math: graduateread: 22mlive demo

Concept Structure

Gaussian Mixture Models and EM

01Intuition

Start with the picture, metaphor, or geometric mechanism.

02Math

Make the objects explicit and connect them with notation.

03Code

Mirror the equations with runnable implementation details.

04Interactive Demo

Manipulate the mechanism and watch the idea respond.

2prerequisites
3next concepts
3related links

Learner Contract

What this page should let you do.

You are here becauseGaussian mixtures replace k-means hard assignments with posterior responsibilities, then EM turns those soft counts into weighted parameter updates.

This Machine Learning concept is the current idea: keep the same invariant visible across Intuition, Math, Code, Interactive Demo.

By the end4/4 sections ready | runnable code expected | live demo

Explain the mechanism, trace the main notation, and test one prediction in the live demo.

Do this firstIntuition

Read the intuition before the notation; the math should name a mechanism you already felt.

Then go nextVariational Inference (review)

Follow this edge after making one prediction here; the next page should reuse the result, not restart the route.

Test the linkManipulate one control and predict the visible change.Then continue to Variational Inference (review)

Claim/source review status

Substantive review recorded

1/1 claims have bounded review metadata; still check caveats and source scope.Metadata-derived; review may be AI-assisted. Not a human certification.
Claims1/1 reviewed
Sources5 cited
Codeattached
Demolive
Reviewed2026-07-02
Updatedpage 2026-07-02

Learning item flow

4/4 sections readyAsk about thisResearch room
ConceptGaussian Mixture Models and EMMachine Learning
5 sources attachedLocal snapshot ready
concept:machine-learning/gaussian-mixtures-em
01

01

Intuition

Build the mental picture first so the rest of the page has something to attach to.

Section prompt

k-means asks every point to pick one centroid. A Gaussian mixture model asks a softer question:

What fraction of responsibility should each component take for this point?

That one change matters. A point between two clouds is no longer forced into one cluster. It can be 70%70\% explained by the left Gaussian and 30%30\% by the right Gaussian. Those responsibility weights then become soft counts when the model updates its parameters.

This is the bridge from clustering to latent-variable modeling. The hidden variable ziz_i says which component generated xix_i, but we do not observe ziz_i. EM handles that missing label by alternating:

  1. E-step: infer the posterior responsibility rik=p(zi=kxi,θ)r_{ik}=p(z_i=k\mid x_i,\theta) under the current parameters;
  2. M-step: refit the mixture weights, means, and covariances using those responsibilities as weights.

The central mental model is:

k-means moves centroids using hard assignments; EM moves Gaussian parameters using soft assignments.

The caveat is just as important. EM improves the current likelihood objective for the chosen model family, but it is still local. Initialization, covariance constraints, outliers, feature scaling, and the chosen number of components can all change the answer.

02

02

Math

Translate the story into symbols, assumptions, and a derivation you can inspect.

Section prompt

Let each data point be xiRdx_i\in\mathbb R^d. A KK-component Gaussian mixture model defines the density

pθ(xi)=k=1KπkN(xiμk,Σk),p_\theta(x_i) = \sum_{k=1}^K \pi_k\, \mathcal N(x_i\mid \mu_k,\Sigma_k),

where:

  • πk0\pi_k\ge 0 is the mixture weight for component kk;
  • k=1Kπk=1\sum_{k=1}^K \pi_k=1;
  • μkRd\mu_k\in\mathbb R^d is the component mean;
  • ΣkRd×d\Sigma_k\in\mathbb R^{d\times d} is the component covariance matrix.

The observed-data log likelihood is

(θ)=i=1nlogk=1KπkN(xiμk,Σk).\ell(\theta) = \sum_{i=1}^n \log \sum_{k=1}^K \pi_k\, \mathcal N(x_i\mid \mu_k,\Sigma_k).

The log is outside a sum over hidden components, which is why the optimization is harder than fitting one Gaussian with known labels.

Introduce a hidden component label

zi{1,,K}.z_i\in\{1,\ldots,K\}.

If ziz_i were observed, we could count how many points belonged to each component and fit weighted Gaussian parameters. Since ziz_i is hidden, EM computes the posterior probability of each possible label.

E-step

Given the current parameters θold\theta^{old}, define the responsibility

rik=p(zi=kxi,θold)=πkoldN(xiμkold,Σkold)j=1KπjoldN(xiμjold,Σjold).r_{ik} = p(z_i=k\mid x_i,\theta^{old}) = \frac{ \pi_k^{old}\mathcal N(x_i\mid \mu_k^{old},\Sigma_k^{old}) }{ \sum_{j=1}^K \pi_j^{old}\mathcal N(x_i\mid \mu_j^{old},\Sigma_j^{old}) }.

For each point ii, the responsibilities sum to one:

k=1Krik=1.\sum_{k=1}^K r_{ik}=1.

These are soft assignments. In k-means, a point contributes either 11 or 00 to a cluster. In a GMM, a point can contribute 0.730.73 to one component and 0.270.27 to another.

M-step

Define the effective soft count

Nk=i=1nrik.N_k=\sum_{i=1}^n r_{ik}.

The updated mixture weight is

πknew=Nkn.\pi_k^{new} = \frac{N_k}{n}.

The updated mean is the responsibility-weighted average:

μknew=1Nki=1nrikxi.\mu_k^{new} = \frac{1}{N_k} \sum_{i=1}^n r_{ik}x_i.

The updated covariance is the responsibility-weighted scatter:

Σknew=1Nki=1nrik(xiμknew)(xiμknew).\Sigma_k^{new} = \frac{1}{N_k} \sum_{i=1}^n r_{ik} (x_i-\mu_k^{new})(x_i-\mu_k^{new})^\top.

The interactive demo uses diagonal covariances, so it tracks only the per-coordinate variances. The full formula above is the object being simplified.

What EM Guarantees

Exact EM can be understood as coordinate ascent on a lower bound to the observed-data log likelihood. The E-step makes the bound tight at the current parameters by using the posterior over hidden labels. The M-step increases that bound by refitting parameters to the soft counts. Therefore one exact EM iteration does not decrease the observed-data log likelihood.

This is a local guarantee, not a global one. Mixture likelihoods can have multiple local optima, component labels are interchangeable, and covariance estimates can become ill-conditioned without constraints or regularization.

03

03

Code

Keep the implementation aligned with the notation so the algorithm is legible.

Section prompt
import numpy as np

X = np.array([[-2.0, -0.6], [-1.4, 0.2], [-0.7, -0.1], [0.2, 0.0],
              [1.0, 0.4], [1.6, -0.2], [2.3, 0.5], [2.8, -0.3]])
pi = np.array([0.55, 0.45])
mu = np.array([[-1.2, -0.2], [1.4, 0.1]])
var = np.array([[0.9, 0.35], [0.8, 0.45]])  # diagonal covariance

def gaussian_diag(X, mu, var):
    d = X.shape[1]
    diff = X[:, None, :] - mu[None, :, :]
    norm = 1 / np.sqrt(((2 * np.pi) ** d) * var.prod(axis=1))
    return norm * np.exp(-0.5 * ((diff ** 2) / var[None, :, :]).sum(axis=2))

def log_likelihood(X, pi, mu, var):
    return np.log(gaussian_diag(X, mu, var) @ pi).sum()

density = gaussian_diag(X, mu, var)
r = (density * pi) / (density @ pi)[:, None]
Nk = r.sum(axis=0)
pi_new = Nk / len(X)
mu_new = (r.T @ X) / Nk[:, None]
diff = X[:, None, :] - mu_new[None, :, :]
var_new = (r[:, :, None] * diff ** 2).sum(axis=0) / Nk[:, None]

print("responsibility for middle point:", np.round(r[3], 3).tolist())
print("old log-likelihood:", round(log_likelihood(X, pi, mu, var), 3))
print("new mixture weights:", np.round(pi_new, 3).tolist())
print("new means:", np.round(mu_new, 3).tolist())
print("new log-likelihood:", round(log_likelihood(X, pi_new, mu_new, var_new), 3))

The code is one EM iteration. It computes densities for every point-component pair, normalizes them into responsibilities, uses those responsibilities as weights, and then checks that the updated parameters improve the observed-data log likelihood for this toy diagonal-covariance model.

04

04

Interactive Demo

Use direct manipulation to connect the explanation to a moving system.

Section prompt

The lab below turns the E-step into a prediction.

Choose a highlighted point and predict whether component 1, component 2, or both components should take responsibility. Before reveal, the responsibility values, weighted means, variances, and likelihood change are hidden. After reveal, inspect how the selected point splits its mass and how all points combine into the M-step update.

The ambiguous point is the key. A hard clustering method must choose one side. EM can say: this point is partly evidence for both components.

Live Concept Demo

Explore Gaussian Mixture Models and EM

The stage is code-native and interactive. Use it to test the explanation against the mechanism.

difficulty 4/5graduatecode-aligned
Demo Prediction Checkpoint

Manipulate one control and predict the visible change.

Commit to what Gaussian Mixture Models and EM should make visible before reading the result.

After The First Pass

Turn the concept into an inspected object.

Once the invariant is visible in the intuition, math, code, and demo, use these panels to inspect the mechanism visually, check source support, practice the idea, and attach a grounded research question.

Mechanism Storyboard

See the idea move before the page explains it

Gaussian mixtures replace k-means hard assignments with posterior responsibilities, then EM turns those soft counts into weighted parameter updates.

Prediction open01 / Intuition
Prediction lens

Start with the picture, metaphor, or geometric mechanism.

Commit first

Before reading further, choose the kind of change Gaussian Mixture Models and EM should make visible.

Visual Inquiry

Make the image answer a mathematical question

Gaussian mixtures replace k-means hard assignments with posterior responsibilities, then EM turns those soft counts into weighted parameter updates.

4/4 stages readyLive demo connected
Prediction

Which visible object should carry the first intuition?

Commit first

Pick the cue that should make Gaussian Mixture Models and EM easier to reason about before the page gives the answer.

Source Grounding

Canonical references for the mechanism on this page.

course-notes · 2020CS229 Notes: The EM AlgorithmStanford CS229

Supports latent-variable maximum likelihood, Jensen/ELBO framing, E-step posterior responsibilities, M-step parameter updates, and EM monotonicity.

Open source
course-notes · 2020CS229 Notes: K-means, Mixtures of Gaussians and the EM AlgorithmStanford CS229

Supports the bridge from k-means hard assignments to Gaussian mixture soft assignments.

Open source
reference · 2020Mathematics for Machine Learning: Gaussian Mixture Model TutorialDeisenroth, Faisal, Ong, and MML contributors

Code-facing source for responsibilities and weighted parameter updates.

Open source
book · 2022Probabilistic Machine Learning: An IntroductionKevin P. Murphy

Probabilistic-modeling anchor for mixture models, latent variables, maximum likelihood, and EM context.

Open source
documentation · 2026scikit-learn User Guide: Gaussian mixture modelsscikit-learn developers

Implementation-context source for covariance choices, initialization sensitivity, convergence behavior, and practical model-selection caveats.

Open source

Claim Review

Gaussian mixtures replace k-means hard assignments with posterior responsibilities, then EM turns those soft counts into weighted parameter updates.

Status1 substantive review recorded

Claims without a substantive review badge still need exact source-support review.

Sources5 references

cs229-2020-em-notes, cs229-2020-kmeans-gmm-notes, deisenroth-2020-mml-gmm-tutorial, murphy-2022-probml-intro, sklearn-2026-gaussian-mixtures

Local checks4 local checks

Use equations, runnable code, and demos to check whether the source support is operational.

Substantively reviewedGMM EM alternates posterior responsibilities with weighted parameter updates, improving the current observed-data likelihood without guaranteeing a global optimum.Claim metadata: source checked

The sources support the model density, E-step responsibility formula, M-step weighted estimates for pi/mu/Sigma, and the monotone likelihood statement under exact EM.

Sources: CS229 Notes: The EM Algorithm, CS229 Notes: K-means, Mixtures of Gaussians and the EM Algorithm, Mathematics for Machine Learning: Gaussian Mixture Model Tutorial, Probabilistic Machine Learning: An Introduction, scikit-learn User Guide: Gaussian mixture modelsThe demo uses a tiny diagonal-covariance two-component witness. It does not cover full covariance estimation, singular covariance pathologies, Bayesian mixtures, model-order selection, component-label non-identifiability, stochastic/online EM, or global optimum guarantees.A bounded review summary is present; still check caveats and exact reference scope.

Checked CS229 for EM responsibilities, weighted updates, and monotonicity; MML for code-facing formulas; ProbML/scikit-learn for caveats. GPT Pro remains pending.

Reviewer: codex-local-source-review; reviewed 2026-07-02

Practice Loop

Try the idea before it explains itself

Gaussian mixtures replace k-means hard assignments with posterior responsibilities, then EM turns those soft counts into weighted parameter updates.

Readiness0/3 checks ready
Predict

Before touching the demo, predict one visible change that should happen in Gaussian Mixture Models and EM.

Hint 1

Reveal when your model needs a nudge.

Hint 2

Reveal when your model needs a nudge.

Hint 3

Reveal when your model needs a nudge.

Grounded research drawerClose
ConceptGaussian Mixture Models and EMMachine Learning

Research Room

Attach the question to a claim, equation, code, or demo

Pick the concept, equation, source, runnable code, claim, misconception, or demo state before asking for help. The handoff keeps that page item in context.
Next local actionNo local draft saved yet

Open the draft below to save one note and next action in this browser.

conceptMachine Learning

Gaussian Mixture Models and EM

Attached question

What is the smallest example that makes Gaussian Mixture Models and EM click without losing the math?

Local action draftNo local draft saved yetExpand only when ready to capture one local next action
Local action draft

This draft stays in this browser, attached to the selected learning item.

No local draft saved.
Evidence to inspect
  • References to inspect: attached references on this page.
  • Definition, prerequisite, and contrast concept links
  • The equation or runnable code that makes the concept operational
  • One demo state that shows the invariant instead of a slogan
What would resolve this
  • The learner can state the mechanism in their own words
  • The learner can name the prerequisite that would repair confusion
  • The learner can predict how the mechanism changes under one perturbation
Grounded AI handoff

I am working in Continuous Function's research reading room. Object: concept - Gaussian Mixture Models and EM Selected item key: recorded for copy. Context: Machine Learning Page anchor: recorded for copy. Open question: What is the smallest example that makes Gaussian Mixture Models and EM click without losing the math? Evidence to inspect: - References to inspect: attached references on this page. - Definition, prerequisite, and contrast concept links - The equation or runnable code that makes the concept operational - One demo state that shows the invariant instead of a slogan What would resolve this: - The learner can state the mechanism in their own words - The learner can name the prerequisite that would repair confusion - The learner can predict how the mechanism changes under one perturbation Answer as a careful research tutor: stay source-grounded, separate verified evidence from assumptions, name the relevant math objects, and end with one next action.

View it in context
concept/concept-notebook/machine-learning/gaussian-mixtures-em concept:machine-learning/gaussian-mixtures-em