Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 3: Classical Machine LearningUnsupervised Learning

Gaussian mixtures and EM

P3.C245 min●●● AdvancedReviewed Dec 2, 2026

Why this matters for machine learning

A Gaussian mixture is the simplest model with a hidden variable: each point comes from one of several groups, but the group is not recorded. Expectation-maximization is the standard way to fit such models, by guessing the hidden group softly and then refitting.

  • k-means (hard assignment to the nearest centre) is the limit of a Gaussian mixture with equal round clusters whose shared variance is held fixed and shrunk to zero, so a mixture is the probabilistic version of the method. (P3.C1: k-means clustering)
  • A fitted mixture gives a probability density for the data, and a point with very low density is a candidate anomaly. (P3.C5: Anomaly detection)
  • A variational autoencoder also has a hidden variable for every data point. It is trained by maximizing a lower bound on the log-likelihood, the same bound that explains why EM works. (P8.3: Variational Autoencoders, coming soon)
  • Naive Bayes with Gaussian class densities is a mixture model whose group labels are known. A mixture fits the same kind of model when the labels are missing. (P3.B2: Naive Bayes)

Before this: Bayes' theorem, Covariance and the multivariate Gaussian, Maximum Likelihood Estimation, The supervised learning setup, Naive Bayes, k-means clustering

After this lesson you can

  • Say what soft clustering is, and write a mixture of Gaussians as a story: pick a component with probability πk\pi_k, then draw the point from N(μk,Σk)\mathcal{N}(\boldsymbol{\mu}_k,\boldsymbol{\Sigma}_k)
  • Explain why the log-likelihood of a mixture is hard to maximize directly, and carry out the E-step (responsibilities by Bayes’ rule) and the M-step (weighted means, covariances and weights) by hand on a small example
  • State what EM guarantees (the log-likelihood never decreases) and what it does not (a global best), and explain initialization, restarts, and the collapse of a component onto one point
  • Choose the covariance type and the number of components with BIC, and use a fitted mixture for soft labels, density and new samples

A point sits between two clusters of dots. Is it in the left cluster or the right one? A hard rule, such as “join the nearest centre”, must pick one, and the choice can flip when the point moves by a hair. A more honest answer is “probably 60% left and 40% right”.

This lesson builds a model that gives such answers. It describes the data as a mixture of Gaussians (the bell shapes of P1.D3 and the ellipses of P1.D7), and fits it with a loop called expectation-maximization, or EM. In the widget below you can watch the loop turn a rough guess into ellipses that match the data.

Hard and soft clustering

Clustering means grouping points that look alike when nobody has told you the groups. There are no labels yy, so this is unsupervised learning (P3.A1).

  • In hard clustering every point gets exactly one cluster. k-means (P3.C1) is the standard example: each point goes to the nearest centre, and each centre becomes the mean of its points.
  • In soft clustering every point gets a share for each cluster, and the shares add to 1. A point in the overlap region might get 0.60.6 and 0.40.4.

A Gaussian mixture does soft clustering, and it also describes the shape of each cluster. k-means uses only a centre, so it treats every cluster as a round blob of the same size. A mixture gives each cluster its own centre, size, tilt and weight.

A mixture as a story

Statisticians describe a mixture as a two-step story for how one data point is made. This is a generative model: a recipe that can produce data.

  1. Pick a component number k∈{1,…,K}k\in\{1,\dots,K\} at random, with probability πk\pi_k. These mixing weights are not negative and add to 1.
  2. Draw the point from that component’s Gaussian: x∼N(μk,Σk)\mathbf{x}\sim\mathcal{N}(\boldsymbol{\mu}_k,\boldsymbol{\Sigma}_k), with the notation of P1.D7.

The number kk is a hidden (or latent) variable: it is part of the story but is not in the data. Adding up over the KK ways a point could have been made gives its density:

p(x)=∑k=1Kπk N(x∣μk,Σk).p(\mathbf{x})=\sum_{k=1}^{K}\pi_k\,\mathcal{N}(\mathbf{x}\mid\boldsymbol{\mu}_k,\boldsymbol{\Sigma}_k).

(The letter πk\pi_k is a weight here. The number 3.14…3.14\ldots appears in the Gaussian density itself, and the context tells them apart.) The model has KK weights (one is fixed by the sum), KK means and KK covariance matrices. Together they are the parameters θ\boldsymbol{\theta}.

This is the model behind naive Bayes with Gaussian features (P3.B2), except that there the class labels are recorded. In a mixture the components play the role of classes that nobody wrote down.

If the labels were recorded, fitting would be easy: for each class, count the points for πk\pi_k, average them for μk\boldsymbol{\mu}_k and take their covariance for Σk\boldsymbol{\Sigma}_k. That is maximum likelihood (P1.D10). The whole difficulty of this lesson is that the labels are missing.

The likelihood, and why it is hard

Maximum likelihood (P1.D10) chooses the parameters that make the data most probable. For NN independent points x1,…,xN\mathbf{x}_1,\dots,\mathbf{x}_N the log-likelihood is

ln⁡p(X∣θ)=∑i=1Nln⁡(∑k=1Kπk×N(xi∣μk,Σk)).\begin{aligned} \ln p(\mathbf{X}\mid\boldsymbol{\theta})&=\sum_{i=1}^{N}\ln\Bigl(\sum_{k=1}^{K}\pi_k\\ &\qquad\times\mathcal{N}(\mathbf{x}_i\mid\boldsymbol{\mu}_k,\boldsymbol{\Sigma}_k)\Bigr). \end{aligned}

Compare this with a single Gaussian, where the log of the density is simple: it is a quadratic in x\mathbf{x} plus a constant, so the maximum has a closed form (the sample mean and covariance). Here the logarithm sits outside a sum, and ln⁡(a+b)\ln(a+b) does not split into ln⁡a+ln⁡b\ln a+\ln b. The terms of the KK components are tangled together, and setting the derivatives to zero gives equations that cannot be solved in one go.

The model is still worth the trouble. In P1.D10’s “two clusters” example, the points 1, 1.5, 2, 6, 6.5, 71,\ 1.5,\ 2,\ 6,\ 6.5,\ 7 were fitted by one Gaussian, which sat at 44 between the groups and reached a log-likelihood of −14.09-14.09. A mixture of two Gaussians with means 1.51.5 and 6.56.5, spread 0.410.41 and weight 12\frac12 each reaches −7.30-7.30. Higher is better, and the gain is large.

EM: guess softly, then refit

The loop rests on one idea. If we knew how much each point belongs to each component, fitting would be easy. If we knew the components, working out how much each point belongs to each would be easy. Each is a problem the other solves, so alternate:

  1. Start with a guess for the parameters.
  2. E-step (expectation): with the current parameters, work out for every point how likely each component is to be the one that made it.
  3. M-step (maximization): refit every component to the data, counting each point as much as that component is responsible for it.
  4. Repeat 2 and 3 until nothing changes much.

The E-step: responsibilities

The responsibility rikr_{ik} is the probability that point ii came from component kk, given the point and the current parameters. It is a posterior, so Bayes’ rule (P1.D6) gives it. The prior is the weight πk\pi_k. The likelihood is the density of the point under that component:

rik=πk N(xi∣μk,Σk)∑j=1Kπj N(xi∣μj,Σj).r_{ik}=\frac{\pi_k\,\mathcal{N}(\mathbf{x}_i\mid\boldsymbol{\mu}_k,\boldsymbol{\Sigma}_k)}{\sum_{j=1}^{K}\pi_j\,\mathcal{N}(\mathbf{x}_i\mid\boldsymbol{\mu}_j,\boldsymbol{\Sigma}_j)}.

For each point, the responsibilities add to 1. The denominator is the mixture density p(xi)p(\mathbf{x}_i). Two things to notice. Responsibility is not just closeness: a component with a large weight, or a wide spread, claims more of a point than a small, narrow one at the same distance. And the nearest centre by plain distance can lose, because the Mahalanobis distance of P1.D7 (which uses Σk\boldsymbol{\Sigma}_k) is what counts.

The M-step: weighted averages

Add up the responsibilities of component kk to get its effective number of points, Nk=∑irikN_k=\sum_i r_{ik} (the NkN_k add to NN). Then refit with the responsibilities as weights:

πk=NkN,μk=1Nk∑i=1Nrik xi,\pi_k=\frac{N_k}{N},\qquad \boldsymbol{\mu}_k=\frac{1}{N_k}\sum_{i=1}^{N}r_{ik}\,\mathbf{x}_i, Σk=1Nk∑i=1Nrik (xi−μk)×(xi−μk)⊤.\begin{aligned} \boldsymbol{\Sigma}_k=\frac{1}{N_k}\sum_{i=1}^{N}r_{ik}\,&(\mathbf{x}_i-\boldsymbol{\mu}_k)\\ &\times(\mathbf{x}_i-\boldsymbol{\mu}_k)^\top. \end{aligned}

These are the ordinary mean and covariance, with each point counted rikr_{ik} times. If every rikr_{ik} were exactly 00 or 11, they would be exactly the “count and average” formulas of labelled data. The covariance uses the new mean μk\boldsymbol{\mu}_k and divides by NkN_k, not Nk−1N_k-1, because it is the maximum likelihood estimate (P1.D10 divided by NN too: its points 2,3,3.5,4.5,5,62,3,3.5,4.5,5,6 gave the variance 1.751.75).

A tiny example by hand

Take five made-up numbers on a line: 1, 2, 4, 7, 81,\ 2,\ 4,\ 7,\ 8. In one dimension a component has a mean μk\mu_k and a variance σk2\sigma_k^2, and N(x∣μ,σ2)=12πσ2e−(x−μ)2/(2σ2)\mathcal{N}(x\mid\mu,\sigma^2)=\frac{1}{\sqrt{2\pi\sigma^2}}\mathrm{e}^{-(x-\mu)^2/(2\sigma^2)}. Use K=2K=2 and a rough starting guess:

π1=π2=0.5,μ1=3, μ2=6,σ12=σ22=4.\begin{aligned} \pi_1=\pi_2&=0.5,\\ \mu_1=3,\ \mu_2&=6,\\ \sigma_1^2=\sigma_2^2&=4. \end{aligned}

E-step. For each point compute the two weighted densities πkN(x∣μk,σk2)\pi_k\mathcal{N}(x\mid\mu_k,\sigma_k^2) and divide each by their sum. For x=4x=4: N(4∣3,4)=e−1/88π=0.1760\mathcal{N}(4\mid3,4)=\frac{\mathrm{e}^{-1/8}}{\sqrt{8\pi}}=0.1760 and N(4∣6,4)=e−4/88π=0.1210\mathcal{N}(4\mid6,4)=\frac{\mathrm{e}^{-4/8}}{\sqrt{8\pi}}=0.1210. With the weights, 0.08800.0880 and 0.06050.0605, so r⋅1=0.08800.0880+0.0605=0.5927r_{\cdot1}=\frac{0.0880}{0.0880+0.0605}=0.5927.

xxπ1N1\pi_1\mathcal{N}_1π2N2\pi_2\mathcal{N}_2ri1r_{i1}ri2r_{i2}
10.06050.00440.93250.0675
20.08800.01350.86700.1330
40.08800.06050.59270.4073
70.01350.08800.13300.8670
80.00440.06050.06750.9325

(The responsibilities were computed from unrounded densities. The point 44 is nearer to μ1=3\mu_1=3 than to μ2=6\mu_2=6, so component 1 gets the larger share, but component 2 keeps 0.40730.4073.)

M-step. The effective counts are N1=0.9325+0.8670+0.5927+0.1330+0.0675=2.5927N_1=0.9325+0.8670+0.5927+0.1330+0.0675=2.5927 and N2=2.4073N_2=2.4073. Then

π1=2.59275=0.5185,μ1=12.5927(0.9325⋅1+0.8670⋅2+0.5927⋅4+0.1330⋅7+0.0675⋅8)=2.5103.\begin{aligned} \pi_1&=\frac{2.5927}{5}=0.5185,\\ \mu_1&=\frac{1}{2.5927}\bigl(0.9325\cdot1+0.8670\cdot2\\ &\qquad+0.5927\cdot4+0.1330\cdot7\\ &\qquad+0.0675\cdot8\bigr)=2.5103. \end{aligned}

By the same steps π2=0.4815\pi_2=0.4815 and μ2=6.4352\mu_2=6.4352. The variances are the weighted mean of (x−μk)2(x-\mu_k)^2 around the new means: σ12=3.2337\sigma_1^2=3.2337 and σ22=3.9821\sigma_2^2=3.9821.

Did it help? The log-likelihood of the data is the sum over points of ln⁡\ln of the mixture density. At the starting guess it is −11.9528-11.9528, and after one M-step it is −11.6391-11.6391. The next cell repeats the loop for four iterations.

Step 1: EM by hand, in NumPy

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

Expected output:

iteration 1: log-likelihood -11.9528
r for x=4: [0.5927 0.4073]
  pi [0.5185 0.4815] mu [2.5103 6.4352] var [3.2337 3.9821]
iteration 2: log-likelihood -11.6391
  pi [0.5223 0.4777] mu [2.2537 6.7466] var [1.9985 2.8462]
iteration 3: log-likelihood -11.1792
  pi [0.5366 0.4634] mu [2.1571 6.9973] var [1.434  1.8237]
iteration 4: log-likelihood -10.8829
  pi [0.5648 0.4352] mu [2.2304 7.2152] var [1.4721 1.1503]

Both means are drifting towards the two groups, {1,2,4}\{1,2,4\} and {7,8}\{7,8\}, and the variances are shrinking. The log-likelihood rises at every step.

Watch the ellipses fit

The same loop in two dimensions, on made-up points. The solid ellipse around each centre is one standard deviation of its Gaussian and the dashed one is two (the level sets of P1.D7). Press E-step and the points take the colour and shape of the component with the largest responsibility, paler where it is shared. Press M-step and the ellipses refit. The chart under the picture shows the log-likelihood after every iteration.

123
1 (blue circle): π = 0.33, μ = (7.1, 2.8) 2 (pink square): π = 0.33, μ = (6.9, 8.1) 3 (amber triangle): π = 0.33, μ = (2.8, 3.2)
iteration: 0
start: 1
log-likelihood: −368.71
−368.71010 iterations

Starting guess (start 1): 3 circles on 3 data points, equal weights. Press E-step: every point gets a responsibility for each component.

Three round groups of 30 points. The easy case: k-means and a mixture agree. Points are drawn in the colour and shape of their most responsible component, and paler when the responsibility is shared. Solid ellipse: one standard deviation (about 39% of a component’s points). Dashed: two (about 86%). “New start” picks different starting centres: some starts end in a worse solution, which the log-likelihood shows.

Expectation-maximization for a Gaussian mixture on made-up 2-D points. Pick a data set (three round clusters, two elongated clusters that overlap, or two thin stripes where k-means fails) and the number of components k from 1 to 5. The starting guess is k data points as centres with round covariances. E-step colours each point by its largest responsibility, with a distinct marker shape per component, paler when shared. M-step moves each component’s ellipses (solid: one standard deviation, dashed: two) and refits the weights. Play alternates the two steps, Jump to convergence runs the loop at once (in Lite Mode, which has no Play button, use the step buttons or Jump), Reset returns to the starting guess and New start picks different starting centres. The readouts show the iteration, the log-likelihood and its change, and a chart of the log-likelihood after each iteration.

Things to try:

  • Round clusters, k=3k=3. From the first start the log-likelihood rises from about −368.7-368.7 to −302.78-302.78 within five iterations, and the three ellipses sit on the three groups. This is the easy case.
  • Elongated, overlapping, k=2k=2. Two long, tilted groups cross in the middle. The ellipses stretch and tilt to follow them, and the log-likelihood reaches −284.09-284.09 after 25 iterations. Round clusters, as in k-means, could not describe these groups.
  • The stripes, k=2k=2. From the first start the two ellipses lie along the two stripes (log-likelihood −282.68-282.68, 11 iterations). Now press New start a few times. From start 5 the loop ends near −335.4-335.4 (this start is still creeping up when the widget reaches its 300-iteration limit): the ellipses cut across the stripes, a worse solution that EM does not leave on its own. Start 8 stops at −322.04-322.04. The same data, the same algorithm, different answers: the next section explains why.
  • Change kk. With k=5k=5 on the round clusters the extra components split the groups, and the log-likelihood is higher than with k=3k=3 (−289.23-289.23 from start 1) although the groups did not change. A higher training log-likelihood is not a better model (see choosing kk below).
  • A collapse. On “Elongated, overlapping” with k=4k=4 (start 5), a component ends on about nine points with a very thin ellipse, and the widget warns (see “When a component collapses”).

A 2-D mixture in NumPy

The widget’s loop, as code with full covariance matrices. The data are three made-up groups of 120120, 8080 and 100100 points. The cell computes the densities with logarithms and subtracts the largest term before exponentiating (the log-sum-exp trick of P1.G2), so that nothing underflows.

Step 2: EM for a 2-D mixture

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

Expected output:

iterations: 27
log-likelihood at iterations 1, 2, 3: [-1647.6  -1042.94 -1014.87]
final log-likelihood: -946.74
never decreased: True
weights: [0.403 0.334 0.263]
means:
 [[0.2  0.1 ]
 [0.78 4.87]
 [3.98 0.99]]

The true weights are 0.4, 0.267, 0.3330.4,\ 0.267,\ 0.333 (from 120, 80, 100120,\ 80,\ 100 points out of 300300) and the true means are (0,0)(0,0), (4,1)(4,1) and (1,5)(1,5). The fitted values are close to them, but not equal: the fit follows the sample, which is only a random draw. The term 1e-6 * np.eye(d) is a variance floor, explained below.

What EM guarantees

The log-likelihood never decreases. Each full iteration (E-step, then M-step) leaves the log-likelihood the same or higher (apart from a tiny effect of the variance floor, explained below). This was shown by Dempster, Laird and Rubin in 1977, in the paper that named the algorithm. You saw it in the hand example (−11.95-11.95 up to −10.88-10.88), in the cell, and in the chart of the widget. It also gives a clean test for bugs: if your own log-likelihood goes down by more than rounding error (apart from a tiny effect of the variance floor, explained below), the code is wrong.

Go deeper Why the log-likelihood cannot go down

Write qikq_{ik} for any weights with ∑kqik=1\sum_kq_{ik}=1 (a guess of the hidden component of point ii). Because the logarithm is concave, Jensen’s inequality (the log of an average is at least the average of the logs) gives, for every point,

ln⁡∑kπkNk=ln⁡∑kqikπkNkqik≥∑kqikln⁡πkNkqik.\begin{aligned} \ln\sum_k\pi_k\mathcal{N}_k&=\ln\sum_kq_{ik}\frac{\pi_k\mathcal{N}_k}{q_{ik}}\\ &\ge\sum_kq_{ik}\ln\frac{\pi_k\mathcal{N}_k}{q_{ik}}. \end{aligned}

Summing over the points, the right side is a lower bound F(q,θ)F(\mathbf{q},\boldsymbol{\theta}) on the log-likelihood. The two sides are equal when qikq_{ik} is the responsibility rikr_{ik} computed with the same θ\boldsymbol{\theta}. So:

  • The E-step sets q\mathbf{q} to the responsibilities. The bound now touches the log-likelihood at the current parameters.
  • The M-step chooses the new parameters to maximize the bound for this q\mathbf{q}. The new bound is at least as high as the old one.
  • The log-likelihood at the new parameters is at least the bound there.

In a chain: ln⁡L(θold)=F(q,θold)≤F(q,θnew)≤ln⁡L(θnew)\ln L(\boldsymbol{\theta}_{\text{old}})=F(\mathbf{q},\boldsymbol{\theta}_{\text{old}})\le F(\mathbf{q},\boldsymbol{\theta}_{\text{new}})\le\ln L(\boldsymbol{\theta}_{\text{new}}). For the hand example the numbers are −11.9528≤−11.7873≤−11.6391-11.9528\le-11.7873\le-11.6391. A bound of this kind is the idea behind the training objective of variational autoencoders (P8.3).

What it does not guarantee. The log-likelihood rises until the changes become tiny, but the point where EM stops is a stationary point, usually a local maximum, and not necessarily the best of all. Like gradient descent on a bumpy surface (P1.F3), the end of the road depends on where you start. The stripes in the widget showed this: different starts, different final log-likelihoods (−282.68-282.68 and about −335.4-335.4), and the higher number is the better fit.

Starts, restarts and labels

Because of local optima, the start matters. Common practice:

  • Start from k-means. Run k-means (P3.C1) first, use its centres as the initial means and the spread of each group as its covariance. This is the default in scikit-learn (init_params="kmeans"). Another option is to pick kk data points as the centres. The widget picks them spread out (a k-means++-style choice) and starts every component as a round ellipse. scikit-learn’s "random_from_data" picks them uniformly at random.
  • Restart several times and keep the best log-likelihood. scikit-learn’s n_init does this. On the stripes data of the widget, scikit-learn’s default k-means start ends in a left-right split (log-likelihood about −335.5-335.5) for seeds 0 to 4. With n_init=10 the best of ten starts is the stripes solution (−282.7-282.7) for one of those five seeds, and with init_params="random_from_data" and n_init=10 for all five. With other seeds the result varies: over seeds 0 to 19, n_init=10 with the k-means start found the stripes 13 times and with "random_from_data" 20 times. The higher log-likelihood is the way to tell.
  • Stop when the gain is small. Both the widget and scikit-learn stop when the improvement is below a tolerance (scikit-learn’s default is tol=0.001 on the average log-likelihood per point, and at most max_iter=100 iterations).

One more point about the answer: the labels of the components are arbitrary. Swapping “component 1” and “component 2” gives the same model, so two runs can describe the same fit with the numbers in a different order. That is why the code cells above sort the components before printing.

When a component collapses

Look again at the log-likelihood. Put one component exactly on one data point, μk=xi\boldsymbol{\mu}_k=\mathbf{x}_i, and let its variance shrink. The density of that point under the component, 1σ2π\frac{1}{\sigma\sqrt{2\pi}} in one dimension, grows without bound as σ→0\sigma\to0. The other points are still covered by the other components, so the total log-likelihood goes up and up. The likelihood has no maximum, and a loop that chases the likelihood can fall into such a spike.

P1.D10 promised this example. Take its six points 2, 3, 3.5, 4.5, 5, 62,\ 3,\ 3.5,\ 4.5,\ 5,\ 6 and a mixture of two Gaussians: weight 12\frac12 on a Gaussian centred on the first point x1=2x_1=2 with spread ss, and weight 12\frac12 on a Gaussian with μ=4\mu=4 and σ=1.5\sigma=1.5.

Step 3: the spike on one point

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

Expected output:

spike spread s    log-likelihood
           1          -11.64
         0.1          -10.81
        0.01           -8.54
       0.001           -6.24
      0.0001           -3.93
with a variance floor of 0.01: -10.81

Each time ss is divided by 1010, the log-likelihood rises by ln⁡10=2.30\ln10=2.30, and it keeps rising. (A log of a density can be positive, because a density can be larger than 11; it is not a probability.) The spike gives a huge likelihood but a useless model: it has memorized one point.

The usual fix is a variance floor: never let a variance fall below a small value. In scikit-learn this is reg_covar, a small number added to the diagonal of every covariance matrix (default 10−610^{-6}), which keeps the matrices invertible. The widget adds 0.0010.001 in every M-step, and warns when a component’s narrow axis is nearly at the floor. Another way is a prior on the covariance (P1.D11). In practice, also watch for a component with very few points (NkN_k near 1), and use fewer components if you see one. The floor is added to each covariance after the M-step has found its best value, so the M-step is no longer an exact maximizer of the bound. The guarantee then holds only approximately: with a component on a few points the log-likelihood can dip by a tiny amount (in the widget, by at most about 0.0030.003).

k-means is a limit of EM

Make the mixture as simple as possible: equal weights, and every component round with the same variance vv, held fixed (not refit). Then the E-step depends only on the distances to the centres. In the hand example the responsibility of component 1 for x=4x=4 is 0.59270.5927 for v=4v=4, 0.81760.8176 for v=1v=1 and 0.99750.9975 for v=0.25v=0.25, and it goes to 11 as v→0v\to0: every responsibility becomes 00 or 11, going to the nearest centre. The M-step mean with 00-or-11 weights is the plain mean of the cluster, which is the k-means loop. So k-means is the hard, round, equal-size limit of EM, and relaxing those three limits gives a mixture: soft shares, a shape for each cluster, and a weight for each cluster.

Go deeper The responsibility with a shared round variance

With equal weights and the covariance vIv\mathbf{I} for every component, the weights and the normalizing constants cancel in rikr_{ik}, leaving rik=softmaxk(−∥xi−μk∥2/(2v))r_{ik}=\mathrm{softmax}_k\bigl(-\lVert\mathbf{x}_i-\boldsymbol{\mu}_k\rVert^2/(2v)\bigr). For two components and x=4x=4 with centres 33 and 66 the squared distances are 11 and 44, so r⋅1=11+e−3/(2v)r_{\cdot1}=\frac{1}{1+\mathrm{e}^{-3/(2v)}}. As v→0v\to0 the softmax tends to a one-hot vector at the nearest centre.

Covariance types

A full d×dd\times d covariance matrix has d(d+1)/2d(d+1)/2 numbers, which is many in high dimensions. A mixture can limit what a covariance matrix may look like. scikit-learn’s four covariance_type options:

  • full: each component has its own general matrix. Ellipses of any size and tilt. The most flexible.
  • tied: all components share one general matrix. The ellipses have one shape, in different places.
  • diag: each component has its own diagonal matrix. Ellipses along the coordinate axes, with different widths.
  • spherical: each component has one variance. Circles of different sizes.

A simpler type trains faster and overfits less when there are few points, but it cannot describe tilted ellipses. Also, “diag” and “spherical” depend on the scale of each feature, so scale the features first (P3.A11).

Go deeper Counting the parameters

A mixture with KK components in dd dimensions has KdKd numbers for the means and K−1K-1 for the weights. The covariances need K d(d+1)/2K\,d(d+1)/2 numbers (full), d(d+1)/2d(d+1)/2 (tied), K dK\,d (diag) or KK (spherical). For d=10d=10 and K=4K=4 the totals are 263263 (full), 9898 (tied), 8383 (diag) and 4747 (spherical).

Choosing the number of components

The number of components KK is a choice made before the fit, and the log-likelihood cannot choose it: on the same data, adding components almost always raises the training log-likelihood, because a more flexible model can fit the sample more closely. For the three-group data of Step 2, the best log-likelihood found for each kk keeps creeping up even after the true number, 33 (the BIC column is explained next):

kkLog-likelihoodBIC
1−1265.6-1265.62559.72559.7
2−1039.1-1039.12141.02141.0
3−946.8-946.81990.51990.5
4−946.4-946.42023.92023.9
5−945.9-945.92057.22057.2
6−939.6-939.62078.92078.9

Two criteria add a price for each extra parameter. With pp free parameters, NN points and L^\hat L the maximum likelihood,

BIC=−2ln⁡L^+pln⁡N,AIC=−2ln⁡L^+2p.\begin{aligned} \mathrm{BIC}&=-2\ln\hat L+p\ln N,\\ \mathrm{AIC}&=-2\ln\hat L+2p. \end{aligned}

Lower is better in both (this is the sign convention of scikit-learn’s bic and aic). BIC charges ln⁡N\ln N per parameter, which is more than 22 once N≥8N\ge8, so it prefers smaller models than AIC. For the three-group data with a full covariance, p=3⋅2+3⋅3+2=17p=3\cdot2+3\cdot3+2=17, and BIC=−2(−946.8)+17ln⁡300=1990.5\mathrm{BIC}=-2(-946.8)+17\ln300=1990.5. BIC is lowest at k=3k=3, as the table shows. Both are rules of thumb that assume the Gaussian model is right, so also look at the clusters and, with held-out data, at its log-likelihood (P3.A4).

Using a fitted mixture

A fitted mixture is a full model of the data, so it can do several things.

  • Soft labels. The E-step formula applied to a new point gives its responsibilities (scikit-learn: predict_proba). Taking the largest gives a hard label (predict).
  • Density. p(x)p(\mathbf{x}) is the mixture formula. The log of it, per point, is score_samples. Points in dense regions score high.
  • New data. Follow the story: pick a component with probability πk\pi_k, then draw from its Gaussian (sample). With a Cholesky factor, as in P1.D7, drawing from N(μk,Σk)\mathcal{N}(\boldsymbol{\mu}_k,\boldsymbol{\Sigma}_k) is easy.
  • Anomaly scores. A point with a very low density is one the model finds unlikely, which is the starting point for anomaly detection (P3.C5). Note that a density is not a probability and its scale depends on the units of the data, so you pick a threshold from the data, for example the lowest 1% of the training scores.

scikit-learn does all of this in a few lines. This block is shown as text, not run in the page, because scikit-learn is not available in the in-browser runner; the output is from a local run (scikit-learn 1.8.0), on the same data as Step 2.

import numpy as np
from sklearn.mixture import GaussianMixture

rng = np.random.default_rng(7)                 # the same made-up data as Step 2
A = rng.multivariate_normal([0, 0], [[1.0, 0.8], [0.8, 1.0]], 120)
B = rng.multivariate_normal([4, 1], [[0.5, 0], [0, 0.5]], 80)
C = rng.multivariate_normal([1, 5], [[0.6, -0.3], [-0.3, 0.8]], 100)
X = np.vstack([A, B, C])

gm = GaussianMixture(n_components=3, covariance_type="full",
                     n_init=5, random_state=0).fit(X)
order = np.argsort(gm.means_[:, 0])            # component order is arbitrary
print("converged:", gm.converged_, " iterations:", gm.n_iter_)
print("weights:", gm.weights_[order].round(3))
print("means:\n", gm.means_[order].round(2))
print("soft labels of (2, 2):", gm.predict_proba([[2.0, 2.0]])[:, order].round(3))

print("choose k with BIC (lower is better):")
for k in range(1, 7):
    m = GaussianMixture(k, n_init=5, random_state=0).fit(X)
    print(f"  k={k}  BIC {m.bic(X):7.1f}  AIC {m.aic(X):7.1f}")

Output:

converged: True  iterations: 5
weights: [0.402 0.334 0.264]
means:
 [[0.19 0.09]
 [0.78 4.87]
 [3.97 0.99]]
soft labels of (2, 2): [[0.988 0.007 0.006]]
choose k with BIC (lower is better):
  k=1  BIC  2559.7  AIC  2541.2
  k=2  BIC  2141.0  AIC  2100.2
  k=3  BIC  1990.5  AIC  1927.5
  k=4  BIC  2023.9  AIC  1938.8
  k=5  BIC  2057.2  AIC  1949.8
  k=6  BIC  2078.9  AIC  1949.3

The point (2,2)(2,2) gets 98.8%98.8\% of its share from the group centred near (0.2,0.1)(0.2,0.1), whose tilted ellipse points towards it. The weights differ a little from the Step 2 cell (0.4020.402 and 0.4030.403), because scikit-learn stops by a different tolerance.

Go deeper Using scikit-learn further

The same fitted model, with the other covariance types, densities and samples (a local run, scikit-learn 1.8.0, continuing the block above):

print("covariance types, k=3 (BIC):")
for ct in ["full", "tied", "diag", "spherical"]:
    m = GaussianMixture(3, covariance_type=ct, n_init=5, random_state=0).fit(X)
    print(f"  {ct:9} BIC {m.bic(X):7.1f}")

print("log density of three points:",
      gm.score_samples([[0, 0], [2, 2.5], [8, -4]]).round(2))
print("three new points drawn from the model:\n", gm.sample(3)[0].round(2))

Output:

covariance types, k=3 (BIC):
  full      BIC  1990.5
  tied      BIC  2097.3
  diag      BIC  2124.5
  spherical BIC  2107.4
log density of three points: [ -2.05  -5.49 -60.46]
three new points drawn from the model:
 [[ 5.46  0.92]
 [-1.21 -1.78]
 [ 0.13  5.45]]

The densities say that (0,0)(0,0) sits at the centre of a group (−2.05-2.05), (2,2.5)(2,2.5) in the gap (−5.49-5.49) and (8,−4)(8,-4) far from everything (−60.46-60.46). Full covariance has the lowest BIC because two of the three groups are tilted ellipses, which a round model cannot reproduce.

Where mixtures struggle

  • Shape and size of the data. A curved group, such as a crescent, needs several Gaussians, and then the pieces are not the groups you meant (density-based methods, P3.C6, can suit it better). In many dimensions a full covariance has d(d+1)/2d(d+1)/2 numbers per component, so with few points use a simpler type, a bigger floor, or reduce the dimension first (P3.C3).
  • Choices and confidence. The start and kk are choices the fit cannot make for you. The responsibilities are the model’s beliefs: a point with responsibility 0.990.99 is “99% component 2 if the model is right”.

Intuition

Think of sorting a mixed bag of coins you cannot see well, from two countries. First you guess what each country’s coins look like. Then, for every coin, you work out how much it looks like each country’s coins, and write down shares such as “70% country A”. Then you redraw each country’s typical coin using every coin, weighted by its share. With the better picture, you re-judge the coins, and so on. The shares and the pictures sharpen each other.

Where the comparison breaks: coins have only one true origin, so a share is your doubt. In a mixture, the model itself claims each point was made by one component, and the share is the model’s doubt about which.

Math

Model. zi∼Categorical(π)z_i\sim\mathrm{Categorical}(\boldsymbol{\pi}) and xi∣zi=k∼N(μk,Σk)\mathbf{x}_i\mid z_i=k\sim\mathcal{N}(\boldsymbol{\mu}_k,\boldsymbol{\Sigma}_k). The marginal is p(x)=∑kπkN(x∣μk,Σk)p(\mathbf{x})=\sum_k\pi_k\mathcal{N}(\mathbf{x}\mid\boldsymbol{\mu}_k,\boldsymbol{\Sigma}_k).

Why the M-step has those formulas. Given the responsibilities, the bound FF of the Go-deeper box depends on the parameters only through ∑i,krik[ln⁡πk+ln⁡N(xi∣μk,Σk)]\sum_{i,k}r_{ik}\bigl[\ln\pi_k+\ln\mathcal{N}(\mathbf{x}_i\mid\boldsymbol{\mu}_k,\boldsymbol{\Sigma}_k)\bigr]. This is a weighted version of the labelled-data log-likelihood. Its maximum over the weights, subject to ∑kπk=1\sum_k\pi_k=1, is πk=Nk/N\pi_k=N_k/N (the categorical estimate of P1.D10), and over μk,Σk\boldsymbol{\mu}_k,\boldsymbol{\Sigma}_k it is the weighted mean and covariance.

Limit. For Σk=vI\boldsymbol{\Sigma}_k=v\mathbf{I} with vv held fixed and equal πk\pi_k, rik=softmaxk(−∥xi−μk∥2/(2v))r_{ik}=\mathrm{softmax}_k\bigl(-\lVert\mathbf{x}_i-\boldsymbol{\mu}_k\rVert^2/(2v)\bigr), which tends to a one-hot vector at the nearest centre as v→0v\to0.

Code

Fitting by scikit-learn is shown in the static block above. The two NumPy cells (Steps 1 and 2) are the whole algorithm: a log-density function, an E-step that normalizes the weighted densities, and an M-step of weighted sums. To explore, change K in Step 2 to 22 or 44 and compare the final log-likelihood.

Try it

  1. In the widget, choose “k-means fails here”, press New start until the log-likelihood ends near −335.4-335.4, and then near −282.68-282.68. How do the two final pictures differ? Which start would you keep?
  2. In Step 1, change the starting variances from 44 to 11. After the first E-step, is the point 44 still the least certain? What happens to its responsibility?
  3. In Step 2, change K to 22 and to 44 and compare the final log-likelihoods. Then compute the BIC of each (for full covariances in two dimensions p=6K−1p=6K-1, and N=300N=300). On “Three round clusters” in the widget, raise kk from 3 to 5: does the log-likelihood rise, and is the picture better?

Exercises

  1. In the table of the hand example, find ri2r_{i2} for x=7x=7 from the two weighted densities.
    Show answerThe weighted densities are 0.01350.0135 for component 1 and 0.08800.0880 for component 2, so ri2=0.08800.0135+0.0880=0.867r_{i2}=\frac{0.0880}{0.0135+0.0880}=0.867. Point 7 is mostly component 2, and the table’s unrounded value is 0.86700.8670.
  2. Count the free parameters of a mixture with K=4K=4 components, spherical covariances and d=10d=10 features.
    Show answerMeans: 4⋅10=404\cdot10=40. Weights: 4−1=34-1=3. Spherical covariances: one variance per component, so 44. In total 4747.
  3. Model A has ln⁡L^=−100\ln\hat L=-100 and 55 parameters. Model B has ln⁡L^=−93\ln\hat L=-93 and 1010. There are N=50N=50 points. Which model do BIC and AIC prefer?
    Show answerBIC: A =200+5ln⁡50=219.56=200+5\ln50=219.56 and B =186+10ln⁡50=225.12=186+10\ln50=225.12, so BIC prefers A. AIC: A =200+10=210=200+10=210 and B =186+20=206=186+20=206, so AIC prefers B. BIC’s price per parameter, ln⁡50=3.91\ln50=3.91, is higher than AIC’s 22, so it is more cautious about the extra parameters.
  4. In Step 3 the log-likelihood is −3.93-3.93 at s=0.0001s=0.0001. Predict it at s=0.00001s=0.00001 without running the code.
    Show answerDividing ss by 1010 adds ln⁡10=2.30\ln10=2.30 (the spike’s density at the point x1x_1 is multiplied by 1010, the other terms are almost unchanged), so about −3.93+2.30=−1.63-3.93+2.30=-1.63. Running the code gives −1.63-1.63. The log-likelihood is still increasing: there is no maximum.
  5. Why can EM not lower the log-likelihood, and why can the final answer still be bad?
    Show answerThe E-step makes the lower bound touch the log-likelihood and the M-step raises the bound, so the log-likelihood cannot fall. But EM only follows the bound uphill from its start, so it can end on a local maximum that is lower than the global one.

Check your understanding

  1. What does the E-step compute for a point?

  2. Why is the log-likelihood of a mixture hard to maximize in one step?

  3. During EM, how does the log-likelihood behave from one full iteration to the next?

  4. One component is centred exactly on a data point and its variance shrinks to 00. What happens to the likelihood, and what is the usual remedy?

  5. You fit mixtures with k=1,2,…,6k=1,2,\dots,6 and the training log-likelihood keeps rising slightly after k=3k=3. What is the sensible way to choose kk?

Next: P3.C3 finds the directions of largest variance, which are the long axes of the covariance ellipses of this lesson. P3.C5 uses the density of a fitted mixture to flag anomalies. P3.C6 shows clustering by density, for shapes that Gaussians describe badly.

Key takeaways

  • A mixture of Gaussians says: pick component kk with probability πk\pi_k, then draw x∼N(μk,Σk)\mathbf{x}\sim\mathcal{N}(\boldsymbol{\mu}_k,\boldsymbol{\Sigma}_k). The density is p(x)=∑kπk N(x∣μk,Σk)p(\mathbf{x})=\sum_k\pi_k\,\mathcal{N}(\mathbf{x}\mid\boldsymbol{\mu}_k,\boldsymbol{\Sigma}_k). Soft clustering gives each point a share for every component instead of one label.
  • The log-likelihood ∑iln⁡∑kπkN(⋅)\sum_i\ln\sum_k\pi_k\mathcal{N}(\cdot) has a log of a sum, so it does not split into one simple term per component and has no closed-form maximum. If the component of every point were known, fitting would be counting and averaging (P1.D10).
  • EM alternates two steps. E-step: the responsibility rik=πkN(xi∣μk,Σk)∑jπjN(xi∣μj,Σj)r_{ik}=\frac{\pi_k\mathcal{N}(\mathbf{x}_i\mid\boldsymbol{\mu}_k,\boldsymbol{\Sigma}_k)}{\sum_j\pi_j\mathcal{N}(\mathbf{x}_i\mid\boldsymbol{\mu}_j,\boldsymbol{\Sigma}_j)} is the posterior probability of component kk (Bayes’ rule, P1.D6). M-step: with Nk=∑irikN_k=\sum_ir_{ik}, set πk=Nk/N\pi_k=N_k/N, μk=1Nk∑irikxi\boldsymbol{\mu}_k=\frac1{N_k}\sum_ir_{ik}\mathbf{x}_i and Σk=1Nk∑irik(xi−μk)(xi−μk)⊤\boldsymbol{\Sigma}_k=\frac1{N_k}\sum_ir_{ik}(\mathbf{x}_i-\boldsymbol{\mu}_k)(\mathbf{x}_i-\boldsymbol{\mu}_k)^\top.
  • On the five made-up numbers 1,2,4,7,81,2,4,7,8 with a starting guess of means 33 and 66 and variances 44, the point 44 gets responsibilities 0.59270.5927 and 0.40730.4073, and the log-likelihood rises −11.9528→−11.6391→−11.1792→−10.8829-11.9528\to-11.6391\to-11.1792\to-10.8829.
  • The log-likelihood never decreases from one iteration to the next (apart from a tiny effect of a variance floor), but EM stops at a local optimum that depends on the start. Run several starts (k-means initialization is common) and keep the one with the highest log-likelihood.
  • Without a limit, the likelihood has no maximum: a component centred on one data point with variance going to 00 makes the density there grow without bound. On the six points of P1.D10 the log-likelihood is −11.64-11.64, −10.81-10.81, −8.54-8.54 and −6.24-6.24 for spreads 11, 0.10.1, 0.010.01 and 0.0010.001. The fix is a floor on the variance (reg_covar in scikit-learn).
  • k-means is the limit of EM with equal weights, one shared round variance held fixed (not refit) and shrinking to 00: the responsibilities become 00 or 11. The covariance type (full, tied, diag, spherical) sets how many parameters a component has, and BIC, −2ln⁡L^+pln⁡N-2\ln\hat L+p\ln N, picks the number of components because the training log-likelihood alone always favours more.
Found a mistake? Tell us