Gaussian Mixture Models from first principles

A plot that looks easy

Here is a question that looks easy until you try to answer it carefully.

You have a pile of completed deliveries. For each one you know two numbers: the straight-line distance from the pickup point to the customer, and the end-to-end time from order placed to order delivered. Nothing else. No courier id, no vehicle type, no restaurant.

879 deliveries plotted as distance against duration

There is clearly structure in there. Two diagonal streaks fan apart as distance grows, and a compact cloud sits in the top left: short trips that took the best part of an hour.

So: how many kinds of trip is that, and which one is each order?

The first time I met a plot like this I reached for k-means with K=3, got three clusters back, and nearly shipped it. The problem is that k-means always returns three clusters. It will partition pure noise without complaint, and it never tells you that an order was a coin flip.

In this post we start from that failure, work out which assumption caused it, and build the fix, a Gaussian mixture model, from scratch in numpy. No sklearn.1 Every function the model needs is in the post. The derivation is in an appendix at the end, and the main thread stays on intuition.

The data here is synthetic: I generate it from parameters I chose. That is deliberate. Because I know the answer, I can tell you when the algorithm gets it right and by how much. No real orders, couriers or customers appear anywhere.

Something that doesn’t work

k-means, K=3:

k-means partition next to the three subpopulations that generated the data

The left panel is k-means. The right panel is the process that actually produced the data, so this is a good moment to say what I planted. Every order comes from one of three groups:

group share of orders what a trip looks like
slower mode 0.40 9 min of overhead plus 4.2 min per km, trips around 4 km
faster mode 0.42 7 min of overhead plus 1.9 min per km, trips around 7 km
stalled at pickup 0.18 about 2 km and 54 minutes, with no relation between the two numbers

Orders in the two courier modes scatter about 3.2 minutes around their line. The question for the rest of the post is whether an algorithm that sees only the 879 points can get these numbers back.

k-means found the stalled orders. That blob is isolated enough that nothing could miss it. But look at what it did with the rest: it carved the main body of deliveries into three horizontal bands of duration. Its three centres sit at roughly (4.4 km, 18 min), (7.2 km, 30 min) and (2.8 km, 53 min). It has discovered fast orders and slow orders.

That is not the structure. The structure is two courier modes, two populations with different minutes per km, one about twice as slow as the other. A slow-mode order going 9 km and a fast-mode order going 9 km take very different times, while a slow-mode 3 km trip and a fast-mode 7 km trip take about the same. Sorting by duration mixes the modes together and splits each one in half.

This isn’t a bug or a bad seed. k-means is doing exactly what it was asked to do. Three assumptions are built into the algorithm:

  1. Assignment is hard. Every order belongs to exactly one cluster with certainty 1. There is no way to say “this one is ambiguous.”
  2. Clusters are round. Distance is plain Euclidean distance, so a cluster’s influence falls off equally in every direction. A long thin diagonal cluster cannot be expressed.
  3. Clusters are the same size. They share one implied radius, and the boundary between two centres is the perpendicular bisector, a straight line.

Assumption 2 is the one that hurt us. The courier modes are long, thin and tilted, and no arrangement of round balls covers one without spilling into the other.

Here is a second way to see the problem. Throw away distance and look only at duration:

The duration histogram and a three-component fit to it

One lumpy histogram. A three-component mixture fits it nicely, with bumps at 20, 29 and 54 minutes, and that fit is useful for something like setting delivery promises. But it answers a different question. Those bumps are “quick”, “not quick” and “went wrong”. The two courier modes are smeared across the first two. You cannot recover the modes from duration alone. You need the relationship between distance and duration, which means you need a model that can represent a tilted cluster.

So let’s change the question.

Flipping the question

k-means asks: how do I partition these points?

A mixture model asks something better: what process would have produced these points? Then it works backwards.2

The proposed process is a two-step recipe. To make one delivery:

  1. Roll a weighted die with faces. Face comes up with probability . Call the result , and think of it as “which kind of trip is this”.
  2. Draw the point from the Gaussian belonging to face : .

Repeat times. That’s the entire model.

The is the interesting part. It is the group that generated the order, and you never get to see it. It is latent. The dataset you receive is the (distance, duration) columns with the group column deleted. Everything that follows is the work of reconstructing that deleted column and the parameters at the same time.

Marginalise out and the density of a single point is

where collects all of . It is a weighted sum of bumps, which is what the right-hand panel of the histogram figure above shows in one dimension. Notice there that the components are not the curve chopped into segments. They overlap, and around 35 minutes the observed density is the sum of two of them.

Three knobs per component

Each component carries three things:

  • , the mixing weight. A scalar. How often the die lands on face , or roughly what share of orders this group handles. It is a property of the mixture, not of the Gaussian.
  • , the mean vector. numbers. Where the component sits: the average trip for that group.
  • , the covariance matrix. A symmetric positive-definite matrix. The shape and orientation. This is the one k-means does not have.

The covariance is the fix for our problem:

Spherical, diagonal and full covariance contours

A spherical covariance has one free number and gives you k-means’ circle. A diagonal one gives an axis-aligned ellipse, numbers. A full covariance matrix gives an ellipse at any angle, for numbers. The off-diagonal entry is the covariance between distance and duration. It is the entry that encodes minutes per km, and it is what lets a cluster tilt.

It helps to make that connection concrete, because it is what makes the fitted model interpretable later. If a component’s points follow with , then

so once the model is fitted, the slope of each courier mode can be read straight off its covariance matrix. We’ll check that number at the end.

That formula is also how the data was built. Here is the whole generator, which is the two-step recipe above with the planted numbers filled in:

import numpy as np

def line_cov(slope, sx, sy):
    """Covariance of (d, a + slope*d + eps): the matrix above."""
    return np.array([[sx ** 2,         slope * sx ** 2],
                     [slope * sx ** 2, slope ** 2 * sx ** 2 + sy ** 2]])

# a = overhead in minutes, m = minutes per km,
# x0 = mean trip distance, sx = its spread, sy = residual in minutes
SLOW = dict(a=9.0, m=4.2, x0=4.0, sx=1.9, sy=3.2)
FAST = dict(a=7.0, m=1.9, x0=7.2, sx=3.0, sy=3.2)

TRUE_PI = np.array([0.40, 0.42, 0.18])
TRUE_MU = np.array([
    [SLOW["x0"], SLOW["a"] + SLOW["m"] * SLOW["x0"]],
    [FAST["x0"], FAST["a"] + FAST["m"] * FAST["x0"]],
    [2.2, 54.0],                                   # stalled at pickup
])
TRUE_SIGMA = np.array([
    line_cov(SLOW["m"], SLOW["sx"], SLOW["sy"]),
    line_cov(FAST["m"], FAST["sx"], FAST["sy"]),
    np.diag([0.80 ** 2, 4.5 ** 2]),
])

def sample(n=900, seed=11):
    rng = np.random.default_rng(seed)
    z = rng.choice(3, size=n, p=TRUE_PI)           # step 1: roll the die
    X = np.empty((n, 2))
    for k in range(3):                             # step 2: draw from that Gaussian
        m = z == k
        X[m] = rng.multivariate_normal(TRUE_MU[k], TRUE_SIGMA[k], size=m.sum())
    # orders are not negative-distance and not instantaneous
    keep = (X[:, 0] > 0.3) & (X[:, 1] > 4.0)
    return X[keep], z[keep]

It draws 900 orders and drops the 21 that come out with an impossible distance or duration, which is where 879 comes from. The function also returns z, the column the model never sees. We only use it at the end, to mark the answer.

Here is the Gaussian density. It is in log space because we will be multiplying a lot of small numbers, and a product of 879 densities underflows a float64 long before you get an answer:

def log_gaussian(X, mu, Sigma):
    """log N(x | mu, Sigma) for every row of X.

    X     : (n, d)
    mu    : (d,)
    Sigma : (d, d), symmetric positive definite
    returns (n,)
    """
    n, d = X.shape
    L = np.linalg.cholesky(Sigma)              # Sigma = L L^T
    diff = X - mu                               # (n, d)
    # solve L z = diff^T  =>  z^T z = diff^T Sigma^-1 diff  (Mahalanobis)
    z = np.linalg.solve(L, diff.T)              # (d, n)
    maha = np.sum(z ** 2, axis=0)               # (n,)
    log_det = 2.0 * np.sum(np.log(np.diag(L)))  # log|Sigma|
    return -0.5 * (d * np.log(2 * np.pi) + log_det + maha)

Two choices there are deliberate. We never form . We Cholesky-factor and solve a triangular system, which is faster and much better conditioned. And comes out of the same factorisation as , instead of going through a determinant that underflows to zero in moderate dimensions.

Full covariances have one more benefit. Distance is in kilometres and duration is in minutes, and nobody standardised anything. k-means is at the mercy of that. It is dominated by whichever feature has the bigger numeric range, which is why its boundaries came out horizontal. A full-covariance GMM is equivariant under invertible linear maps of the features, so rescaling an axis just rescales and changes nothing about the fit.

The chicken-and-egg problem

We want the parameters that make the observed data most likely. The log-likelihood is

Try to maximise that directly and you get stuck. The sum is inside the log, so it doesn’t separate into per-component terms, and setting the gradient to zero gives a system with no closed form. The function isn’t concave either.

But notice something. If somebody handed me the hidden group column, this would be trivial: group the orders, and each component’s mean and covariance are just the sample mean and sample covariance of its group. One line each.

And the other way round: if somebody handed me the parameters, recovering the groups would be easy. For each order, ask which component most plausibly produced it.

Each half is easy given the other, and neither is available. So guess one, compute the other, and repeat. That is expectation-maximisation.3 It sounds like a greedy hack, and the surprising part is that it provably works.

The E-step: responsibilities

Fix the parameters. For each order and component , ask: given these parameters, what is the probability that component generated this order? That is a posterior over the latent variable, and Bayes’ rule gives it directly:

The numerator is the prior for component times how well component explains this order. The denominator is the same quantity totalled over all components, so the result is a probability. These values are called responsibilities: component is responsible for a fraction of order .

By hand, with four orders

Before the code, it is worth doing this once with numbers small enough to follow. Forget distance and take four orders with durations of 18, 22, 27 and 34 minutes. Guess two components: A centred at 20 minutes and B centred at 32, both with a standard deviation of 4, and equal weights of 0.5.

Take the 27-minute order. Under A its density is 0.0216, and under B it is 0.0457. Both priors are 0.5, so

Do the same for all four:

order density under A density under B
18 min 0.0880 0.0002 1.00 0.00
22 min 0.0880 0.0044 0.95 0.05
27 min 0.0216 0.0457 0.32 0.68
34 min 0.0002 0.0880 0.00 1.00

The 18-minute and 34-minute orders are clear cases. The 27-minute order sits between the two centres, a little closer to B, and the numbers say exactly that: about one third A, two thirds B.

This is the most important idea in the model. k-means gives you a label. EM gives you numbers per order that sum to one.

The same thing happens on the real fit we end up with. An 11 km delivery that took 28 minutes is unambiguous and gets , because only the fast mode can produce that. A 0.9 km delivery that took 6.5 minutes gets , because on a trip that short the two modes are indistinguishable.

In code, entirely in log space:

def e_step(X, pi, mu, Sigma):
    """Returns (log_resp, log_likelihood).

    log_resp[i, k] = log gamma(z_ik) = log p(z_i = k | x_i)
    """
    K = len(pi)
    # log of the joint p(x_i, z_i = k) for every i, k
    log_joint = np.column_stack([
        np.log(pi[k]) + log_gaussian(X, mu[k], Sigma[k]) for k in range(K)
    ])                                                    # (n, K)
    log_px = logsumexp(log_joint, axis=1)                 # (n,)  -- log p(x_i)
    log_resp = log_joint - log_px[:, None]                # Bayes, in log space
    return log_resp, log_px.sum()

The division in Bayes’ rule has become a subtraction. And the denominator we had to compute anyway, , summed over , is the log-likelihood. So the E-step gives us our convergence monitor at no extra cost.

logsumexp is the standard trick for adding numbers that only exist as logarithms:

def logsumexp(A, axis):
    """Numerically stable log(sum(exp(A)))."""
    m = np.max(A, axis=axis, keepdims=True)
    out = m + np.log(np.sum(np.exp(A - m), axis=axis, keepdims=True))
    return np.squeeze(out, axis=axis)

Pulling the maximum out front means the largest exponential is and the rest are smaller, so nothing overflows and the dominant term never underflows.

The M-step: refit, weighted

Now reverse it. Hold the responsibilities fixed and update the parameters. Define the soft count for component :

This is the effective number of orders the component owns, and it is not an integer. Then:

These are the ordinary formulas for a weight, a mean and a covariance, with every order weighted by how much this component owns it. That is not an approximation. It is what comes out of the maximisation, and the appendix derives it.

By hand, continued

Back to the four orders. Add up each column of responsibilities to get the soft counts:

So A owns about 2.27 orders out of 4, and its new weight is . Its new mean is the average duration, with each order counted by the share A owns:

The same sum for B gives 30.9. The centres have moved from 20 and 32 to 21.0 and 30.9, each pulled a little toward the 27-minute order they share. The spread updates the same way, as a weighted average of squared distances from the new mean.

Compare that with what k-means would do. It would hand the 27-minute order entirely to B, so B’s centre would be the plain average of 27 and 34. Here that order counts as about a third of an order for A and two thirds for B, so a near coin flip does not get to move one centre as if it were a sure thing.

That is one round of EM. Compute responsibilities, then take weighted averages. In code:

def m_step(X, log_resp, reg=1e-6):
    n, d = X.shape
    resp = np.exp(log_resp)                 # (n, K)
    Nk = resp.sum(axis=0) + 1e-300          # (K,)  -- soft counts

    pi = Nk / n
    mu = (resp.T @ X) / Nk[:, None]         # (K, d)

    K = resp.shape[1]
    Sigma = np.empty((K, d, d))
    for k in range(K):
        diff = X - mu[k]                                    # (n, d)
        Sigma[k] = (resp[:, k, None] * diff).T @ diff / Nk[k]
        Sigma[k].flat[:: d + 1] += reg                      # ridge on the diagonal
    return pi, mu, Sigma

The reg on the diagonal is not cosmetic. I’ll come back to why it has to be there.

A place to start

In the by-hand example I simply guessed the starting centres. The real code needs a rule for that, and there are two common ones.

The first is the crude one: pick orders at random as the means, give every component the covariance of the whole dataset, and make the weights equal. The second runs k-means first and builds each component from one k-means cluster.

def _cov(A, d):
    """Sample covariance as a (d, d) matrix, with a small ridge."""
    S = np.atleast_2d(np.cov(A, rowvar=False))
    return S.reshape(d, d) + 1e-6 * np.eye(d)

def init_params(X, K, rng, method="kmeans"):
    n, d = X.shape
    if method == "kmeans":
        labels, centres = kmeans(X, K, rng)
        mu = centres
        pi = np.array([max((labels == k).sum(), 1) / n for k in range(K)])
        pi = pi / pi.sum()
        Sigma = np.array([
            _cov(X[labels == k], d) if (labels == k).sum() > d else _cov(X, d)
            for k in range(K)
        ])
    else:  # "random": deliberately crude
        mu = X[rng.choice(n, size=K, replace=False)]
        pi = np.full(K, 1.0 / K)
        Sigma = np.array([_cov(X, d) for _ in range(K)])
    return pi, mu, Sigma

And since the post promised no sklearn, here is the k-means it calls. It is the same algorithm that produced the three bands earlier:

def kmeans(X, K, rng, iters=50):
    """Lloyd's algorithm with k-means++ seeding. Returns (labels, centres)."""
    n, d = X.shape

    # k-means++ seeding: prefer new centres far from the ones already picked
    centres = [X[rng.integers(n)]]
    for _ in range(K - 1):
        d2 = np.min(
            ((X[:, None, :] - np.array(centres)[None, :, :]) ** 2).sum(-1), axis=1
        )
        centres.append(X[rng.choice(n, p=d2 / d2.sum())])
    centres = np.array(centres)

    labels = np.zeros(n, dtype=int)
    for _ in range(iters):
        dist = ((X[:, None, :] - centres[None, :, :]) ** 2).sum(-1)   # (n, K)
        new_labels = np.argmin(dist, axis=1)
        if np.array_equal(new_labels, labels):
            break
        labels = new_labels
        for k in range(K):
            if np.any(labels == k):
                centres[k] = X[labels == k].mean(axis=0)
    return labels, centres

The loop

def fit_gmm(X, K, rng, max_iter=200, tol=1e-6, init="kmeans"):
    pi, mu, Sigma = init_params(X, K, rng, method=init)
    lls = []
    prev = -np.inf

    for it in range(max_iter):
        log_resp, ll = e_step(X, pi, mu, Sigma)
        lls.append(ll)
        if ll - prev < tol * abs(ll):
            break
        prev = ll
        pi, mu, Sigma = m_step(X, log_resp)

    return dict(pi=pi, mu=mu, Sigma=Sigma, log_resp=log_resp,
                ll=lls[-1], lls=np.array(lls), n_iter=it)

The EM part of this (the density, the E-step, the M-step and the loop) comes to about forty lines of code. Here it is running from the crude random start:

EM iterations converging on the delivery data

Each order is coloured by blending the three component colours in proportion to its responsibilities, and faded toward grey as the assignment gets less certain, so grey means undecided. The ellipses are the 1σ and 2σ contours. The colours match the earlier figure: blue for the slower mode, teal for the faster one, red for the stalled orders.

Iteration 0 is nonsense. Within three iterations the stalled-order blob has been isolated, because nothing else is near it. After that, from iteration 3 all the way through iteration 41, the picture barely changes. The two courier modes are covered by two components sitting more or less on top of each other, both trying to explain both modes, and the whole middle of the plot is grey.

It isn’t stuck. It is moving very slowly along a flat ridge.

Log-likelihood over EM iterations, and the per-step improvement

The left plot is the log-likelihood. It never decreases, and that is a theorem with a proof in the appendix. The right plot is the improvement per step on a log scale. The gain drops sharply in the first few iterations, flattens out at roughly 0.15 nats per step, stays there for the better part of thirty iterations, and then speeds up, climbing back past 60 nats per step around iteration 54, before the fit settles and converges for real.

The speed-up is the giveaway. A converging optimiser slows down. This one got faster, so the flat stretch was never convergence.

The plateau comes from a near-symmetry. Two nearly identical components covering the same region make a nearly flat region of the likelihood surface, tilted just enough that EM keeps moving. The practical lesson:

A small change in log-likelihood is not the same as convergence. Stopping at iteration 41, where the last step gained about 0.15 nats, would have reported a fit 242 nats worse than the answer twenty iterations later, and a picture in which the two courier modes do not exist.

I checked the monotonicity claim empirically too, over 80 runs with tolerance-based stopping disabled. The worst single-step change was , which is floating-point noise.

What soft assignment actually buys you

Now for the part k-means cannot do.

Fitted density, and the regions where the model is uncertain

Left is the fitted density , the model’s picture of where deliveries come from. Right is evaluated everywhere on the plane, which is how confident the assignment is. Red means unsure, and the dark line is the 0.9 contour.

Look at the shape of the red wedge. It is widest near the origin and narrows as distance grows, which is what you would expect if you understood the domain. On a 2 km trip the two courier modes differ by about six minutes, which is less than the noise, so the model cannot tell them apart and says so. On a 12 km trip they differ by half an hour and the assignment is never in doubt. 64 of the 879 orders fall inside that wedge.

Nobody picked that band as a threshold. It comes out of the fit. If you are using these clusters to make decisions (routing, pricing, SLA attribution), those 64 orders are the ones not to act on automatically.

One thing catches people out here. The far corners of that plot are white, meaning high confidence. That is correct and also useless. Responsibility is a ratio: “given that this order came from the mixture, which component was it?” Far from all the data every component’s density is tiny, but one is relatively less tiny, so it wins the ratio outright. High responsibility does not mean the point is typical. If you want to know whether an order is unusual at all, look at the left panel, . That is how you would do anomaly detection with a GMM.

Did it actually recover the modes?

This is where synthetic data pays off. The whole fit is two lines (fit_best is fit_gmm with restarts, and its code is further down under “Where this breaks”):

X, z = sample()
fit = fit_best(X, K=3)

Sorting the fitted components by mean distance, and reading the slope straight off each covariance matrix as :

component mean trip min/km (planted) residual σ (planted)
stalled at pickup 2.3 km, 54 min n/a 5.0 min (4.5)
slower mode 4.1 km, 26 min 4.17 (4.2) 3.1 min (3.2)
faster mode 7.4 km, 21 min 1.93 (1.9) 3.2 min (3.2)

It recovered both courier speeds to within about 2%, from unlabelled data, with no idea that courier modes existed. That is what you get for modelling the process that generated the data instead of partitioning the plane.

The weights need a closer look, because at first glance they are off:

component fitted share in this sample planted
stalled at pickup 0.163 0.163 0.18
slower mode 0.434 0.430 0.40
faster mode 0.404 0.407 0.42

The fitted stalled weight is 0.163 against a planted 0.18, which looks like a 9% miss. It is not the model’s miss. The planted weights are the probabilities on the die, and 900 rolls do not come out in exact proportion: this sample has 143 stalled orders out of 879, which is 0.163. Against the shares that are actually in the data, the fit is within 0.004 on every component. The model can only learn the sample it was given, and it learned that one almost exactly.

Because we kept z, we can also mark individual orders. Giving each order to its most responsible component gets 860 of the 879 right. All 143 stalled orders are found, and the 19 mistakes are all swaps between the two courier modes, most of them short trips where the modes overlap.

The fitted log-likelihood is , slightly above the log-likelihood of the true generating parameters, . That is the right way round. The maximum-likelihood fit should beat the truth on the particular sample it was fitted to, and if it didn’t, something would be wrong.

Checking the code itself

“It converged” is not the same as “it’s right”, so I also ran three checks that do not depend on the delivery data:

  • log_gaussian against a brute-force inv/det version in 5 dimensions: max absolute error .
  • Responsibilities sum to 1 per order: max deviation .
  • The fitted density numerically integrates to over the plane.

These tell you the code does what the math says. The recovered speeds are the check that tells you the math was worth doing.

Choosing K

I told it . In real use nobody tells you. The log-likelihood can’t choose for you, because more components always fit better:

Log-likelihood vs K, and BIC/AIC vs K

The standard move is to penalise complexity. With free parameters,

and for full-covariance components in dimensions,

def n_params(K, d):
    return K * d + K * d * (d + 1) // 2 + (K - 1)

def bic(ll, K, d, n):
    return -2 * ll + n_params(K, d) * np.log(n)

def aic(ll, K, d, n):
    return -2 * ll + 2 * n_params(K, d)

The sweep, best of 20 restarts at each :

K log-likelihood params BIC AIC
1 −5716.7 5 11467.4 11443.5
2 −5270.4 11 10615.4 10562.9
3 −4985.5 17 10086.2 10005.0
4 −4978.8 23 10113.6 10003.7
5 −4972.3 29 10141.2 10002.6
6 −4965.6 35 10168.4 10001.1
7 −4960.2 41 10198.2 10002.3
8 −4948.6 47 10215.7 9991.1

BIC picks , which is the truth. AIC never turns around and is still descending at 8. Its penalty is a flat while BIC’s is , and at that is , more than three times stronger. For picking the number of clusters, prefer BIC.

Don’t read “BIC is minimised at 3” as “there are 3 kinds of delivery”. It means a 3-component Gaussian mixture is the best trade-off available within this model family, for this data, at this sample size. That is a narrower statement.

Where this breaks

Three failure modes, in order of how often you will meet them.

Local optima. EM finds a maximum, not the maximum.

EM on the full data and on a 180-order subsample, with different starts

On the full 879 orders this data turns out to be well-behaved: all 80 starts I tried, random and k-means-seeded, landed on the same optimum. That is luck and not a guarantee, and it goes away once you have less data. Take just the first 180 orders and 10 of those same 80 starts land on a solution 17 nats worse, in which the stalled orders get swallowed into a courier mode and the two modes get split some other way. Same data, same , different answer depending on where you started.

So always restart, and mix the initialisers. Seeding from k-means is the common default and is usually fine, but it gives EM a starting point shaped by k-means’ own biases, so it shouldn’t be the only thing you try.

def fit_best(X, K, n_init=10, seed=0, **kw):
    """EM is a local method. Restart it and keep the best run."""
    runs = []
    for s in range(n_init):
        for init in ("kmeans", "random"):
            runs.append(fit_gmm(X, K, np.random.default_rng(seed + s), init=init, **kw))
    return max(runs, key=lambda r: r["ll"])

Singular covariances. Park a component on a single order and shrink its covariance toward zero. The density at that point goes to infinity, and so does the likelihood. The global maximum of is and it is a useless answer. The likelihood really is unbounded above, so the MLE does not exist. We aren’t finding the global optimum. We are finding a good interior local one, and the diagonal ridge in m_step is what stops a component collapsing into a spike along the way. This is why that 1e-6 has to be there.

The shape assumption. A GMM assumes every cluster is an ellipse. Our courier modes really are roughly elliptical, because a linear distance-time relationship with Gaussian noise produces exactly that, which is why this worked so well. Give it two concentric rings, or a crescent, and it will fit ellipses to them, because ellipses are all it has. It will converge, report a fine likelihood, and be wrong. For shapes like that you want kernel density estimation, spectral clustering, or DBSCAN. GMMs are also for continuous data. Mixtures of Bernoullis or multinomials are the analogue for binary and categorical features, and the EM machinery is identical. Only the component density changes.

k-means, revisited

One last thing, and it is my favourite fact in this whole topic.

Take a GMM, force every covariance to with the same everywhere, and fix all . Then let . The responsibility

is a softmax over negative squared distances with temperature . As the temperature goes to zero, the nearest centre’s term dominates completely and the responsibility vector goes to one-hot. The E-step becomes “assign to nearest centre”. The M-step becomes “average the points assigned to you”.

That’s k-means. It is a GMM at zero temperature, with the shape and the uncertainty thrown away. So it reported three bands of duration not because it is a worse algorithm, but because it is the same algorithm with the two parts we needed removed.


Appendix: the math, properly

Skip this if you have what you came for. Everything above stands on its own. This section is why it is true.4

A.1 Why the direct approach fails

We want to maximise

The obstruction is structural. With a single Gaussian, and cancel, you get a quadratic, and the MLE is one line of algebra. With a sum inside the log, nothing cancels. Setting gives

which rearranges to , the M-step formula. But it isn’t a solution, because depends on . It is a fixed-point equation. EM is, among other things, the fixed-point iteration for this system, and the value of the EM derivation is that it tells you the iteration converges and why.

A.2 The ELBO

Introduce, for each order , an arbitrary distribution over the components. Then for any such :

The inequality is Jensen’s: is concave, so the log of an average is at least the average of the logs. The middle line is the trick. Multiply and divide by so the inner sum becomes an expectation under , which is what Jensen needs.

is the evidence lower bound, the ELBO. It has the sum outside the log, so it decomposes, and that makes it tractable.5

How loose is it? Write and substitute:

The gap is exactly a KL divergence. KL is non-negative and zero only when the two distributions are identical. So:

The algorithm follows from this identity. EM is coordinate ascent on :

  • E-step: maximise over with fixed. doesn’t involve , so maximising means driving the KL term to zero, which means setting , the posterior. That is . The bound becomes tight: .
  • M-step: maximise over with fixed.

A.3 Monotonicity

One chain, three steps:

(1) is the ELBO being a lower bound at any . (2) is the M-step maximising over . (3) is the E-step having made the bound tight at .

So , always. There is no step size, no line search and nothing to tune. And since is bounded above on any region where the covariances stay away from singular, the sequence converges.

Note what this does not say. It does not say you converge to the global maximum, and it says nothing about how fast. The long plateau in the log-likelihood figure above shows how little the guarantee promises about speed.

A.4 The M-step, derived

With fixed, drop the entropy term (constant in ):

The components are now decoupled, which is what having the sum outside the log buys us. Write .

Weights. Only the terms matter, subject to . Lagrangian:

Summing over and using the constraint: , so

Means. The -dependent part is . Differentiating:

is invertible, so it drops out entirely, which is why the mean update doesn’t depend on the covariance:

Covariances. Easier in terms of the precision . The relevant terms are

using . With the matrix identities and , and both and symmetric:

Three weighted averages. That is the whole M-step, and it is why EM for GMMs is so cheap per iteration: no optimiser and no gradients at runtime, just sums.

A.5 Unboundedness

Set exactly and . The first order’s contribution contains , which as , while every other order still has components keeping its density positive. So along this path.

The likelihood is unbounded above and the maximum-likelihood estimator does not exist. Every GMM fit you have ever run was a well-behaved local optimum, found by an algorithm that was kept away from that divergence by initialisation, by a covariance floor, or by luck. reg_covar in sklearn and the reg in m_step above are that floor. It is more than a numerical convenience: without it the problem is not well-posed.

Notes

  1. scikit-learn user guide, Gaussian mixture models ↩

  2. IBM, What is a Gaussian Mixture Model? ↩

  3. Dempster, Laird & Rubin (1977), Maximum Likelihood from Incomplete Data via the EM Algorithm. The original. ↩

  4. Bishop, Pattern Recognition and Machine Learning, chapter 9. The canonical treatment of EM and mixtures. ↩

  5. Neal & Hinton (1998), A View of the EM Algorithm that Justifies Incremental, Sparse, and Other Variants. Where the ELBO-as-coordinate-ascent framing in A.2 comes from. ↩

Citation

Please cite this work as:

Makonda, Barnabas, "Gaussian Mixture Models from first principles", Barnabas Makonda's blog, Oct 2026.

Or use the BibTeX citation:

bibtex
@misc{makonda2026gaussian,
  author = {Barnabas Makonda},
  title = {Gaussian Mixture Models from first principles},
  howpublished = {Barnabas Makonda's blog},
  year = {2026},
  month = {oct},
  url = {https://blog.barnabasmakonda.workers.dev/posts/gaussian-mixture-models/},
}