TExcelTAD
Home › Classical ML Algorithms: Supervised & Unsupervised › Gaussian Mixtures and the EM Algorithm

Gaussian Mixtures and the EM Algorithm

k-means gives every point exactly one cluster and assumes round clusters of equal spread. Real groups are often stretched, tilted, of different sizes, and points between two groups genuinely belong a bit to each. A Gaussian mixture model (GMM) describes the data as coming from kk Gaussian distributions, each with its own mean, covariance (shape and orientation) and weight, and gives every point a probability of belonging to each component. It is fitted with the expectation-maximisation (EM) algorithm, one of the most widely used ideas in statistics.

The model

p(x)=∑j=1kπj N(x∣μj,Σj),πj≥0,  ∑jπj=1p(\mathbf{x}) = \sum_{j=1}^{k} \pi_j \, \mathcal{N}(\mathbf{x} \mid \boldsymbol{\mu}_j, \Sigma_j), \qquad \pi_j \ge 0, \ \ \sum_j \pi_j = 1

Think of each point as generated in two steps: pick a component jj with probability πj\pi_j, then draw x\mathbf{x} from that component's Gaussian. The component is a hidden (latent) variable. We would like to maximise the log-likelihood ∑ilog⁡p(xi)\sum_i \log p(\mathbf{x}_i), but the sum inside the log has no closed-form maximum.

EM: alternate guessing and fitting

E-step. With the current parameters, compute each point's responsibilities, the posterior probability of each component (Bayes' rule):

rij=πj N(xi∣μj,Σj)∑l=1kπl N(xi∣μl,Σl)r_{ij} = \frac{\pi_j \, \mathcal{N}(\mathbf{x}_i \mid \boldsymbol{\mu}_j, \Sigma_j)}{\sum_{l=1}^{k} \pi_l \, \mathcal{N}(\mathbf{x}_i \mid \boldsymbol{\mu}_l, \Sigma_l)}

M-step. Refit each Gaussian to all points, weighting point ii by rijr_{ij}. With Nj=∑irijN_j = \sum_i r_{ij}:

πj=Njn,μj=1Nj∑irijxi,Σj=1Nj∑irij(xi−μj)(xi−μj)⊤\pi_j = \frac{N_j}{n}, \qquad \boldsymbol{\mu}_j = \frac{1}{N_j} \sum_i r_{ij} \mathbf{x}_i, \qquad \Sigma_j = \frac{1}{N_j} \sum_i r_{ij} (\mathbf{x}_i - \boldsymbol{\mu}_j)(\mathbf{x}_i - \boldsymbol{\mu}_j)^\top

Each iteration never lowers the log-likelihood, so EM converges, to a local maximum that depends on the start. k-means is the special case with equal spherical covariances shrunk to zero, where responsibilities become 0 or 1. The derivations are in Gaussian Mixture Models, The EM Algorithm and Mixtures as Latent-Variable Models; the Gaussian itself in Marginals and Conditionals of Gaussians.

EM from scratch

Two clusters: 200 points in a tilted, elongated cloud and 100 in a small round one. EM starts from one point in each region and the whole data's covariance, and is compared with GaussianMixture started from the same means:

python · try it yourself
import numpy as np
from scipy.stats import multivariate_normal
from sklearn.mixture import GaussianMixture

rng = np.random.default_rng(0)
A = rng.multivariate_normal([0, 0], [[2.0, 1.2], [1.2, 1.0]], 200)     # an elongated, tilted cluster
B = rng.multivariate_normal([4, 0], [[0.3, 0.0], [0.0, 0.3]], 100)     # a small round one
X = np.vstack([A, B])

def em(X, means, iters=100, reg=1e-6):
    n, d = X.shape
    k = len(means)
    weights = np.full(k, 1 / k)
    covs = np.array([np.cov(X.T) for _ in range(k)])
    for it in range(iters):
        # E-step: responsibilities r_ik = p(component k | x_i)
        dens = np.column_stack([w * multivariate_normal(m, c).pdf(X) for w, m, c in zip(weights, means, covs)])
        loglik = np.log(dens.sum(axis=1)).mean()
        R = dens / dens.sum(axis=1, keepdims=True)
        # M-step: weighted proportions, means and covariances
        Nk = R.sum(axis=0)
        weights = Nk / n
        means = (R.T @ X) / Nk[:, None]
        covs = np.array([((R[:, j, None] * (X - means[j])).T @ (X - means[j])) / Nk[j] + reg * np.eye(d) for j in range(k)])
        if it in (0, 1, 5, 20):
            print(f"  iteration {it + 1:3d}  mean log-likelihood {loglik:.4f}")
    return weights, means, covs, R, loglik

init = X[[0, 250]]                                     # one starting mean in each region
w, m, c, R, ll = em(X, init)
gm = GaussianMixture(n_components=2, means_init=init, covariance_type="full", max_iter=100, tol=1e-10,
                     random_state=0).fit(X)
print("weights ours", w.round(3), " sklearn", gm.weights_.round(3))
print("means ours  ", m.round(3).tolist())
print("means skl   ", gm.means_.round(3).tolist())
print("covariance of component 0:", c[0].round(2).tolist())
print("mean log-likelihood ours", round(ll, 4), " sklearn", round(gm.score(X), 4))
x_mid = np.array([[2.2, 0.0]])
print("soft assignment of the point (2.2, 0):", gm.predict_proba(x_mid).round(3))
  iteration   1  mean log-likelihood -3.5336
  iteration   2  mean log-likelihood -3.1202
  iteration   6  mean log-likelihood -2.8475
  iteration  21  mean log-likelihood -2.8450
weights ours [0.671 0.329]  sklearn [0.671 0.329]
means ours   [[0.144, 0.102], [3.988, 0.032]]
means skl    [[0.144, 0.102], [3.988, 0.032]]
covariance of component 0: [[1.98, 1.13], [1.13, 0.93]]
mean log-likelihood ours -2.845  sklearn -2.845
soft assignment of the point (2.2, 0): [[0.776 0.224]]

The log-likelihood rises at every iteration and settles by about iteration 20. EM recovers the generating mixture closely: weights 0.671/0.3290.671/0.329 (true 2/32/3 and 1/31/3), means near (0,0)(0, 0) and (4,0)(4, 0), and the tilted covariance (true [[2.0,1.2],[1.2,1.0]][[2.0, 1.2], [1.2, 1.0]]). The point (2.2,0)(2.2, 0), between the clusters, gets a soft assignment: 78 % to the large component, whose wide spread reaches it, 22 % to the small one. GaussianMixture agrees on every number.

Choosing the number of components

The likelihood always rises with more components, so it cannot choose kk by itself. The Bayesian information criterion penalises parameters: BIC=−2log⁡L+plog⁡n\text{BIC} = -2 \log L + p \log n, with pp the number of free parameters; lower is better.

python · try it yourself
import numpy as np
from sklearn.mixture import GaussianMixture
from sklearn.cluster import KMeans
from sklearn.metrics import adjusted_rand_score

rng = np.random.default_rng(0)
A = rng.multivariate_normal([0, 0], [[2.0, 1.2], [1.2, 1.0]], 200)
B = rng.multivariate_normal([4, 0], [[0.3, 0.0], [0.0, 0.3]], 100)
X = np.vstack([A, B])
truth = np.r_[np.zeros(200), np.ones(100)]

print("components  BIC (lower is better)")
for k in range(1, 6):
    gm = GaussianMixture(n_components=k, n_init=3, random_state=0).fit(X)
    print(f"{k:5d}       {gm.bic(X):8.1f}")
gm = GaussianMixture(n_components=2, n_init=3, random_state=0).fit(X)
km = KMeans(n_clusters=2, n_init=10, random_state=0).fit(X)
print("ARI with the true components: GMM", round(adjusted_rand_score(truth, gm.predict(X)), 3),
      " k-means", round(adjusted_rand_score(truth, km.labels_), 3))
components  BIC (lower is better)
    1         2045.1
    2         1769.7
    3         1800.1
    4         1829.4
    5         1857.6
ARI with the true components: GMM 0.987  k-means 0.682

BIC is lowest at 2 components, the true number. Measured against the true components with the adjusted Rand index, the GMM is almost perfect (0.987), while k-means (0.682) cuts the elongated cloud with a straight line halfway between the centroids and gives its right tip to the small cluster.

Hyperparameters

Hyperparameter Effect
n_components kk; choose with BIC or AIC
covariance_type "full" (any ellipse per component), "tied" (one shared), "diag" (axis-aligned), "spherical" (circles); fewer parameters, more stable
n_init, init_params restarts and k-means-based starts against bad local maxima
reg_covar added to the diagonal so a component cannot collapse onto one point

Strengths, weaknesses, when to use it

A GMM gives soft assignments, elliptical clusters of different sizes and orientations, a density p(x)p(\mathbf{x}) that can score how unusual a point is, and a principled way (BIC) to choose kk. It assumes roughly Gaussian clusters, has local maxima, needs O(kd2)O(kd^2) parameters with full covariances (unstable in high dimensions with little data), and like k-means it assigns every point to some component. Use it when clusters are elliptical or overlap, when you need membership probabilities, or as a density model for anomaly detection and generation.

Pitfalls

  • Singular covariances. A component that shrinks onto a few identical points has a likelihood going to infinity; reg_covar prevents it.
  • Too many full covariances in high dimensions. 100 features mean 5050 covariance parameters per component; use "diag" or reduce dimensions first.
  • Trusting one run. Use n_init above 1.

Practice

  1. A point has densities N1=0.02\mathcal{N}_1 = 0.02, N2=0.08\mathcal{N}_2 = 0.08 under two components with weights π=(0.8,0.2)\pi = (0.8, 0.2). Compute its responsibilities.
Answer

Numerators 0.8⋅0.02=0.0160.8 \cdot 0.02 = 0.016 and 0.2⋅0.08=0.0160.2 \cdot 0.08 = 0.016: equal, so r=(0.5,0.5)r = (0.5, 0.5). The larger component's higher weight exactly offsets the smaller component's higher density.

  1. How many free parameters does a 2-D GMM with 2 full-covariance components have?
Answer

Per component: 2 means and 3 covariance entries (symmetric 2×22 \times 2), so 5; two components give 10; plus 1 free weight (the second is 1−π11 - \pi_1): 11 parameters.

Test yourself

What does the E-step of EM compute for a Gaussian mixture?

  1. New means and covariances
  2. Responsibilities: each point's probability of belonging to each component
  3. The number of components
  4. The BIC

How does a GMM's assignment of points differ from k-means'?

  1. It is the same
  2. It is soft: each point has a probability for each component
  3. It only works in 2-D
  4. It needs labels

Why use BIC instead of the likelihood to choose the number of components?

  1. BIC is faster
  2. The likelihood always increases with more components; BIC penalises extra parameters
  3. BIC needs no data
  4. The likelihood can be negative