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 , 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 and .
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.
- Pick a component number at random, with probability . These mixing weights are not negative and add to 1.
- Draw the point from that component’s Gaussian: , with the notation of P1.D7.
The number is a hidden (or latent) variable: it is part of the story but is not in the data. Adding up over the ways a point could have been made gives its density:
(The letter is a weight here. The number appears in the Gaussian density itself, and the context tells them apart.) The model has weights (one is fixed by the sum), means and covariance matrices. Together they are the parameters .
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 , average them for and take their covariance for . 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 independent points the log-likelihood is
Compare this with a single Gaussian, where the log of the density is simple: it is a quadratic in plus a constant, so the maximum has a closed form (the sample mean and covariance). Here the logarithm sits outside a sum, and does not split into . The terms of the 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 were fitted by one Gaussian, which sat at between the groups and reached a log-likelihood of . A mixture of two Gaussians with means and , spread and weight each reaches . 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:
- Start with a guess for the parameters.
- E-step (expectation): with the current parameters, work out for every point how likely each component is to be the one that made it.
- M-step (maximization): refit every component to the data, counting each point as much as that component is responsible for it.
- Repeat 2 and 3 until nothing changes much.
The E-step: responsibilities
The responsibility is the probability that point came from component , given the point and the current parameters. It is a posterior, so Bayes’ rule (P1.D6) gives it. The prior is the weight . The likelihood is the density of the point under that component:
For each point, the responsibilities add to 1. The denominator is the mixture density . 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 ) is what counts.
The M-step: weighted averages
Add up the responsibilities of component to get its effective number of points, (the add to ). Then refit with the responsibilities as weights:
These are the ordinary mean and covariance, with each point counted times. If every were exactly or , they would be exactly the “count and average” formulas of labelled data. The covariance uses the new mean and divides by , not , because it is the maximum likelihood estimate (P1.D10 divided by too: its points gave the variance ).
A tiny example by hand
Take five made-up numbers on a line: . In one dimension a component has a mean and a variance , and . Use and a rough starting guess:
E-step. For each point compute the two weighted densities and divide each by their sum. For : and . With the weights, and , so .
| 1 | 0.0605 | 0.0044 | 0.9325 | 0.0675 |
| 2 | 0.0880 | 0.0135 | 0.8670 | 0.1330 |
| 4 | 0.0880 | 0.0605 | 0.5927 | 0.4073 |
| 7 | 0.0135 | 0.0880 | 0.1330 | 0.8670 |
| 8 | 0.0044 | 0.0605 | 0.0675 | 0.9325 |
(The responsibilities were computed from unrounded densities. The point is nearer to than to , so component 1 gets the larger share, but component 2 keeps .)
M-step. The effective counts are and . Then
By the same steps and . The variances are the weighted mean of around the new means: and .
Did it help? The log-likelihood of the data is the sum over points of of the mixture density. At the starting guess it is , and after one M-step it is . The next cell repeats the loop for four iterations.
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, and , 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.
Things to try:
- Round clusters, . From the first start the log-likelihood rises from about to within five iterations, and the three ellipses sit on the three groups. This is the easy case.
- Elongated, overlapping, . Two long, tilted groups cross in the middle. The ellipses stretch and tilt to follow them, and the log-likelihood reaches after 25 iterations. Round clusters, as in k-means, could not describe these groups.
- The stripes, . From the first start the two ellipses lie along the two stripes (log-likelihood , 11 iterations). Now press New start a few times. From start 5 the loop ends near (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 . The same data, the same algorithm, different answers: the next section explains why.
- Change . With on the round clusters the extra components split the groups, and the log-likelihood is higher than with ( from start 1) although the groups did not change. A higher training log-likelihood is not a better model (see choosing below).
- A collapse. On “Elongated, overlapping” with (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 , and 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.
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 (from points out of ) and the true means are , and . 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 ( up to ), 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 for any weights with (a guess of the hidden component of point ). 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,
Summing over the points, the right side is a lower bound on the log-likelihood. The two sides are equal when is the responsibility computed with the same . So:
- The E-step sets 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 . 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: . For the hand example the numbers are . 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 ( and about ), 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 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_initdoes this. On the stripes data of the widget, scikit-learn’s default k-means start ends in a left-right split (log-likelihood about ) for seeds 0 to 4. Withn_init=10the best of ten starts is the stripes solution () for one of those five seeds, and withinit_params="random_from_data"andn_init=10for all five. With other seeds the result varies: over seeds 0 to 19,n_init=10with 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.001on the average log-likelihood per point, and at mostmax_iter=100iterations).
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, , and let its variance shrink. The density of that point under the component, in one dimension, grows without bound as . 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 and a mixture of two Gaussians: weight on a Gaussian centred on the first point with spread , and weight on a Gaussian with and .
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 is divided by , the log-likelihood rises by , and it keeps rising. (A log of a density can be positive, because a density can be larger than ; 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 ), which keeps the matrices invertible. The widget adds 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 ( 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 ).
k-means is a limit of EM
Make the mixture as simple as possible: equal weights, and every component round with the same variance , 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 is for , for and for , and it goes to as : every responsibility becomes or , going to the nearest centre. The M-step mean with -or- 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 for every component, the weights and the normalizing constants cancel in , leaving . For two components and with centres and the squared distances are and , so . As the softmax tends to a one-hot vector at the nearest centre.
Covariance types
A full covariance matrix has 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 components in dimensions has numbers for the means and for the weights. The covariances need numbers (full), (tied), (diag) or (spherical). For and the totals are (full), (tied), (diag) and (spherical).
Choosing the number of components
The number of components 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 keeps creeping up even after the true number, (the BIC column is explained next):
| Log-likelihood | BIC | |
|---|---|---|
| 1 | ||
| 2 | ||
| 3 | ||
| 4 | ||
| 5 | ||
| 6 |
Two criteria add a price for each extra parameter. With free parameters, points and the maximum likelihood,
Lower is better in both (this is the sign convention of scikit-learn’s bic and aic). BIC charges per parameter, which is more than once , so it prefers smaller models than AIC. For the three-group data with a full covariance, , and . BIC is lowest at , 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. 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 , then draw from its Gaussian (
sample). With a Cholesky factor, as in P1.D7, drawing from 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 gets of its share from the group centred near , whose tilted ellipse points towards it. The weights differ a little from the Step 2 cell ( and ), 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 sits at the centre of a group (), in the gap () and far from everything (). 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 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 are choices the fit cannot make for you. The responsibilities are the model’s beliefs: a point with responsibility 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. and . The marginal is .
Why the M-step has those formulas. Given the responsibilities, the bound of the Go-deeper box depends on the parameters only through . This is a weighted version of the labelled-data log-likelihood. Its maximum over the weights, subject to , is (the categorical estimate of P1.D10), and over it is the weighted mean and covariance.
Limit. For with held fixed and equal , , which tends to a one-hot vector at the nearest centre as .
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 or and compare the final log-likelihood.
Try it
- In the widget, choose “k-means fails here”, press New start until the log-likelihood ends near , and then near . How do the two final pictures differ? Which start would you keep?
- In Step 1, change the starting variances from to . After the first E-step, is the point still the least certain? What happens to its responsibility?
- In Step 2, change
Kto and to and compare the final log-likelihoods. Then compute the BIC of each (for full covariances in two dimensions , and ). On “Three round clusters” in the widget, raise from 3 to 5: does the log-likelihood rise, and is the picture better?
Exercises
- In the table of the hand example, find for from the two weighted densities.
Show answer
The weighted densities are for component 1 and for component 2, so . Point 7 is mostly component 2, and the table’s unrounded value is . - Count the free parameters of a mixture with components, spherical covariances and features.
Show answer
Means: . Weights: . Spherical covariances: one variance per component, so . In total . - Model A has and parameters. Model B has and . There are points. Which model do BIC and AIC prefer?
Show answer
BIC: A and B , so BIC prefers A. AIC: A and B , so AIC prefers B. BIC’s price per parameter, , is higher than AIC’s , so it is more cautious about the extra parameters. - In Step 3 the log-likelihood is at . Predict it at without running the code.
Show answer
Dividing by adds (the spike’s density at the point is multiplied by , the other terms are almost unchanged), so about . Running the code gives . The log-likelihood is still increasing: there is no maximum. - Why can EM not lower the log-likelihood, and why can the final answer still be bad?
Show answer
The 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
What does the E-step compute for a point?
The E-step is Bayes’ rule: weight times density for each component, divided by the sum over components, which gives shares that add to 1. Updating the means is the job of the M-step, assigning to the nearest centre alone is hard clustering as in k-means, and EM does not use a gradient.
Why is the log-likelihood of a mixture hard to maximize in one step?
The log of a sum is not a sum of logs, so the components stay tangled and the equations for the parameters involve the responsibilities, which themselves depend on the parameters. The Gaussian density is smooth, the sum-to-1 condition is easy to meet, and a mixture has more parameters than a single Gaussian, not fewer.
During EM, how does the log-likelihood behave from one full iteration to the next?
The lower-bound argument gives a log-likelihood that goes up or stays the same at each iteration. That does not mean the best solution is reached: the stripes in the widget end near from one start and from another. Going down by more than a tiny amount is a sign of a bug (a variance floor can cause a tiny dip), up and down at random is not how EM behaves, and the E-step leaves the parameters, and so the log-likelihood, unchanged.
One component is centred exactly on a data point and its variance shrinks to . What happens to the likelihood, and what is the usual remedy?
The density at that point, proportional to , grows without bound as shrinks, so the likelihood has no maximum. A floor on the variance stops it. The likelihood does not fall to , it is not unchanged, and a likelihood is never negative (its log can be), so normalizing the data does not address the cause.
You fit mixtures with and the training log-likelihood keeps rising slightly after . What is the sensible way to choose ?
More components nearly always raise the training log-likelihood because a flexible model fits the sample more closely, even the noise. BIC subtracts a price per parameter, and held-out data tests the model on points it did not fit. The lowest log-likelihood is a worse fit, and no fixed suits every data set.
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.