Gaussian Mixture Models and Expectation-Maximization › Formula
Machine Learning from ScratchAll chapters Gaussian Mixture Models and Expectation-Maximization › FormulaSection view · Sections in this chapter4 / 10 ↓
Reading tools Definitions, links & notes
Choose your expertise level to adjust how many terms are explained. Beginners see more tooltips, experts see fewer to maintain reading flow. Hover over underlined terms for instant definitions.
Article links
Make inline references clickable
This section derives the mixture density, introduces the latent-variable formulation, and develops the E- and M-step updates.
Mixture densities and latent assignments
The derivation starts with the smallest object we need: a single Gaussian bump. In one dimension, with mean , positive standard deviation and variance , its density is
The fraction in front is not decoration. It is the exact constant that makes the area under the curve equal one, so the result can be treated as a probability density. The exponent measures how far sits from in units of standard deviations, then squares that distance; the negative sign turns distance into a penalty, so points near the mean get high density and points far away get low density. A single Gaussian therefore encodes one centre and one spread. That is useful, but it cannot describe data with two separated modes.
A mixture removes that limitation by averaging several Gaussian densities together:
where:
- : the full parameter set collecting all means , variances , and mixing weights
- : the mixing weight of component , satisfying and , so the weights behave like probabilities
- : the mean (centre) of component
- : the variance of component (one-dimensional case; the multivariate case replaces it with a covariance matrix below)
- : the Gaussian density of component evaluated at
The mixing weights describe prior component membership within the model: before seeing an observation's features, is its chance of coming from component . These are mixture probabilities, not a Bayesian prior on the fitted parameters. The sum says that the overall density at is a weighted average of the component densities at : each component contributes in proportion to how much prior mass it owns.
This weighted sum is also a generative recipe. To produce a point, first choose a component with probability , then draw the point from that component's Gaussian. The recipe contains a hidden step, and naming that step is what makes inference possible. Let record which component produced observation . We never observe , which is why it is called a latent variable. Writing the model jointly over the observation and its hidden label gives
and the law of total probability recovers the marginal density we use:
That identity is the reason the latent variable earns its place. The marginal likelihood contains a sum over hidden states, and that sum is exactly what blocks a direct closed-form maximum. If we could condition on , the sum would disappear; the latent variable lets us separate the difficult marginal problem into a sequence of easier complete-data problems.
Bayes' rule then turns the generative model into an inference procedure. Given the current parameters, the posterior probability that observation belongs to component is
The denominator is the total density at contributed by all components, and the numerator is the piece of that total contributed by component . Their ratio is the share of the density that component explains, which is precisely a probability. These are the soft assignments. They replace the missing labels with graded beliefs instead of forcing each point into one cluster.
Before generalizing, it is worth seeing why the obvious optimization strategy fails. The log-likelihood of independent observations is
We take logs because the likelihood itself is a product of densities, and products of many small numbers underflow quickly on a computer; logs turn products into sums without moving the maximum, since is strictly increasing. The obstacle is the outer logarithm sitting on top of a sum. Differentiating with respect to and setting the result to zero produces
because the ratio is precisely . Solving for the mean gives
This looks like a closed-form answer, but it is not: the responsibilities on the right-hand side are themselves functions of the whole parameter set , including . We have a fixed-point equation, not a formula. EM's insight is to freeze the right-hand side at its current value, recompute the left-hand side, and repeat. The E-step supplies the current beliefs about the hidden labels; the M-step turns those beliefs into new parameters.
Now the multivariate case, which is what we will implement. For an observation the component density is
where is a -vector, is a symmetric positive definite covariance matrix, the superscript means transpose (turn the column vector into a row vector so the matrix product is defined), is the matrix inverse, and is the determinant. The quadratic form is the squared Mahalanobis distance: it rescales and de-rotates space so that distance is measured in units of the component's own spread. The factor does the same job the factor did in one dimension: it divides by the volume the Gaussian occupies, so the density integrates to one.
Expectation and maximization steps
EM alternates between two problems, each of which is easy on its own. The first problem is inference: given parameters, what do we believe about the hidden labels? The second is estimation: given beliefs about the labels, what parameters are most likely?
Both problems are phrased in terms of the complete-data log-likelihood, the quantity we would maximize if the labels were observed. With a one-hot indicator equal to one when observation comes from component ,
where:
- : the complete-data log-likelihood, the log-likelihood we would maximize if the latent labels were observed
- : a one-hot indicator equal to when observation came from component , and otherwise
- : the mixing weight of component
- : the Gaussian density of component evaluated at
- : the number of observations, : the number of components
Because the indicators select exactly one term per observation, each component's mean and covariance can be fitted from its assigned observations. The mixing weights still share their sum-to-one constraint and are estimated from the component counts. That is the structure the marginal likelihood destroyed.
Since is unknown, we replace it with its conditional expectation, which is the responsibility: . This produces the auxiliary function
where denotes the parameters at iteration . The E-step consists of computing the from the current parameters using Bayes' rule above. Each depends on all components through the denominator. Holding responsibilities fixed separates the mean and covariance estimation by component, while the mixing weights retain their shared normalization.
The M-step maximizes over . For the means, only the quadratic term depends on :
Differentiating the quadratic form with respect to the vector uses the chain rule on the squared Mahalanobis distance,
where the minus sign appears because enters with a negative sign inside the parenthesis. Setting gives
Because is invertible, we may multiply both sides on the left by to remove it, leaving . Splitting the sum and solving,
where:
- : the effective number of observations assigned to component , formed by summing the responsibilities
- : the responsibility of component for observation , its posterior probability of membership
- : the -th observation
The mean update requires . When a component has zero effective count, this weighted-mean formula is undefined. We can stop with an error, reinitialize or remove the component, or retain its parameters as an inactive zero-weight component and skip its update. Our implementation below stops with an error. The effective count need not be an integer, because responsibilities are fractional: a point with contributes to the weighted feature sum, then division by converts that sum to the mean. This is the soft-count idea in its simplest form.
For the covariance, we need two matrix-calculus facts. First, for a symmetric positive definite matrix, which is the matrix analogue of . Second, , which follows from differentiating the inverse. Applying both,
Multiply on the left and right by (which is legal since it is invertible) and use :
where:
- : the covariance matrix of component
- : the responsibility of component for observation
- : the centered observation, its deviation from component 's mean
- : the effective count for component
For this to be a valid nondegenerate Gaussian covariance we need and a positive-definite scatter. This is the weighted scatter matrix of component , with each observation's outer product counted times. It is the same estimator we would use with known labels, except that the counts are fractional.
The mixing weights carry a constraint, , so we cannot differentiate and set to zero naively; we add the constraint times a Lagrange multiplier and differentiate the augmented expression:
The first term's derivative is because , and the Lagrange multiplier is a constant; note that although itself depends on through the Bayes formula, in the responsibilities are held fixed at their current E-step values, so within this maximization they act as constants on the derivative. Rearranging gives . Summing both sides over and using and (each observation's responsibilities sum to one),
where:
- : the mixing weight of component
- : the effective count for component
- : the number of observations
- : the Lagrange multiplier enforcing the constraint
So each mixing weight is just the share of the effective count that component holds.
Collecting everything, one full EM iteration is:
The matrix form of the M-step makes the computation obvious. Gather the responsibilities into an matrix whose entry is , and the data into an matrix whose rows are the observations. Let be a column vector of ones and the column vector of effective counts. Then
where:
- : the responsibility matrix with entry
- : the data matrix whose rows are the observations
- : a column vector of ones of length
- : the column vector of effective counts whose -th entry is
- : the -th entry of (same as ), the effective count of component
- : the -th column of (the responsibilities for component )
- : the matrix whose -th row is
- : the mean of component
- : turns a vector into a diagonal matrix
Multiplying by sums the rows of weighted by the responsibilities (each column accumulates a weighted sum), and dividing by turns those weighted sums into weighted averages, giving the matrix whose -th row is . The covariance expression is the same operation applied to the centered data: subtracting centers every row, the diagonal matrix reweights the rows, and the product accumulates the weighted outer products. In code this is a handful of matrix multiplications rather than nested loops, which matters because the E-step is repeated until convergence.
The reason EM works at all is that it is coordinate ascent on a lower bound. For a probability distribution that is positive on the joint model's positive support, multiplying and dividing inside the log by and applying Jensen's inequality (which says that for a concave function like , the average of the function is at most the function of the average) gives
The gap between the two sides is the Kullback-Leibler divergence from to the posterior , which is non-negative and equals zero exactly when is the posterior. The E-step sets to that posterior, closing the gap so the bound touches the log-likelihood at the current parameters. The M-step then pushes the bound up by maximizing it over . Since the log-likelihood is at least the bound, and the bound has increased, the log-likelihood cannot decrease. This proves likelihood nondecrease for the exact bound-increasing updates. It does not prove parameter convergence, a finite maximum, or a global optimum, and it does not apply automatically after an arbitrary covariance modification.
Mathematical Properties
A few properties follow directly from the derivation and shape how the method is used.
- Monotone under exact updates. With valid parameters and an exact E-step followed by a bound-increasing M-step, . The likelihood is non-concave; finite interior limits under suitable regularity are stationary, and they need not be global maxima. Singular boundary behaviour remains possible.
- Unbounded above for unrestricted mixtures with . A component can collapse onto one observation while another covers the remaining points, driving the sample likelihood to . A single Gaussian whose empirical centered covariance is positive definite does have a finite maximum-likelihood fit; the collapse claim is not a statement about every Gaussian model.
- Label switching. Any permutation of the component indices leaves the likelihood unchanged, so its component labels are arbitrary. Comparing parameter estimates across runs requires matching components first.
- Affine transformation of full-covariance models. For with invertible , transform each mean to and covariance to . The density divides by , so responsibilities remain unchanged and total log-likelihood shifts by . This relates corresponding unrestricted fits, not arbitrary numerical runs with fixed regularization. Diagonal models are closed under axis scaling but not general rotations; spherical models permit common uniform scaling and rotations, not arbitrary axis scaling.
- Asymptotic relation to k-means. For fixed observations and centroids, suppose all components have equal fixed weights and common spherical covariance . As the externally specified common variance tends to zero, responsibilities at observations with a unique nearest centroid approach nearest-centroid indicators. This varies a prescribed variance across models rather than estimating it in the M-step. For each component with a positive limiting hard-assignment count, its mean update approaches the k-means update. Empty limiting clusters require a separate handling rule. This is the small-variance connection between the mixture and k-means.
- Parameter counts. A full-covariance mixture has free parameters: means, covariance matrices with distinct entries each, and free mixing weights. Diagonal covariances cost , spherical ones cost , and a tied covariance uses parameters by sharing one covariance across components.
Comments
Add to the conversation
A question, a correction, or an example from your own work.
No comments yet. Be the first to share your thoughts!