Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Gaussian mixture models

ProblemModel data as a weighted sum of Gaussian densities; assign each point a probability of belonging to each component
Devised byKarl Pearson (1894), mixtures of two normals; Arthur Dempster, Nan Laird and Donald Rubin (1977), the EM algorithm; Gideon Schwarz (1978), the Bayesian information criterion; Hirotugu Akaike (1974), AIC
AccuracyEM increases the likelihood at every step and converges to a local maximum (or saddle point)
Cost per iteration with full covariances, plus for the Cholesky factors
Read firstk-means and k-medoids
APIGaussianMixture (new(k, covariance, seed), predict_proba, score_samples, weights, means, covariances, bic, aic), CovarianceType (Full, Diagonal)

Overview

A Gaussian mixture model (GMM) assumes each point was produced by first choosing one of components with probabilities , and then drawing from that component’s normal distribution . Fitting the model clusters the data, and more besides: each point gets membership probabilities rather than a hard label (a soft clustering), clusters may be elliptical and of different sizes, and the fitted density can score new points and compare models. The expectation-maximisation (EM) algorithm fits it. It alternates between estimating the memberships and re-estimating the parameters, and k-means is its limit with equal, spherical, vanishing covariances.

Where it is used

A mixture of Gaussians is a flexible model for data with several groups.

  • Soft clustering. Each point gets a probability of belonging to each group, as in customer segmentation and image segmentation by colour.
  • Speech and speaker recognition. Gaussian mixture models of spectral features were the standard acoustic model.
  • Density estimation and anomaly detection. A mixture describes the data’s density, and low-probability points are unusual.
  • The EM algorithm. The expectation-maximisation iteration that fits it also fits many other latent-variable models.

History

Karl Pearson (1894) fitted a mixture of two normal distributions to measurements of crab foreheads, by the method of moments, solving a ninth-degree polynomial by hand. Maximum likelihood for mixtures had to wait for computers. Arthur Dempster, Nan Laird and Donald Rubin (1977) unified many earlier special cases as the EM algorithm and proved that it never decreases the likelihood; Jeff Wu (1983) corrected and completed the convergence proof. Information criteria for choosing the number of components came from Hirotugu Akaike (1974) and Gideon Schwarz (1978).

The idea

The mixture likelihood

Under the model, the probability density of a point is a weighted sum of the component densities,

The parameters, the weights , means and covariances , are to be chosen by maximum likelihood: make the observed data as probable as possible, by maximising the log-likelihood .

For a single Gaussian this is easy, and the answer is the sample mean and covariance. For a mixture it is hard, for three reasons.

  • No closed form. The logarithm of a single Gaussian density is a simple quadratic. Here the logarithm is applied to a sum of densities and cannot be simplified, so setting the derivatives to zero gives equations with no explicit solution.
  • Local maxima. The likelihood generally has many of them, so the result depends on the starting point.
  • It is unbounded. Centre one component exactly on a data point and let its covariance shrink to zero. Its density at that point grows without limit, and so does the likelihood, although the fit is useless. The library adds reg_covar to every covariance diagonal, which keeps the covariances from collapsing and rules this out.

Expectation-maximisation

The difficulty comes from not knowing which component generated each point. If we knew, fitting would be easy: collect the points of each component and compute their mean and covariance. Conversely, if we knew the parameters, we could work out how likely each point is to belong to each component. Expectation-maximisation (EM) breaks the circle by alternating between the two, starting from a guess.

E-step: assign points to components, softly. With the current parameters, compute for each point and component the responsibility

This is Bayes’ rule: the prior probability of the component times the density it gives the point, normalised so that the responsibilities of each point sum to 1. It is the posterior probability that point came from component . A point close to one component and far from the others has a responsibility near 1 for it; a point between two components is shared.

M-step: refit each component. Treat as the fraction of point that belongs to component , and compute weighted versions of the usual estimates:

is the effective number of points in the component, and the mean and covariance are averages in which each point counts in proportion to its responsibility.

The two steps are repeated until the log-likelihood stops increasing. This is the same alternation as k-means, assign and then refit, with soft assignments in place of hard ones, and with covariances as well as means.

Why it works. Each iteration can be shown never to decrease the log-likelihood. The E-step constructs a function of the parameters that lies below the log-likelihood everywhere and touches it at the current parameters (a lower bound); the M-step moves to the maximum of that function. Since the bound touches the likelihood at the old parameters and lies below it at the new ones, the likelihood at the new parameters is at least as large as before. EM therefore climbs steadily to a local maximum. Progress can be slow, though:

Figure 12.5. Log-likelihood by iteration.

Starting from k-means, which split the two overlapping elongated clusters across rather than along their length, EM creeps along a plateau for about 25 iterations while the components slowly rotate, then climbs quickly to the better maximum.

Ellipses instead of circles

The three clusters are stretched and tilted, two of them almost touching. k-means draws straight boundaries between centroids and cuts the clusters across. The mixture’s full covariances follow the clusters’ shapes and recover them; the remaining errors are in the region where the two lower clusters overlap. The fitted parameters match the sample statistics of the generating clusters:

Table 12.10. Gaussian mixture fit: means and weights against the truth.

true clustersample meanfitted meanfitted weight (true 1/3)
0(0.02, 0.00)(0.03, -0.01)0.333
1(-0.09, 1.35)(-0.06, 1.31)0.327
2(-4.14, 5.09)(-4.10, 5.06)0.341

Diagonal covariances allow axis-aligned ellipses only, with instead of parameters per component. They are cheaper and more stable in high dimensions, but cannot represent tilted clusters.

Choosing the number of components

A model with more components always fits at least as well, so the likelihood alone cannot choose . Information criteria charge for the number of free parameters :

with for full covariances. Lower is better.

Figure 12.6. BIC against k.

With full covariances the BIC is smallest at the true . With diagonal covariances it keeps falling: several axis-aligned components are needed to approximate each tilted ellipse, so the criterion chooses a different for a different model. BIC penalises more heavily than AIC once and tends to choose fewer components.

Algorithm

Input: the data, the number of components and the covariance type.

  1. Initialise. Run k-means with clusters. Treat its assignments as responsibilities that are 1 for a point’s own cluster and 0 for the others, and perform one M-step to obtain starting weights, means and covariances.
  2. E-step. For each point and component, compute the logarithm of the weight times the Gaussian density, using the Cholesky factor of the covariance for the quadratic form and the determinant. The log of the mixture density at the point is the logarithm of the sum of the exponentials of these numbers; it is computed after subtracting their maximum (the log-sum-exp trick), so that densities too small to represent do not underflow to zero. The responsibilities are the exponentials of the differences.
  3. M-step. Update the weights, means and covariances by the responsibility-weighted formulas. Add reg_covar to the diagonal of each covariance and compute its Cholesky factor for the next E-step.
  4. Test. If the mean log-likelihood changed by less than the tolerance (), or 200 iterations have been done, stop; otherwise go to 2.
  5. Label each point by the component with the largest responsibility.

An iteration costs with full covariances in dimensions.

Model selection: fit the model for each candidate , compute the BIC from the final log-likelihood and the number of parameters, and choose the smallest.

Implementation

        for it in 1..=self.max_iterations {
            self.iterations = it;
            // E-step.
            let mut total = 0.0;
            for (i, row) in x.rows().into_iter().enumerate() {
                let lj = self.log_joint(&row.to_vec());
                let m = lj.iter().copied().fold(f64::NEG_INFINITY, f64::max);
                let s: f64 = lj.iter().map(|v| (v - m).exp()).sum();
                total += m + s.ln();
                for c in 0..self.k {
                    resp[[i, c]] = (lj[c] - m).exp() / s;
                }
            }
            self.log_likelihood = total / n as f64;
            if (self.log_likelihood - previous).abs() < self.tolerance {
                break;
            }
            previous = self.log_likelihood;
            self.maximise(x, &resp)?;
            if it == self.max_iterations {
                // Stopped at the limit after an M-step: report the likelihood of the final parameters.
                self.log_likelihood = self.score_samples(x)?.iter().sum::<f64>() / n as f64;
            }
        }
  • Densities are evaluated through the Cholesky factor of each covariance: , and the Mahalanobis distance is .
  • Responsibilities are computed from log-densities with the maximum subtracted, so far-away points do not underflow to 0/0.
  • mean_log_likelihood always describes the final parameters. (Before this chapter was written, a fit that stopped at the iteration limit reported the value from one step earlier.)

In practice

//! Gaussian mixture models: soft assignments, densities, and choosing the number of components by BIC.

use lib_jsl_machine_learning::common::Clusterer;
use lib_jsl_machine_learning::datasets::make_blobs;
use lib_jsl_machine_learning::unsupervised::clustering::{CovarianceType, GaussianMixture};
use ndarray::arr2;

fn main() {
    let (x, _) = make_blobs(150, &[vec![0.0, 0.0], vec![4.0, 1.0], vec![1.0, 4.0]], 0.9, 2);
    for k in 1..=5 {
        let mut g = GaussianMixture::new(k, CovarianceType::Full, 1);
        g.fit_predict(x.view()).unwrap();
        println!("k = {k}: mean log-likelihood {:.4}, BIC {:7.1}, {} EM iterations", g.mean_log_likelihood(), g.bic(), g.iterations());
    }
    let mut g = GaussianMixture::new(3, CovarianceType::Full, 1);
    g.fit_predict(x.view()).unwrap();
    println!("weights {:.3?}", g.weights());
    let probe = arr2(&[[0.0, 0.0], [2.0, 0.5], [10.0, 10.0]]);
    let p = g.predict_proba(probe.view()).unwrap();
    let density = g.score_samples(probe.view()).unwrap();
    for (i, d) in density.iter().enumerate() {
        println!("point {:?}: memberships {:.3}, log density {d:.2}", probe.row(i).to_vec(), p.row(i));
    }
}
k = 1: mean log-likelihood -4.1471, BIC  3763.0, 2 EM iterations
k = 2: mean log-likelihood -3.8495, BIC  3531.8, 11 EM iterations
k = 3: mean log-likelihood -3.6651, BIC  3402.4, 7 EM iterations
k = 4: mean log-likelihood -3.6627, BIC  3436.9, 22 EM iterations
k = 5: mean log-likelihood -3.6563, BIC  3467.9, 187 EM iterations
weights [0.338, 0.333, 0.329]
point [0.0, 0.0]: memberships [1.000, 0.000, 0.000], log density -2.75
point [2.0, 0.5]: memberships [0.474, 0.002, 0.523], log density -4.87
point [10.0, 10.0]: memberships [0.000, 1.000, 0.000], log density -73.46

The point between two components is split almost evenly between them. The far point at (10, 10) is assigned to one component with certainty, yet its log density of −73 shows that it fits none: memberships are relative, and the density is the tool for spotting outliers. Extra components barely raise the likelihood and take many more iterations to settle.

Strengths

  • Soft, probabilistic clustering with elliptical clusters of different sizes and orientations.
  • A density model: likelihoods for new points, outlier scores, and BIC or AIC for choosing .

Weaknesses

  • Local maxima and sensitivity to initialisation; EM can be slow when clusters overlap.
  • Full covariances need parameters, too many in high dimensions without regularisation.
  • Assumes Gaussian clusters; curved clusters need many components.

Exercises

  1. Derive the M-step updates by maximising the expected complete-data log-likelihood.
  2. Show that EM never decreases the likelihood, using Jensen’s inequality.
  3. Show that with shared covariance and , EM becomes Lloyd’s k-means algorithm.
  4. Show that the likelihood is unbounded without regularisation, by centring a component on a data point.
  5. Fit a mixture to data drawn from a single uniform square, and plot the BIC against . What does it choose, and why?
Hints and answers
  1. Maximise over the parameters with : , , .
  2. Jensen’s inequality gives with equality at ; maximising therefore cannot decrease the likelihood.
  3. With and the responsibilities become 0 or 1 (each point goes to its nearest mean) and the means become cluster averages: Lloyd’s algorithm.
  4. Centre one component on a data point and let its covariance shrink to 0: its density at that point grows without bound while the other points keep a positive density from the other components, so the likelihood is unbounded.
  5. A uniform square is not Gaussian, so BIC typically selects more than one component (several tile the square). It does not indicate several real clusters, only that the Gaussian shape assumption is wrong.

Further reading

  • A. P. Dempster, N. M. Laird and D. B. Rubin, “Maximum likelihood from incomplete data via the EM algorithm”, Journal of the Royal Statistical Society B 39 (1977) 1–38.
  • G. McLachlan and D. Peel, Finite Mixture Models, Wiley, 2000.
  • C. M. Bishop, Pattern Recognition and Machine Learning, Springer, 2006, chapter 9.
  • G. Schwarz, “Estimating the dimension of a model”, Annals of Statistics 6 (1978) 461–464.