Gaussian mixture models
Gaussian mixture models, expectation-maximization, numerical stability, model selection and the k-means limit.
After this lesson you can
- Describe the generative mixture model and its latent assignments.
- Derive EM responsibilities and parameter updates.
- Implement numerically stable EM with covariance regularization.
- Explain likelihood singularities and component collapse.
- Select components and covariance type using BIC and validation likelihood.
- Prove k-means is the zero-variance limit of EM.
Before you start
- 12Lloyd's algorithmk-means++ seedingKernel density estimation
- 04Mixture distributions and hierarchical modelsMultivariate Gaussian distributionMahalanobis distance
- 05Maximum likelihood estimator (MLE)
- 06Lagrange multipliers
- 09Log-sum-exp trick and stable softmaxCholesky in finite precision: stability and jitter
- 02Cholesky decomposition
Motivation: elliptical, overlapping groups of different sizes
k-means gives each group a fixed shape: a Voronoi cell, the region of points nearest a centroid. This amounts to assuming round, similarly sized groups separated by hyperplanes, and making a hard decision about each point’s membership. Real data are often elliptical with different orientations and sizes, and frequently overlap: near the boundary, an honest answer to “which group does this point belong to?” is “probably one, but possibly the other.”
A Gaussian mixture model addresses all three limitations at once. Each group is described by a mean, covariance matrix (shape and orientation) and weight (size), and each point receives a probability of belonging to each group. The model is also a full density : evaluate it, sample it, or use it for classification or anomaly detection. In the first example, three elongated oblique clouds challenge k-means, which can draw only straight lines.
import numpy as np, warnings
from sklearn.datasets import make_blobs
from sklearn.cluster import KMeans
from sklearn.mixture import GaussianMixture
from sklearn.metrics import adjusted_rand_score as ARI
warnings.filterwarnings("ignore")
X, y = make_blobs(n_samples=600, centers=3, cluster_std=1.1, random_state=170)
X = X @ np.array([[0.608, -0.637], [-0.409, 0.853]]) # estira y gira las nubes: elipses oblicuas
km = KMeans(3, n_init=10, random_state=0).fit(X)
gm = GaussianMixture(3, covariance_type="full", n_init=5, random_state=0).fit(X)
R = gm.predict_proba(X)
print(f"ARI k-means = {ARI(y, km.labels_):.3f} ARI mezcla gaussiana = {ARI(y, gm.predict(X)):.3f}")
print(f"log-verosimilitud media por punto de la mezcla: {gm.score(X):.3f}")
print("pesos estimados:", np.round(gm.weights_, 3))
for u in (0.99, 0.9, 0.6):
print(f"puntos con responsabilidad máxima < {u}: {(R.max(1) < u).sum()} de {len(X)}")
i = np.argmin(R.max(1))
print("el punto más ambiguo reparte su pertenencia así:", np.round(R[i], 3), "; k-means lo manda al grupo", km.labels_[i], "sin matices")Adjusted Rand index (ARI) is 1 if the partition matches truth. k-means reaches 0.493 because Voronoi boundaries cannot separate oblique clouds; the mixture gets nearly everything right (0.995) and recovers the three weights (0.332, 0.333 and 0.335, versus true 1/3 each). Notice the last line: of 600 points only 6 have maximum responsibility below 0.99, and the most ambiguous splits 0.249 and 0.751 between two groups. These groups barely overlap; the next interactive uses data that do.
Before definitions, watch the algorithm work. It is EM (expectation-maximization) on 180 points from three ellipses, two touching on the left. Each iteration has two half-steps. In the E step, each point divides its color among components according to the probability each generated it. In the M step, each component refits (mean, covariance and weight) using points weighted by those probabilities. Everything in the lesson is a more careful version of those steps.
Review: the multivariate Gaussian
A Gaussian mixture is made of Gaussian pieces, so keep their geometry fresh. The density of in , with symmetric positive-definite (definition), is
Quantity is Mahalanobis distance to the mean. By the spectral theorem, , and points at Mahalanobis distance form an ellipsoid with semiaxes along eigenvector directions . Thus covariance is cloud shape: eigenvectors give orientation and eigenvalues each axis’s length. In the plane, follows when , so a radius- ellipsoid contains probability : 39.3% at and 86.5% at , the interactive contours.
Two useful facts: the density’s is quadratic in , and stable evaluation does not require inverting (Cholesky factorization, linear algebra lesson, suffices; below).
The model: a randomly chosen Gaussian
It is a generative model, so use ancestral sampling: draw with probabilities and then from the selected Gaussian (with , with , as in the Gaussian lesson). This lesson’s interactives generate data that way.
A mixture is not a Gaussian. It can be multimodal (with well-separated components, one mode each; if they overlap, modes merge and there are fewer modes than components, as with two nearby clouds below), asymmetric and more kurtotic than a normal distribution. With large it can approximate arbitrary densities: lesson 4’s kernel estimation is exactly a mixture with components of weight , means at data points and covariances , converging to any density in as and (Devroye and Györfi, 1985). A mixture with compresses that idea: a few fitted components instead of one per datum.
Count free parameters: weights, means and symmetric covariance entries. With and that is 21449; quadratic growth in motivates other covariance types below.
Responsibilities: component posterior
The natural question about an observed point is where it came from. By Bayes,
The three forces in have clear interpretations: weight favors large components; penalizes wide components because they spread mass over more volume and give less density at each point; and Mahalanobis distance penalizes distance from center measured using component shape. k-means keeps only the third, with for all. Hard assignment is the model’s Bayes classifier, and responsibilities are its confidence: reliable probabilities only if the mixture models data well (the same calibration caveat).
What is the boundary between two components? The log-likelihood ratio is quadratic:
Proof
Since , subtract scores and expand (symmetry of gives factor 2). With quadratic and volume terms cancel, leaving affine function ; since with the log-likelihood ratio, . For : .
∎This is familiar from LDA and QDA: a mixture posterior with shared covariance is logistic regression, whose form linear discriminant analysis shares (and with components, softmax regression); if covariances differ, the boundary is quadratic. In one dimension a degree-2 polynomial can cross 0 at two points, and it does: the wider component wins again in both tails, which one threshold rule cannot imitate.
import numpy as np
from scipy.special import logsumexp, expit
def resp(x, pis, mus, sig):
lp = np.log(pis)[None] - 0.5 * ((x[:, None] - mus[None]) / sig[None]) ** 2 - np.log(sig)[None]
return np.exp(lp - logsumexp(lp, axis=1, keepdims=True))
x = np.linspace(-6, 10, 4001)
# (1) el ejemplo del ejercicio: pesos iguales, N(0,1) y N(3,1), x = 1
r = resp(np.array([1.0]), np.array([0.5, 0.5]), np.array([0.0, 3.0]), np.array([1.0, 1.0]))
print("r_1(1) =", np.round(r[0], 4))
# (2) varianzas iguales: la posterior es una sigmoide de una función afín de x
pis, mus, sig = np.array([0.3, 0.7]), np.array([0.0, 3.0]), np.array([1.2, 1.2])
w = (mus[0] - mus[1]) / sig[0] ** 2
b = np.log(pis[0] / pis[1]) - 0.5 * (mus[0] + mus[1]) * (mus[0] - mus[1]) / sig[0] ** 2
print("varianzas iguales: máx |r_1 - sigmoide(w x + b)| =", np.abs(resp(x, pis, mus, sig)[:, 0] - expit(w * x + b)).max())
# (3) varianzas distintas: dos cortes de r_1 = 1/2
pis, mus, sig = np.array([0.5, 0.5]), np.array([0.0, 3.0]), np.array([0.7, 2.0])
r1 = resp(x, pis, mus, sig)[:, 0]
cortes = x[:-1][np.diff(np.sign(r1 - 0.5)) != 0]
print("varianzas distintas: cortes de r_1 = 0.5 en x ≈", np.round(cortes, 2), " r_1 en x = -6 y x = 10:", np.round([r1[0], r1[-1]], 4))The cell confirms all three facts: , the sigmoid reproduces the posterior with an error of (rounding), and with there are two crossings (at and ) and at both extremes.
The log-likelihood and why there is no closed-form solution
For independent observations (ordinary maximum likelihood), the objective function is
The logarithm of a sum does not split into a sum of logarithms, so each component’s parameters are coupled to all the others inside the logarithm. For a single Gaussian, the derivative vanishes at the sample mean and covariance; here there is no formula. But an identity makes everything clear: the derivative with respect to the parameters of component is
because . This is the score (the gradient of the log-likelihood) of an ordinary Gaussian, but each observation has weight , which itself depends on . The next cell checks the identity for the means, , against finite differences.
import numpy as np
from scipy.stats import multivariate_normal as mvn
rng = np.random.default_rng(5)
X = rng.normal(size=(50, 2)) * [2, 1]
pis = np.array([0.4, 0.6]); mus = np.array([[0., 0.], [1., 0.5]])
covs = np.array([[[1.5, 0.3], [0.3, 0.8]], [[0.7, -0.2], [-0.2, 1.2]]])
def ell(mus):
return np.log(sum(p * mvn(m, S).pdf(X) for p, m, S in zip(pis, mus, covs))).sum()
dens = np.column_stack([p * mvn(m, S).pdf(X) for p, m, S in zip(pis, mus, covs)])
R = dens / dens.sum(1, keepdims=True)
analitico = np.array([((R[:, k, None] * (X - mus[k])) @ np.linalg.inv(covs[k])).sum(0) for k in range(2)])
h, numerico = 1e-6, np.zeros_like(mus)
for k in range(2):
for a in range(2):
mp, mm = mus.copy(), mus.copy()
mp[k, a] += h; mm[k, a] -= h
numerico[k, a] = (ell(mp) - ell(mm)) / (2 * h)
print("gradiente analítico:\n", np.round(analitico, 6))
print("diferencias finitas:\n", np.round(numerico, 6))
print("máx |diferencia| =", np.abs(analitico - numerico).max())The two matrices agree to all displayed digits (the maximum difference, , is finite-difference error). Setting the gradient to zero is therefore the maximum-likelihood problem for Gaussians with weighted data, and this is the blueprint for EM: with fixed weights the problem has a closed-form solution, and given that solution the weights are recalculated.
Proof
By the gradient identity, the equations for and are those of a Gaussian with weighted data. For : ; since is invertible, , giving the weighted mean. For : has gradient with respect to equal to (using and , with and symmetric, as matrix gradients); summing with weights and setting to zero gives , and multiplying by on both sides yields the result. For the weights, the Lagrangian gives, by the gradient identity with , the equation , that is, . Summing over and using gives and . (Lagrange multipliers.)
∎Notice that the equations do not solve anything: the right-hand side depends on through the . They form a fixed-point equation, , and the natural way to find a fixed point is to iterate.
The EM algorithm for Gaussian mixtures
The M-step is the Gaussian MLE with observations “distributed” among components. If you knew the assignments , with , these would be the mean, covariance and frequency of each group: those of a supervised Gaussian classification model, as in LDA or QDA. EM works with the best information available: the expected assignments. That is why the mixed colors in the first interactive are at the heart of the algorithm.
Two questions deliberately lie beyond this lesson. The first is why this procedure cannot decrease likelihood: in the next lesson you will see that the E-step builds a lower bound on touching at and that the M-step maximizes that bound, yielding (monotonicity and convergence). Here you can see the result: the first interactive’s graph never decreases. The second question is what kind of point it reaches: a stationary point, not necessarily the global maximum. Per iteration, including Cholesky factorizations of the covariance matrices, the cost is in time and in memory.
A stable implementation from scratch
Three decisions separate an implementation that works from one that returns NaN:
- Log-space with log-sum-exp. In moderate dimensions the densities are or less and the ratio in the definition is . Calculate each component’s score and normalize with , where (the log-sum-exp trick), which also gives without leaving log-space.
- Cholesky instead of inversion. With , obtain by solving a triangular system, and . It is cheaper and more stable than inversion, and also fails with a Cholesky error when the covariance ceases to be positive definite rather than continuing with meaningless numbers.
- Regularization. Add (in scikit-learn,
reg_covar, default ) to each estimated covariance, the same device as Cholesky jitter. It prevents singular matrices and, as you will see, controls the model’s main pathology.
Initialization and stopping remain to be decided. Standard initialization uses k-means (with k-means++ seeding): Lloyd’s hard assignments are the responsibilities for the first M-step. The stopping rule compares the mean log-likelihood with the previous iteration and stops when its increase is less than tol. The cell implements everything and validates it against sklearn.mixture.GaussianMixture, giving it the same initial conditions so that the comparison concerns algorithms rather than seeds.
import numpy as np, warnings
from scipy.linalg import solve_triangular
from scipy.special import logsumexp
from sklearn.datasets import make_blobs
from sklearn.mixture import GaussianMixture
warnings.filterwarnings("ignore")
def log_gauss(X, mu, L):
"""log N(x | mu, Sigma) con Sigma = L L^T: el exponente es ||L^{-1}(x - mu)||^2, sin invertir Sigma."""
z = solve_triangular(L, (X - mu).T, lower=True)
return -0.5 * (X.shape[1] * np.log(2 * np.pi) + (z ** 2).sum(0)) - np.log(np.diag(L)).sum()
def e_step(X, pis, mus, chols):
"""Log-responsabilidades (n, K) y log-verosimilitud media, siempre en log-espacio."""
lp = np.column_stack([np.log(p) + log_gauss(X, m, L) for p, m, L in zip(pis, mus, chols)])
lse = logsumexp(lp, axis=1)
return lp - lse[:, None], lse.mean()
def m_step(X, resp, reg):
"""Pesos, medias y covarianzas ponderados por las responsabilidades; reg se suma a la diagonal."""
n, d = X.shape
nk = resp.sum(0) + 10 * np.finfo(float).eps
mus = (resp.T @ X) / nk[:, None]
covs = np.empty((resp.shape[1], d, d))
for k in range(resp.shape[1]):
D = X - mus[k]
covs[k] = (resp[:, k, None] * D).T @ D / nk[k] + reg * np.eye(d)
return nk / n, mus, covs
def kmeanspp(X, K, rng):
C = [X[rng.integers(len(X))]]
for _ in range(K - 1):
D2 = np.min([((X - c) ** 2).sum(1) for c in C], axis=0)
C.append(X[rng.choice(len(X), p=D2 / D2.sum())])
return np.array(C)
def init_params(X, K, rng, reg=1e-6):
"""k-means++ y Lloyd; las asignaciones duras son las responsabilidades del primer paso M."""
C = kmeanspp(X, K, rng)
for _ in range(50):
z = ((X[:, None] - C[None]) ** 2).sum(2).argmin(1)
C2 = np.array([X[z == k].mean(0) if (z == k).any() else C[k] for k in range(K)])
if np.allclose(C2, C):
break
C = C2
return m_step(X, np.eye(K)[z], reg)
def em(X, pis, mus, covs, reg=1e-6, tol=1e-6, max_iter=200):
prev = -np.inf
for it in range(1, max_iter + 1):
chols = [np.linalg.cholesky(S) for S in covs]
log_r, ll = e_step(X, pis, mus, chols)
pis, mus, covs = m_step(X, np.exp(log_r), reg)
if abs(ll - prev) < tol:
break
prev = ll
return pis, mus, covs, ll, it
X, _ = make_blobs(600, centers=[[0, 0], [3.5, 0], [1.5, 3.5]], cluster_std=1.0, random_state=0)
X = X @ np.array([[1.0, 0.5], [0.0, 0.7]])
p0, m0, c0 = init_params(X, 3, np.random.default_rng(0))
pis, mus, covs, ll, it = em(X, p0, m0, c0)
sk = GaussianMixture(3, covariance_type="full", tol=1e-6, reg_covar=1e-6, max_iter=200,
weights_init=p0, means_init=m0, precisions_init=np.linalg.inv(c0)).fit(X)
print(f"iteraciones: nuestra {it}, sklearn {sk.n_iter_}")
print(f"log-verosimilitud media: nuestra {ll:.10f}, sklearn lower_bound_ {sk.lower_bound_:.10f}")
print(f"máx |medias| = {np.abs(mus - sk.means_).max():.1e} máx |pesos| = {np.abs(pis - sk.weights_).max():.1e} máx |covarianzas| = {np.abs(covs - sk.covariances_).max():.1e}")
# el mismo cálculo en espacio lineal se rompe en dimensión alta: d = 600, tres componentes N(m_k, I)
rng = np.random.default_rng(1)
d = 600
M = rng.normal(0, 0.3, size=(3, d)); Z = rng.normal(size=(5, d)) + M[0]
I = np.eye(d)
lp = np.column_stack([np.log(1 / 3) + log_gauss(Z, M[k], I) for k in range(3)])
dens = np.exp(lp) # densidades en espacio lineal
print("densidad mínima en espacio lineal:", dens.min(), " log-densidad típica:", np.round(lp[0], 1))
print("responsabilidades ingenuas (fila 0):", dens[0] / dens[0].sum())
print("responsabilidades con logsumexp (fila 0):", np.round(np.exp(lp[0] - logsumexp(lp[0])), 4))With the same initial conditions, our EM and scikit-learn’s both take 21 iterations, end at the same mean log-likelihood ( to the ten printed decimal places), and their means, weights and covariances match to machine precision (differences of order ). That is no magic: it is the same algorithm. The second half of the cell shows why log-space is necessary: in the log-densities range from to , and since the smallest positive number representable by a float64 is (and already rounds to 0), all three densities are exactly and naive responsibilities are nan, while log-sum-exp gives the correct values (1, 0, 0). The lesson’s coding exercise asks you to write exactly this E-step.
Pathologies: singularities, permutations and local optima
Maximum likelihood for mixtures has a history of problems that a single Gaussian does not. There are three mixture pathologies: an unbounded likelihood, a solution that exists only up to label permutation, and a surface with many local optima.
Singularities: a collapsing component
Proof
At , the density is at least component 1’s contribution: . At each with , , which does not depend on . Hence
∎Consequences: the supremum of is , so the global maximum-likelihood estimator does not exist; EM finds local maxima, and the closer a solution is to collapse, the more “likely” a useless solution appears. The mechanism is a component shrinking onto a single observation (or, more generally, a few observations contained in a proper affine subspace, such as points in ). With one covariance shared by all components, this pathology disappears if enough observations are in general position: a single cannot shrink without destroying the density of all observations away from a mean. In 1D, more distinct observations than components suffice: two observations then share the nearest mean, one is at distance from every mean ( is the smallest separation between observations), and its density, of order , pulls to as . The interactive uses an explicit model: one component centered on an observation, with standard deviation under your control, and another fixed component explaining the rest.
reg_covar): the blue curve flattens at with , at with and at with . The floor bounds , but the best value still occurs as , with the component stuck to one observation. Next select the inverse-gamma prior on (shape 1, scale 0.02, mode 0.01): the term drives the objective down as the component narrows and the maximum becomes an interior point, at . Both floor and prior bound the pathology; only the prior removes the boundary supremum, and both require choosing a scale.The interactive describes a family of parameters; the next cell lets EM make the journey, with a two-component mixture over 14 1D observations and the em function you have already implemented, with component A starting at .
rng = np.random.default_rng(3)
x = np.sort(np.where(rng.random(14) < 0.5, rng.normal(-1.5, 0.7, 14), rng.normal(1.8, 1.0, 14)))[:, None]
j = 6 # la componente A se inicia sobre el dato x_j = -1.028
def corre(v0, reg, iters=60):
pis, mus, covs = np.array([0.15, 0.85]), np.array([x[j], x.mean(0)]), np.array([[[v0]], [[x.var()]]])
for t in range(iters):
chols = [np.linalg.cholesky(S) for S in covs]
log_r, ll = e_step(x, pis, mus, chols)
if t in (0, 1, 3, 10):
print(f" t={t:2d} ell = {14 * ll:8.2f} varianza de A = {covs[0, 0, 0]:.2e}")
pis, mus, covs = m_step(x, np.exp(log_r), reg)
return 14 * ll, covs[0, 0, 0], np.exp(log_r)[:, 0].sum()
print("Datos 1D:", np.round(x.ravel(), 2))
for v0, reg, nota in [(0.09, 0, "arranque ancho, sin suelo"), (1e-3, 0, "arranque estrecho, sin suelo"), (1e-3, 1e-6, "reg_covar = 1e-6"), (1e-3, 1e-2, "reg_covar = 1e-2")]:
print(f"{nota}:")
ell, var, nA = corre(v0, reg)
print(f" final: ell = {ell:.2f}, varianza de A = {var:.2e}, puntos que le pertenecen = {nA:.2f}")There are three things to read. With a broad start (variance 0.09), EM reaches a reasonable solution, , with the component covering 4.14 effective points. With a narrow start (variance ) and no floor, collapse occurs: A’s variance drops from to in one iteration and to in three, and jumps to , more than 26 units above the good solution, with 1.00 effective points. Collapse is explosive because the new variance is on the order of the other observations’ responsibilities for A, which are with the distance to the nearest observation: (here and give , the order of the variance after one iteration, and at the next is already 0 in float64). Variance stays at , the rounding error of the weighted mean, and stops rising only because float64 precision runs out. With reg_covar the variance stays pinned to the floor and , greater than the reasonable solution’s: the floor bounds but does not eliminate the attractor, and that solution is still spurious (0.99 effective points). With it disappears (A ends with 0.26 effective points and ), but at the cost of destroying the component.
There are two kinds of safeguards. Numerical: a variance floor reg_covar, which guarantees and therefore ; and discarding or restarting components whose effective count falls below a few points (collapse is signaled by or a tiny variance, as in the cell). Statistical: bound the eigenvalue ratio across components, restoring estimator consistency (Hathaway, 1985), or place a prior on covariances (with an inverse Wishart of scale , MAP adds to the M-step’s weighted sum of squares, much like the floor; Bayesian models in module 14 cover this in depth; unlike the floor, the prior drives the objective to as , as the last interactive option shows). Asymptotic theory is not lost for lack of a global maximum: with probability tending to 1, the likelihood equation has a consistent, asymptotically efficient root that is a local maximum (the classic review is Redner and Walker, 1984). That root is what you seek with EM, not the supremum.
Non-identifiability: permuting labels
Permuting components leaves the model unchanged: for any permutation of . If the pairs are distinct and weights positive, there are exactly equivalent points, and this is the entire lack of identifiability: a finite Gaussian mixture determines its components up to ordering (Teicher, 1963, in one dimension; Yakowitz and Spragins, 1968, in several). The practical consequence is label switching: runs with different seeds can return the same solution with components in a different order, so averaging parameters across runs, comparing “component 1” of two fits, or calculating bootstrap intervals makes no sense without first aligning labels (with an optimal assignment, for example the Hungarian algorithm, graphs lesson). A more serious lack of identifiability arises when is greater than the true number of components: an extra component can then have zero weight (and arbitrary mean and covariance), or two components can split a true component in infinitely many ways; the maximum is not a point and the Fisher information matrix is singular. This breaks the usual asymptotic approximations and explains why selecting is delicate.
Local optima, initialization and slow convergence
is not concave (permuting gives another maximum and the average of the two, which merges components, usually has a lower value), and EM only guarantees that does not decrease, so it ends at a stationary point depending on . The first interactive showed this: two means in one group suffice to trap EM. Standard countermeasures are k-means initialization (cheaper and better than random), multiple restarts retaining the best (n_init in scikit-learn), and always inspecting the solution’s weights and . Two cells measure this. The first compares two initializations over 20 runs on the same data.
import numpy as np, warnings
from sklearn.datasets import make_blobs
from sklearn.mixture import GaussianMixture
warnings.filterwarnings("ignore")
Xo, _ = make_blobs(450, centers=[[0, 0], [3.5, 0.3], [1.2, 3.6]], cluster_std=[1.0, 0.8, 1.2], random_state=2)
Xo = Xo @ np.array([[1.0, 0.6], [0.0, 0.7]])
print("óptimos locales con 20 inicializaciones (K = 3, covarianza completa):")
for init in ["random_from_data", "kmeans"]:
ajustes = [GaussianMixture(3, init_params=init, tol=1e-6, max_iter=500, random_state=s).fit(Xo) for s in range(20)]
lb = np.array([g.lower_bound_ for g in ajustes])
its = np.array([g.n_iter_ for g in ajustes])
print(f" init = {init:16s} mejor ell/n = {lb.max():.4f} alcanzan el mejor: {(lb > lb.max() - 1e-3).sum():2d} de 20 peor: {lb.min():.4f} iteraciones: mediana {np.median(its):.0f}, máximo {its.max()}")With means randomly chosen from the data, 15 of 20 runs reach the best value () and the other five remain at local maxima, the worst at , taking up to 183 iterations; with k-means initialization, all 20 reach the best in a median of 30 iterations (maximum 31). This is no guarantee: in the first interactive, 2 of 30 k-means++ seeds remain at a local maximum with , the same kind of poor solution as the “Two on the right” initialization. The second cell measures the other side: EM is slow when groups are poorly separated because it converges linearly at a rate approaching 1 when information about labels is weak (Redner and Walker, 1984).
print("iteraciones de EM hasta tol = 1e-6 frente a la separación s de dos nubes N(0, I) y N((s, 0), I) con 200 puntos cada una:")
r = np.random.default_rng(0)
A, B = r.normal(size=(200, 2)), r.normal(size=(200, 2))
for s in [1, 2, 3, 4, 6]:
g = GaussianMixture(2, tol=1e-6, max_iter=2000, random_state=0).fit(np.vstack([A, B + [s, 0]]))
print(f" s = {s}: {g.n_iter_:4d} iteraciones")With EM needs 3 iterations and with nine; with and , 275 and 372. The jump between and (275 versus 8) fits a classic fact: a 50/50 mixture of two Gaussians with the same variance is unimodal if and only if the distance between means is at most . With the data do not even have two modes, and EM moves across an almost flat likelihood plateau. Practical lesson: a huge iteration count is a symptom of overlapping groups or excessive , not just an overly demanding stopping criterion.
Covariance types
A full covariance per component costs parameters, a luxury with little data or high . Four common restrictions trade flexibility for parameters; in scikit-learn choose them with covariance_type.
| Type | Ellipses | Covariance parameters | M-step | |
|---|---|---|---|---|
full | free and positive definite | any | (weighted covariance) | |
tied | one shared | all identical (same shape and rotation) | ||
diag | axes parallel to coordinate axes | |||
spherical | circles |
Here is the weighted covariance of the full M-step. The three restricted-row formulas follow from the same step: after substituting , the term in is , maximized within each family. With a shared matrix, the sum of the terms is , maximized at the weighted mean of the . With , the term is , whose derivative with respect to vanishes at . With a diagonal matrix, the problem separates by coordinates and each is the diagonal element of .
The counts grow much faster than intuition suggests, and you can check them against scikit-learn’s BIC, which depends only on and the number of parameters.
import numpy as np, warnings
from sklearn.mixture import GaussianMixture
warnings.filterwarnings("ignore")
def n_params(K, d, tipo):
cov = {"full": K * d * (d + 1) // 2, "tied": d * (d + 1) // 2, "diag": K * d, "spherical": K}[tipo]
return (K - 1) + K * d + cov
print("parámetros libres (pesos + medias + covarianzas):")
print(f"{'d, K':>8s} " + " ".join(f"{t:>10s}" for t in ["full", "tied", "diag", "spherical"]))
for d, K in [(2, 3), (10, 5), (64, 10)]:
print(f"{d:>4d},{K:>3d} " + " ".join(f"{n_params(K, d, t):10d}" for t in ["full", "tied", "diag", "spherical"]))
# comprobamos la fórmula contra el BIC de scikit-learn: BIC = -2 ell + p ln n
Xr = np.random.default_rng(0).normal(size=(400, 5)) * [3, 1, 1, 0.5, 2]
for t in ["full", "tied", "diag", "spherical"]:
g = GaussianMixture(3, covariance_type=t, random_state=0).fit(Xr)
mio = -2 * g.score(Xr) * len(Xr) + n_params(3, 5, t) * np.log(len(Xr))
print(f"{t:9s} BIC sklearn = {g.bic(Xr):9.3f} con nuestra cuenta = {mio:9.3f}")With and , full covariance has 21,449 parameters, tied has 2,729, diagonal has 1,289 and spherical has 659: moving from full to diagonal divides model size by 16.6. Each restriction is a deliberate bias: diagonal and spherical are more stable and work with little data, but cannot represent correlation between variables within a group, which is precisely what tilts the ellipses. When groups have internal correlation, restricted types compensate with more components. An intermediate form, diagonal covariance plus a low-rank term, is factor analysis in lesson 12.
Model selection: how many components and which covariance
EM does not make two choices for you: the number of components and the covariance type. Comparing log-likelihood is tempting but a trap: the model with components contains (as a limit, giving the new one almost zero weight) the model with , and full covariance contains the other types, so the maximum training likelihood never decreases as the model gets more complex and with singularities is not even bounded. You must penalize complexity or measure on data the model has not seen.
AIC and BIC use different penalties: AIC aims for good prediction (up to a constant it estimates the expected KL divergence between truth and fitted model), while BIC aims to identify the true model (it comes from a Laplace approximation of marginal likelihood retaining only terms that grow with , BIC, hence the penalty). With BIC’s penalty exceeds AIC’s, so it selects smaller models. See order selection with information criteria for another use in time series.
For mixtures these criteria require care. The approximation justifying BIC requires a true parameter in the interior of a regular space with nonsingular Fisher information, and this fails when exceeds the true number (above). Keribin (2000) showed under technical assumptions that penalized likelihood criteria of this kind consistently estimate a mixture’s order, and in practice BIC is standard for choosing covariance type and jointly (Fraley and Raftery, 2002). What does not work is a likelihood-ratio test for versus with a tail: its assumptions fail, so a parametric bootstrap is used (McLachlan, 1987). One more warning: “number of components” is not “number of clusters.” A non-Gaussian group needs several components, and BIC counts components. If clusters are the goal, merge overlapping components afterward (Baudry et al., 2010).
The cell does the same with scikit-learn on another two-moons dataset (240 training and 240 validation points, n_init=2), and is half of this lesson’s density lab.
from sklearn.datasets import make_moons
Xm, _ = make_moons(480, noise=0.1, random_state=0)
tr, va = Xm[:240], Xm[240:]
tipos = ["full", "tied", "diag", "spherical"]
Ks = range(1, 9)
bic = {t: [] for t in tipos}; val = {t: [] for t in tipos}; trn = {t: [] for t in tipos}
for t in tipos:
for K in Ks:
g = GaussianMixture(K, covariance_type=t, n_init=2, random_state=0).fit(tr)
bic[t].append(g.bic(tr)); val[t].append(g.score(va)); trn[t].append(g.score(tr))
print("K " + " ".join(f"{K:7d}" for K in Ks))
for t in tipos:
print(f"BIC {t:10s} " + " ".join(f"{v:7.1f}" for v in bic[t]))
print("ell/n entren. full" + " ".join(f"{v:7.3f}" for v in trn["full"]))
for t in tipos:
print(f"ell/n valid. {t[:4]} " + " ".join(f"{v:7.3f}" for v in val[t]))
for t in tipos:
print(f"{t:10s} mejor K por BIC: {1 + int(np.argmin(bic[t]))} (BIC {min(bic[t]):.1f}); por validación: {1 + int(np.argmax(val[t]))} ({max(val[t]):.3f})")The numbers tell the same story as the interactive. With full covariance, training log-likelihood per point rises steadily from () to (), while validation rises until () and falls at (): overfitting. Full covariance BIC is minimized at (671.5). Across types, diagonal with reaches 744.8, better than full with (762.4) or (805.5), but worse than full with or (693.2 and 671.5): with enough components, a restricted type can beat a more flexible one with few components, but not enough. For tied, diagonal and spherical the BIC-best is 8, the edge of the tested range: a sign that higher values must be tried before trusting the choice.
k-means as the zero-variance limit
At the start of the lesson k-means appeared as the “poor” model; now you can state exactly what it lacks. It is the limit of a GMM with the most restricted possible components.
Proof
The factors and are equal for all components and cancel in the responsibilities: . Thus with . If , the exponent tends to , so with the stated bound; since , . With responsibilities in (the nearest center), the M-step sets to the mean of points in its Voronoi cell, the update of Lloyd’s algorithm, and , which does not affect limiting assignments: versus . Since the M-step is continuous in responsibilities, a finite number of EM iterations converges to Lloyd’s.
∎Two conditions are essential. First, must be shared: with distinct , the dominant score is , so in the limit each point goes to the component minimizing , a component-rescaled distance whose boundaries are circles, not Voronoi bisectors: there is no Lloyd limit. Second, the no-ties assumption: points nearly equidistant from two centers have split responsibilities until is small relative to distance from the boundary. This is classification EM (CEM, Celeux and Govaert, 1992) in its simplest form: assign each point to its most likely component and maximize complete-data likelihood. This explains k-means’ biases: it favors round groups of similar spread because it is a GMM with covariance frozen to a common .
from sklearn.datasets import make_blobs
Xk, _ = make_blobs(150, centers=3, cluster_std=1.0, random_state=11)
C0 = kmeanspp(Xk, 3, np.random.default_rng(4))
def lloyd_paso(X, C):
z = ((X[:, None] - C[None]) ** 2).sum(2).argmin(1)
return np.array([X[z == k].mean(0) if (z == k).any() else C[k] for k in range(len(C))])
def em_paso(X, C, pis, s2):
lp = np.log(pis) - ((X[:, None] - C[None]) ** 2).sum(2) / (2 * s2) # la constante -d/2 log(2 pi s2) se cancela
r = np.exp(lp - logsumexp(lp, axis=1, keepdims=True))
nk = r.sum(0)
return (r.T @ X) / nk[:, None], nk / len(X), r
print(" sigma^2 dist. máxima de medias EM-Lloyd tras 4 pasos máx |r - dura| densidades en espacio lineal = 0")
for s2 in [4.0, 1.0, 0.25, 0.04, 1e-3, 1e-5]:
Ce, pe, Cl = C0.copy(), np.full(3, 1 / 3), C0.copy()
for _ in range(4):
Ce, pe, r = em_paso(Xk, Ce, pe, s2)
Cl = lloyd_paso(Xk, Cl)
dura = np.eye(3)[r.argmax(1)]
nulas = (np.exp(-((Xk[:, None] - Ce[None]) ** 2).sum(2) / (2 * s2)) == 0).all(1).mean()
print(f"{s2:10.3g} {np.abs(Ce - Cl).max():26.2e} {np.abs(r - dura).max():22.2e} {nulas:10.0%} de los puntos")The result matches the theorem: separation between EM and Lloyd means after four steps falls from 0.376 with to 0.0077 with , to with and to zero (below machine precision) from onward; the maximum distance of responsibilities from a hard assignment falls in parallel, from 0.381 to . The last column repeats the implementation lesson: with , 46% of points have all linear-space densities exactly 0, and with , 99%. The entire limit is impossible to study without log-sum-exp.
The mixture as a density estimator and classifier
A fitted GMM is a density model with three immediate uses. First, density estimation, with validation likelihood as criterion: this is the same framework as KDE bandwidth selection, and the comparison is natural because KDE is a mixture with and all parameters fixed to the data. Second, generate new data (ancestral sampling) and as a byproduct detect anomalies: very low-density points are suspicious (lesson 19). Third, classify: if instead of one density you fit a GMM per class, , and combine it with class frequencies, Bayes’ theorem gives the generative classifier . With per class and full covariance this is QDA; with and covariance shared by all classes, LDA (careful: this is not scikit-learn’s tied, which ties components within each mixture, not across classes; with per class, tied and full coincide); with and diagonal covariance, Gaussian naive Bayes. With it interpolates toward multimodal class densities.
from sklearn.neighbors import KernelDensity
from sklearn.model_selection import GridSearchCV
from scipy.spatial import cKDTree
g6 = GaussianMixture(6, covariance_type="full", n_init=2, random_state=0).fit(tr)
g8 = GaussianMixture(8, covariance_type="diag", n_init=2, random_state=0).fit(tr)
kde = GridSearchCV(KernelDensity(), {"bandwidth": np.logspace(-1.5, 0, 12)}, cv=5).fit(tr).best_estimator_
print(f"ell/n en validación: GMM full K=6 {g6.score(va):.3f} GMM diag K=8 {g8.score(va):.3f} KDE (h = {kde.bandwidth:.3f}, por validación cruzada) {kde.score(va) / len(va):.3f}")
print(f"parámetros: GMM full K=6 = {n_params(6, 2, 'full')}; la KDE guarda los {len(tr)} puntos")
nuevos, _ = g6.sample(240)
d_nuevos = cKDTree(tr).query(nuevos)[0]; d_valid = cKDTree(tr).query(va)[0]
print(f"distancia mediana al dato de entrenamiento más cercano: puntos generados {np.median(d_nuevos):.3f}, puntos de validación reales {np.median(d_valid):.3f}")
print("fracción de puntos generados con densidad GMM por debajo del percentil 1 de los datos reales:",
round(float((g6.score_samples(nuevos) < np.percentile(g6.score_samples(tr), 1)).mean()), 3))On the two moons, the full mixture with achieves per validation point, and KDE with cross-validated bandwidth () achieves : slightly better, but with 240 stored points versus 35 parameters; the diagonal mixture with , , does worse. KDE’s narrow win is no surprise: with it is in its most favorable case, and its cost and error grow with dimension (KDE bias and variance), while the mixture pays for parameters, not stored data. Mixture-generated points have median distance 0.048 to the nearest training observation, versus 0.046 for real validation points: indistinguishable by this measure, and only 1.7% fall in the lowest-density 1% tail of the data.
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA
D = load_digits()
Z = PCA(10, random_state=0).fit_transform(D.data); yd = D.target
perm = np.random.default_rng(0).permutation(len(Z))
Zt, yt, Zv, yv = Z[perm[:1000]], yd[perm[:1000]], Z[perm[1000:]], yd[perm[1000:]]
def clasificador(K, tipo):
gms = [GaussianMixture(K, covariance_type=tipo, reg_covar=1e-3, random_state=0).fit(Zt[yt == c]) for c in range(10)]
log_prior = np.log(np.bincount(yt) / len(yt))
S = np.column_stack([g.score_samples(Zv) + lp for g, lp in zip(gms, log_prior)]) # log p(x | c) + log p(c)
return (S.argmax(1) == yv).mean()
print("dígitos (10 componentes principales, 1000 entrenamiento y", len(Zv), "validación): exactitud del clasificador generativo")
for K, tipo, nota in [(1, "diag", "Bayes ingenuo gaussiano"), (1, "full", "QDA"), (2, "full", ""), (3, "diag", ""), (5, "diag", "")]:
print(f" K = {K} por clase, covarianza {tipo:4s}: {clasificador(K, tipo):.4f} {nota}")On digits reduced to 10 principal components, Gaussian naive Bayes correctly classifies 89.5% of 797 validation examples; QDA, which adds correlations, 96.9%. Two full components per class give 97.1%, a difference of two examples that is not significant. Diagonal mixtures with and recover part of the gap to QDA (94.4% and 95.6%) with more components and fewer parameters per component, but do not reach it. This is the previous section’s lesson in classification form: correlation matters and can be bought with full covariance or many diagonal components.
Common mistakes
Exercises
Step 1 of 4. How is structured, and what does this allow?
Step 1 of 4. How is written when for all components?
e_step(X, pis, mus, chols): X has shape (n, d), pis has K weights, mus is a list of K means and chols is a list of K lower Cholesky factors with . Return (log_resp, ll): log-responsibilities (n, K) and total log-likelihood . Avoid overflow and NaN in high dimensions, and do not invert any matrix.import numpy as np
from scipy.linalg import solve_triangular
from scipy.special import logsumexp
def e_step(X, pis, mus, chols):
"""Devuelve (log_resp de forma (n, K), log-verosimilitud total)."""
X = np.asarray(X, dtype=float)
n, d = X.shape
K = len(pis)
# tu código: log de pi_k N(x_i | mu_k, L_k L_k^T) con solve_triangular, y normaliza con logsumexp
return np.zeros((n, K)), 0.0Summary
- Model: , , ; free parameters are covariance parameters (full: ; tied: ; diagonal: ; spherical: ).
- Responsibilities: ; with equal covariances the posterior is a sigmoid (logistic regression); with distinct covariances the boundary is a quadric with two crossings in 1D.
- Stationarity: , yielding , and ; EM iterates these equations and cannot decrease (lesson 9).
- Implementation: log-sum-exp and Cholesky; in , linear-space densities are 0 and responsibilities
nan. With the same initial conditions the from-scratch implementation matches scikit-learn to . - Pathologies: is unbounded (collapse onto a point, with rising for each decade the variance falls); a variance floor (
reg_covar) bounds it and a covariance prior also eliminates the boundary supremum, both at the cost of choosing a scale. The solution is unique up to permutations; local optima and slow convergence under overlap require k-means initialization and multiple restarts. - Selection: training likelihood is unsuitable; BIC () and AIC () penalize, and validation likelihood measures directly. Components are not clusters: two moons need six.
- k-means is the limit of EM with shared , with exponential tail ; the mixture is also a density estimator (KDE is a mixture with ), a generator, and, with one mixture per class, a generative classifier generalizing LDA and QDA.