Module contents
Lesson 8 of 24Core 105 min

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

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 p(x)p(\vb{x}): 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.

[ ]k-means versus a Gaussian mixture on elliptical groupsBrowser
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.

InteractiveEM in action
Data, means and Mahalanobis ellipses (radii 1 and 2) of the three components
start, θ0
Mean log-likelihood per point: never decreases (28 iterations to tolerance 10−710^{-7})
best of 30 seeds
  • component 1
  • component 2
  • component 3
  • point with shared responsibility: mixed color
  • best known value
Initialization
Iteration0 of 28
Stepinitial parameters
ℓ(θt)/n\ell(\theta_t)/n−7.3888
Best of 30 k-means seeds−3.3514
k-means seeds reaching it28 of 30
Weights πk\pi_k0.33 · 0.33 · 0.33
Points with max⁡krik<0.9\max_k r_{ik} < 0.9n/a
There are only initial parameters: three equally round ellipses. Advance. The E-step colors each point by its responsibilities; the M-step moves the ellipses.
Three full-covariance components fitted to 180 points from an explicit mixture of three ellipses (fixed seed). Each point is colored by a mixture of component colors weighted by responsibilities; ellipses are Mahalanobis contours of radius 1 (dashed) and 2. With 'All in center', EM converges in 28 iterations to ℓ/n=−3.3514\ell/n = -3.3514, the best value found (28 of 30 k-means seeds reach it), and the plot below never decreases: the monotonicity guarantee proved next lesson. With 'Two on right', initialization puts two means in the right group: EM stops at a local maximum with ℓ/n≈−3.75\ell/n \approx -3.75, one broad component covering both left groups and the other two splitting the right one. Drag initial means at step 0 and seek other stuck initializations.

Review: the multivariate Gaussian

A Gaussian mixture is made of Gaussian pieces, so keep their geometry fresh. The density of N(μ,Σ)\Normal(\vb{\mu}, \mat{\Sigma}) in Rd\R^d, with symmetric positive-definite Σ\mat{\Sigma} (definition), is

N(x;μ,Σ)=(2π)−d/2 det⁡(Σ)−1/2exp⁡ ⁣(−12 Δ2),Δ2=(x−μ)⊤Σ−1(x−μ).\Normal(\vb{x}; \vb{\mu}, \mat{\Sigma}) = (2\pi)^{-d/2}\,\det(\mat{\Sigma})^{-1/2}\exp\!\Big(-\tfrac12\,\Delta^2\Big), \qquad \Delta^2 = (\vb{x} - \vb{\mu})\T\mat{\Sigma}\inv(\vb{x} - \vb{\mu}).

Quantity Δ\Delta is Mahalanobis distance to the mean. By the spectral theorem, Σ=UΛU⊤\mat{\Sigma} = \mat{U}\mat{\Lambda}\mat{U}\T, and points at Mahalanobis distance rr form an ellipsoid with semiaxes rλjr\sqrt{\lambda_j} along eigenvector directions uj\vb{u}_j. Thus covariance is cloud shape: eigenvectors give orientation and eigenvalues each axis’s length. In the plane, Δ2\Delta^2 follows χ22\chi^2_2 when x∼N(μ,Σ)\vb{x} \sim \Normal(\vb{\mu}, \mat{\Sigma}), so a radius-rr ellipsoid contains probability 1−e−r2/21 - e^{-r^2/2}: 39.3% at r=1r = 1 and 86.5% at r=2r = 2, the interactive contours.

Two useful facts: the density’s log⁡\log is quadratic in x\vb{x}, and stable evaluation does not require inverting Σ\mat{\Sigma} (Cholesky factorization, linear algebra lesson, suffices; below).

The model: a randomly chosen Gaussian

It is a generative model, so use ancestral sampling: draw zz with probabilities π\vb{\pi} and then x\vb{x} from the selected Gaussian (with Σk=LkLk⊤\mat{\Sigma}_k = \mat{L}_k\mat{L}_k\T, x=μk+Lkε\vb{x} = \vb{\mu}_k + \mat{L}_k\vb{\varepsilon} with ε∼N(0,I)\vb{\varepsilon} \sim \Normal(\vb{0}, \mat{I}), 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 KK it can approximate arbitrary densities: lesson 4’s kernel estimation is exactly a mixture with K=nK = n components of weight 1/n1/n, means at data points and covariances h2Ih^2\mat{I}, converging to any density in L1L^1 as h→0h \to 0 and nhd→∞nh^d \to \infty (Devroye and Györfi, 1985). A mixture with K≪nK \ll n compresses that idea: a few fitted components instead of one per datum.

Count free parameters: K−1K - 1 weights, KdKd means and K d(d+1)/2K\,d(d+1)/2 symmetric covariance entries. With d=64d = 64 and K=10K = 10 that is 21449; quadratic growth in dd 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 sks_k have clear interpretations: weight πk\pi_k favors large components; −12log⁡det⁡Σk-\tfrac12\log\det\mat{\Sigma}_k 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 Σ=I\mat{\Sigma} = \mat{I} for all. Hard assignment z^=arg max⁡krik\hat z = \argmax_k r_{ik} 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 log⁡r1−log⁡r2=s1−s2\log r_1 - \log r_2 = s_1 - s_2, subtract scores and expand Δk2=x⊤Σk−1x−2μk⊤Σk−1x+μk⊤Σk−1μk\Delta_k^2 = \vb{x}\T\mat{\Sigma}_k\inv\vb{x} - 2\vb{\mu}_k\T\mat{\Sigma}_k\inv\vb{x} + \vb{\mu}_k\T\mat{\Sigma}_k\inv\vb{\mu}_k (symmetry of Σk−1\mat{\Sigma}_k\inv gives factor 2). With Σ1=Σ2\mat{\Sigma}_1 = \mat{\Sigma}_2 quadratic and volume terms cancel, leaving affine function w⊤x+b\vb{w}\T\vb{x} + b; since r1=eL/(1+eL)r_1 = e^{L}/(1 + e^{L}) with LL the log-likelihood ratio, r1=σ(L)r_1 = \sigmoid(L). For bb: −12μ1⊤Σ−1μ1+12μ2⊤Σ−1μ2=−12(μ1−μ2)⊤Σ−1(μ1+μ2)-\tfrac12\vb{\mu}_1\T\mat{\Sigma}\inv\vb{\mu}_1 + \tfrac12\vb{\mu}_2\T\mat{\Sigma}\inv\vb{\mu}_2 = -\tfrac12(\vb{\mu}_1 - \vb{\mu}_2)\T\mat{\Sigma}\inv(\vb{\mu}_1 + \vb{\mu}_2).

∎

This is familiar from LDA and QDA: a mixture posterior with shared covariance is logistic regression, whose form linear discriminant analysis shares (and with K>2K > 2 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.

InteractiveThe shape of the posterior
Weighted densities πk N(x;μk,σk2)\pi_k\,\mathcal N(x;\mu_k,\sigma_k^2) and their sum
Responsibility r1(x)=p(z=1∣x)r_1(x) = p(z = 1 \mid x) (curve; blue area below) and r2=1−r1r_2 = 1 - r_1 (orange area)
r₁(1.00) = 0.818
  • component 1
  • component 2
  • mixture
  • intersections r1=1/2r_1 = 1/2
  • test point
Variances
0.0
3.0
1.00
0.50
1.00
log⁡r1(x)r2(x)=0 x2−3.00 x+4.50\log\frac{r_1(x)}{r_2(x)} = 0\,x^2 - 3.00\,x + 4.50
Razón de log-verosimilitudes: cuadrática en xx
r1(1.00)r_1(1.00)0.818
r2(1.00)r_2(1.00)0.182
Intersections of r1=1/2r_1 = 1/21.50
With equal variances the quadratic term cancels (a=0a = 0) and L(x)L(x) is linear: r1r_1 is a sigmoid, exactly the logistic-regression form, with one intersection at x=1.50x = 1.50. Move π1\pi_1: it only shifts the sigmoid.
Explicit mixture of two 1D Gaussians, no data: the interactive calculates r1(x)r_1(x) from the theorem. Initially (μ=0\mu = 0 and 33, σ=1\sigma = 1, equal weights), log-likelihood ratio is −3x+4.5-3x + 4.5, a line, and r1(1)=0.818r_1(1) = 0.818 (the lesson's numeric exercise): a sigmoid with one crossing at x=1.5x = 1.5. Move π1\pi_1: it only shifts the sigmoid. Switch to 'Different': the second standard deviation becomes 2.2 and the parabola crosses zero twice (x=−3.00x = -3.00 and x=1.44x = 1.44 for these parameters), so r1r_1 rises, falls again and returns to 0 in both tails where the wide component wins. With equal weights both crossings never disappear, however close the means (the narrow one always wins near its mean); lower π1\pi_1 to 0.1 and they disappear: the wide component wins everywhere.
[ ]Responsibilities and decision boundary in 1DBrowser
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: r1(1)=0.8176r_1(1) = 0.8176, the sigmoid reproduces the posterior with an error of 10−1510^{-15} (rounding), and with σ=(0.7,2)\sigma = (0.7, 2) there are two crossings (at x≈−2.04x \approx -2.04 and x≈1.19x \approx 1.19) and r1≈0r_1 \approx 0 at both extremes.

The log-likelihood and why there is no closed-form solution

For independent observations x1,…,xn\vb{x}_1, \dots, \vb{x}_n (ordinary maximum likelihood), the objective function is

ℓ(θ)=∑i=1nlog⁡∑k=1Kπk N(xi;μk,Σk).\ell(\theta) = \sum_{i=1}^n \log \sum_{k=1}^K \pi_k\,\Normal(\vb{x}_i; \vb{\mu}_k, \mat{\Sigma}_k).

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 θk\theta_k of component kk is

∂ℓ∂θk=∑i=1nπk ∂θkN(xi;θk)∑jπj N(xi;θj)=∑i=1nrik ∂∂θklog⁡(πk N(xi;θk)),\pd{\ell}{\theta_k} = \sum_{i=1}^n \frac{\pi_k\,\partial_{\theta_k}\Normal(\vb{x}_i; \theta_k)}{\sum_j \pi_j\,\Normal(\vb{x}_i; \theta_j)} = \sum_{i=1}^n r_{ik}\,\pd{}{\theta_k}\log\big(\pi_k\,\Normal(\vb{x}_i; \theta_k)\big),

because ∂θN=N ∂θlog⁡N\partial_\theta \Normal = \Normal\,\partial_\theta\log\Normal. This is the score (the gradient of the log-likelihood) of an ordinary Gaussian, but each observation has weight rikr_{ik}, which itself depends on θ\theta. The next cell checks the identity for the means, ∂ℓ/∂μk=∑irikΣk−1(xi−μk)\partial\ell/\partial\vb{\mu}_k = \sum_i r_{ik}\mat{\Sigma}_k\inv(\vb{x}_i - \vb{\mu}_k), against finite differences.

[ ]The gradient is the responsibility-weighted scoreBrowser
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, 1.3⋅10−81.3 \cdot 10^{-8}, is finite-difference error). Setting the gradient to zero is therefore the maximum-likelihood problem for KK 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 μk\vb{\mu}_k and Σk\mat{\Sigma}_k are those of a Gaussian with weighted data. For μk\vb{\mu}_k: ∑irikΣk−1(xi−μk)=0\sum_i r_{ik}\mat{\Sigma}_k\inv(\vb{x}_i - \vb{\mu}_k) = \vb{0}; since Σk\mat{\Sigma}_k is invertible, ∑irik(xi−μk)=0\sum_i r_{ik}(\vb{x}_i - \vb{\mu}_k) = \vb{0}, giving the weighted mean. For Σk\mat{\Sigma}_k: log⁡N=−12log⁡det⁡Σ−12(x−μ)⊤Σ−1(x−μ)+cte\log\Normal = -\tfrac12\log\det\mat{\Sigma} - \tfrac12(\vb{x} - \vb{\mu})\T\mat{\Sigma}\inv(\vb{x} - \vb{\mu}) + \text{cte} has gradient with respect to Σ\mat{\Sigma} equal to −12Σ−1+12Σ−1(x−μ)(x−μ)⊤Σ−1-\tfrac12\mat{\Sigma}\inv + \tfrac12\mat{\Sigma}\inv(\vb{x} - \vb{\mu})(\vb{x} - \vb{\mu})\T\mat{\Sigma}\inv (using ∂log⁡det⁡Σ=Σ−1\partial\log\det\mat{\Sigma} = \mat{\Sigma}\inv and ∂ tr⁡(Σ−1S)=−Σ−1SΣ−1\partial\,\tr(\mat{\Sigma}\inv\mat{S}) = -\mat{\Sigma}\inv\mat{S}\mat{\Sigma}\inv, with Σ\mat{\Sigma} and S\mat{S} symmetric, as matrix gradients); summing with weights rikr_{ik} and setting to zero gives NkΣk−1=Σk−1[∑irik(xi−μk)(xi−μk)⊤]Σk−1N_k\mat{\Sigma}_k\inv = \mat{\Sigma}_k\inv\big[\sum_i r_{ik}(\vb{x}_i - \vb{\mu}_k)(\vb{x}_i - \vb{\mu}_k)\T\big]\mat{\Sigma}_k\inv, and multiplying by Σk\mat{\Sigma}_k on both sides yields the result. For the weights, the Lagrangian ℓ+λ(∑kπk−1)\ell + \lambda(\sum_k\pi_k - 1) gives, by the gradient identity with ∂πklog⁡(πk Nk)=1/πk\partial_{\pi_k}\log(\pi_k\,\Normal_k) = 1/\pi_k, the equation ∑irik/πk+λ=0\sum_i r_{ik}/\pi_k + \lambda = 0, that is, Nk=−λπkN_k = -\lambda\pi_k. Summing over kk and using ∑kNk=∑i∑krik=n\sum_k N_k = \sum_i\sum_k r_{ik} = n gives λ=−n\lambda = -n and πk=Nk/n\pi_k = N_k/n. (Lagrange multipliers.)

∎

Notice that the equations do not solve anything: the right-hand side depends on θ^\hat\theta through the rikr_{ik}. They form a fixed-point equation, θ=F(θ)\theta = F(\theta), 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 ziz_i, with rik=1[zi=k]r_{ik} = \ind[z_i = k], 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 ℓ\ell touching ℓ\ell at θ(t)\theta^{(t)} and that the M-step maximizes that bound, yielding ℓ(θ(t+1))≥ℓ(θ(t))\ell(\theta^{(t+1)}) \ge \ell(\theta^{(t)}) (monotonicity and convergence). Here you can see the result: the first interactive’s ℓ\ell 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 KK covariance matrices, the cost is O(Kd3+nKd2)\bigO(Kd^3 + nKd^2) in time and O(nK+Kd2)\bigO(nK + Kd^2) 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 N(x;… )\Normal(\vb{x}; \dots) are e−500e^{-500} or less and the ratio in the definition is 0/00/0. Calculate each component’s score log⁡πk+log⁡Nk\log\pi_k + \log\Normal_k and normalize with log⁡∑keak=m+log⁡∑keak−m\log\sum_k e^{a_k} = m + \log\sum_k e^{a_k - m}, where m=max⁡kakm = \max_k a_k (the log-sum-exp trick), which also gives ℓ\ell without leaving log-space.
  • Cholesky instead of inversion. With Σ=LL⊤\mat{\Sigma} = \mat{L}\mat{L}\T, obtain Δ2=∥L−1(x−μ)∥2\Delta^2 = \norm{\mat{L}\inv(\vb{x} - \vb{\mu})}^2 by solving a triangular system, and log⁡det⁡Σ=2∑jlog⁡Ljj\log\det\mat{\Sigma} = 2\sum_j\log L_{jj}. 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 λI\lambda\mat{I} (in scikit-learn, reg_covar, default 10−610^{-6}) 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.

[ ]EM for a Gaussian mixture from scratch in log-spaceBrowser
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 (−3.4058449705-3.4058449705 to the ten printed decimal places), and their means, weights and covariances match to machine precision (differences of order 10−1610^{-16}). That is no magic: it is the same algorithm. The second half of the cell shows why log-space is necessary: in d=600d = 600 the log-densities range from −843-843 to −905-905, and since the smallest positive number representable by a float64 is 4.9⋅10−324≈e−744.44.9 \cdot 10^{-324} \approx e^{-744.4} (and e−746e^{-746} already rounds to 0), all three densities are exactly 0.00.0 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 x1\vb{x}_1, the density is at least component 1’s contribution: p(x1)≥π1N(x1;x1,εI)=π1(2πε)−d/2p(\vb{x}_1) \ge \pi_1\Normal(\vb{x}_1; \vb{x}_1, \varepsilon\mat{I}) = \pi_1(2\pi\varepsilon)^{-d/2}. At each xi\vb{x}_i with i≥2i \ge 2, p(xi)≥∑k≥2πkN(xi;μk,Σk)=:qi>0p(\vb{x}_i) \ge \sum_{k \ge 2}\pi_k\Normal(\vb{x}_i; \vb{\mu}_k, \mat{\Sigma}_k) =: q_i > 0, which does not depend on ε\varepsilon. Hence

ℓ(θε)≥log⁡π1−d2log⁡(2πε)+∑i≥2log⁡qi⟶+∞(ε→0).\ell(\theta_\varepsilon) \ge \log\pi_1 - \tfrac d2\log(2\pi\varepsilon) + \sum_{i \ge 2}\log q_i \longrightarrow +\infty \quad (\varepsilon \to 0).∎

Consequences: the supremum of ℓ\ell is +∞+\infty, 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 dd points in Rd\R^d). With one covariance shared by all components, this pathology disappears if enough observations are in general position: a single Σ\mat{\Sigma} 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 ≥δ/2\ge \delta/2 from every mean (δ\delta is the smallest separation between observations), and its density, of order σ−1e−δ2/(8σ2)\sigma^{-1}e^{-\delta^2/(8\sigma^2)}, pulls ℓ\ell to −∞-\infty as σ→0\sigma \to 0. The interactive uses an explicit model: one component centered on an observation, with standard deviation σA\sigma_A under your control, and another fixed component explaining the rest.

InteractiveA collapsing component
Mixture density: component A (red) on the captured data point and B (blue) on the rest
height 6.0 (clipped)
Mixture log-likelihood versus σA\sigma_A (log scale: component narrows toward the left)
single Gaussian
  • without variance floor
  • with chosen remedy (floor λ or prior)
  • mixture
  • single Gaussian
7 of 14
0.0100
0.15
Remedy: variance floor λ\lambda (reg_covar) or prior on σA2\sigma_A^2
ℓ\ell without floor (λ=0\lambda = 0)−25.14
ℓ\ell of a single Gaussian−26.41
Peak height at xjx_j6.0
Without a remedy, each tenfold reduction of σ_A raises log-likelihood by 2.28 (approaching log 10 = 2.30 for small σ_A). There is no maximum: the mixture fits one point with a peak of height 6.0.
Fourteen 1D observations from an explicit mixture (fixed seed). Component A (red, weight πA=0.15\pi_A = 0.15) is centered on your chosen observation, with standard deviation σA\sigma_A; B is the maximum-likelihood Gaussian for the other 13 observations. With λ=0\lambda = 0 (no variance floor), the red curve below grows without bound as the component narrows: each decade of σA\sigma_A adds log⁡10=2.30\log 10 = 2.30 (from −25.14-25.14 at σA=0.01\sigma_A = 0.01 to −22.86-22.86 at 0.0010.001 and −20.56-20.56 at 0.00010.0001), far above a single Gaussian (−26.41-26.41). Enable a floor λ\lambda (added to the variance, like reg_covar): the blue curve flattens at −22.87-22.87 with 10−610^{-6}, at −25.14-25.14 with 10−410^{-4} and at −26.26-26.26 with 10−210^{-2}. The floor bounds ℓ\ell, but the best value still occurs as σA→0\sigma_A \to 0, with the component stuck to one observation. Next select the inverse-gamma prior on σA2\sigma_A^2 (shape 1, scale 0.02, mode 0.01): the term −0.02/σA2-0.02/\sigma_A^2 drives the objective down as the component narrows and the maximum becomes an interior point, ℓ+log⁡p=−22.97\ell + \log p = -22.97 at σA≈0.09\sigma_A \approx 0.09. 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 x7=−1.028x_7 = -1.028.

[ ]EM with a collapsing component, with and without a variance floorBrowser
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, ℓ=−20.61\ell = -20.61, with the component covering 4.14 effective points. With a narrow start (variance 10−310^{-3}) and no floor, collapse occurs: A’s variance drops from 10−310^{-3} to 9.35⋅10−109.35 \cdot 10^{-10} in one iteration and to 6⋅10−306 \cdot 10^{-30} in three, and ℓ\ell jumps to +5.75+5.75, 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 e−δ2/(2σ2)e^{-\delta^2/(2\sigma^2)} with δ\delta the distance to the nearest observation: σt+12≈e−c/σt2\sigma^2_{t+1} \approx e^{-c/\sigma^2_t} (here δ≈0.2\delta \approx 0.2 and σ2=10−3\sigma^2 = 10^{-3} give e−20≈2⋅10−9e^{-20} \approx 2 \cdot 10^{-9}, the order of the variance after one iteration, and at the next e−0.04/(2⋅10−9)e^{-0.04/(2 \cdot 10^{-9})} is already 0 in float64). Variance stays at 6⋅10−306 \cdot 10^{-30}, the rounding error of the weighted mean, and ℓ\ell stops rising only because float64 precision runs out. With reg_covar =10−6= 10^{-6} the variance stays pinned to the 10−610^{-6} floor and ℓ=−20.47\ell = -20.47, greater than the reasonable solution’s: the floor bounds ℓ\ell but does not eliminate the attractor, and that solution is still spurious (0.99 effective points). With 10−210^{-2} it disappears (A ends with 0.26 effective points and ℓ=−24.16\ell = -24.16), but at the cost of destroying the component.

There are two kinds of safeguards. Numerical: a variance floor reg_covar, which guarantees Σk⪰λI\mat{\Sigma}_k \succeq \lambda\mat{I} and therefore ℓ≤−nd2log⁡(2πλ)\ell \le -\tfrac{nd}{2}\log(2\pi\lambda); and discarding or restarting components whose effective count NkN_k falls below a few points (collapse is signaled by Nk≈1N_k \approx 1 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 Ψ=λI\mat{\Psi} = \lambda\mat{I}, MAP adds Ψ\mat{\Psi} 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 −∞-\infty as Σk→0\mat{\Sigma}_k \to \mat{0}, 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: ℓ(θ)=ℓ(θ∘σ)\ell(\theta) = \ell(\theta\circ\sigma) for any permutation σ\sigma of {1,…,K}\{1, \dots, K\}. If the pairs (μk,Σk)(\vb{\mu}_k, \mat{\Sigma}_k) are distinct and weights positive, there are exactly K!K! 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 KK 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 KK is delicate.

Local optima, initialization and slow convergence

ℓ\ell 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 ℓ\ell does not decrease, so it ends at a stationary point depending on θ(0)\theta^{(0)}. 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 ℓ\ell (n_init in scikit-learn), and always inspecting the solution’s weights and NkN_k. Two cells measure this. The first compares two initializations over 20 runs on the same data.

[ ]Local optima: random versus k-means initializationBrowser
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 (ℓ/n=−3.4132\ell/n = -3.4132) and the other five remain at local maxima, the worst at −3.5614-3.5614, 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 ℓ/n=−3.7475\ell/n = -3.7475, 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).

[ ]EM iterations versus separation of two cloudsBrowser
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 s=6s = 6 EM needs 3 iterations and with s=4s = 4 nine; with s=2s = 2 and s=1s = 1, 275 and 372. The jump between s=2s = 2 and s=3s = 3 (275 versus 8) fits a classic fact: a 50/50 mixture of two Gaussians with the same variance σ2\sigma^2 is unimodal if and only if the distance between means is at most 2σ2\sigma. With s≤2s \le 2 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 KK, not just an overly demanding stopping criterion.

Covariance types

A full covariance per component costs O(Kd2)\bigO(Kd^2) parameters, a luxury with little data or high dd. Four common restrictions trade flexibility for parameters; in scikit-learn choose them with covariance_type.

TypeΣk\mat{\Sigma}_kEllipsesCovariance parametersM-step
fullfree and positive definiteanyK d(d+1)/2K\,d(d+1)/2Sk\mat{S}_k (weighted covariance)
tiedone shared Σ\mat{\Sigma}all identical (same shape and rotation)d(d+1)/2d(d+1)/2∑k(Nk/n)Sk\sum_k (N_k/n)\mat{S}_k
diagdiag⁡(σk12,…,σkd2)\diag(\sigma_{k1}^2, \dots, \sigma_{kd}^2)axes parallel to coordinate axesKdKddiag⁡(Sk)\diag(\mat{S}_k)
sphericalσk2I\sigma_k^2\mat{I}circlesKKtr⁡(Sk)/d\tr(\mat{S}_k)/d

Here Sk=1Nk∑irik(xi−μk)(xi−μk)⊤\mat{S}_k = \frac1{N_k}\sum_i r_{ik}(\vb{x}_i - \vb{\mu}_k)(\vb{x}_i - \vb{\mu}_k)\T is the weighted covariance of the full M-step. The three restricted-row formulas follow from the same step: after substituting μ^k\hat{\vb{\mu}}_k, the Σk\mat{\Sigma}_k term in QQ is −Nk2(log⁡det⁡Σk+tr⁡(Σk−1Sk))-\tfrac{N_k}{2}\big(\log\det\mat{\Sigma}_k + \tr(\mat{\Sigma}_k\inv\mat{S}_k)\big), maximized within each family. With a shared matrix, the sum of the KK terms is −n2(log⁡det⁡Σ+tr⁡(Σ−1∑kNknSk))-\tfrac n2\big(\log\det\mat{\Sigma} + \tr(\mat{\Sigma}\inv\sum_k\tfrac{N_k}{n}\mat{S}_k)\big), maximized at the weighted mean of the Sk\mat{S}_k. With Σk=σk2I\mat{\Sigma}_k = \sigma_k^2\mat{I}, the term is −Nk2(dlog⁡σk2+tr⁡(Sk)/σk2)-\tfrac{N_k}{2}\big(d\log\sigma_k^2 + \tr(\mat{S}_k)/\sigma_k^2\big), whose derivative with respect to σk2\sigma_k^2 vanishes at tr⁡(Sk)/d\tr(\mat{S}_k)/d. With a diagonal matrix, the problem separates by coordinates and each σkj2\sigma_{kj}^2 is the diagonal element of Sk\mat{S}_k.

The counts grow much faster than intuition suggests, and you can check them against scikit-learn’s BIC, which depends only on ℓ\ell and the number of parameters.

[ ]Parameter counts by covariance type, checked against scikit-learn BICBrowser
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 d=64d = 64 and K=10K = 10, 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 KK and the covariance type. Comparing log-likelihood is tempting but a trap: the model with K+1K + 1 components contains (as a limit, giving the new one almost zero weight) the model with KK, 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 −2log⁡-2\log marginal likelihood retaining only terms that grow with nn, BIC, hence the pln⁡np\ln n penalty). With n≥8n \ge 8 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 KK 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 KK jointly (Fraley and Raftery, 2002). What does not work is a likelihood-ratio test for KK versus K+1K + 1 with a χ2\chi^2 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).

InteractiveCovariance types and selection
Fit with full and K=3K = 3: radius-2 ellipses over 150 training points
BIC versus KK for all four types (lower is better; each ★ marks the best KK of its type)
★★★★ground-truth K
  • full
  • tied
  • diagonal
  • spherical
  • training data
  • validation data
Data
Covariance type
3
Criterion
Validation points
Free parameters17
BIC (lower is better)1034.4
AIC (lower is better)983.3
Training ℓ per point−3.164
Validation ℓ per point−3.422
Best by BICfull, K = 3
BIC selects full with K = 3. Ground truth has K = 3.
Three 2D datasets (150 training and 150 validation points each, from explicit mixtures or two moons) and, for each of the four covariance types and KK from 1 to 8, the best of four EM fits using k-means++ training seeds. With 'Rotated ellipses' (truth: 3 components with full covariances) and BIC, full with K=3K = 3 wins easily (BIC 1034, versus 1097 for the best tied fit, with K=7K = 7): restricted types try to imitate tilted ellipses with many components. With 'Four spheres', the types are similar (at K=4K = 4: tied 1218, spherical 1221, diagonal 1235, full 1253) and full pays for extra parameters. With 'Two moons', truth is not a Gaussian mixture: BIC and validation select full with K=6K = 6 (BIC 479), and diagonal with K=8K = 8 (507) beats full with K=3K = 3 (528). Change the criterion to training ℓ: curves rise with KK and their best value is always at or near K=8K = 8; it cannot select a model. Where one falls (diagonal on 'Four spheres', from K=7K = 7 to 88), EM is stuck in a worse local optimum: the maximum of the larger family can never be smaller.

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.

[ ]Selecting K and covariance type: BIC and validation likelihoodBrowser
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 −1.919-1.919 (K=1K = 1) to −0.908-0.908 (K=8K = 8), while validation rises until K=7K = 7 (−1.087-1.087) and falls at K=8K = 8 (−1.113-1.113): overfitting. Full covariance BIC is minimized at K=6K = 6 (671.5). Across types, diagonal with K=8K = 8 reaches 744.8, better than full with K=4K = 4 (762.4) or K=3K = 3 (805.5), but worse than full with K=5K = 5 or 66 (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 KK 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 (2πσ2)−d/2(2\pi\sigma^2)^{-d/2} and det⁡\det are equal for all components and cancel in the responsibilities: rj∝πjexp⁡(−∥x−μj∥2/(2σ2))r_j \propto \pi_j\exp(-\norm{\vb{x} - \vb{\mu}_j}^2/(2\sigma^2)). Thus rj/rk=(πj/πk)exp⁡ ⁣(−(Dj−Dk)/(2σ2))r_j/r_k = (\pi_j/\pi_k)\exp\!\big(-(D_j - D_k)/(2\sigma^2)\big) with Dj=∥x−μj∥2D_j = \norm{\vb{x} - \vb{\mu}_j}^2. If Dk<DjD_k < D_j, the exponent tends to −∞-\infty, so rj/rk→0r_j/r_k \to 0 with the stated bound; since ∑jrj=1\sum_j r_j = 1, rk→1r_k \to 1. With responsibilities in {0,1}\{0, 1\} (the nearest center), the M-step sets μk\vb{\mu}_k to the mean of points in its Voronoi cell, the update of Lloyd’s algorithm, and πk=Nk/n\pi_k = N_k/n, which does not affect limiting assignments: log⁡πk=O(1)\log\pi_k = \bigO(1) versus O(1/σ2)\bigO(1/\sigma^2). Since the M-step is continuous in responsibilities, a finite number of EM iterations converges to Lloyd’s.

∎

Two conditions are essential. First, σ\sigma must be shared: with distinct σk=ckσ\sigma_k = c_k\sigma, the dominant score is −∥x−μk∥2/(2ck2σ2)-\norm{\vb{x} - \vb{\mu}_k}^2/(2c_k^2\sigma^2), so in the limit each point goes to the component minimizing ∥x−μk∥2/ck2\norm{\vb{x} - \vb{\mu}_k}^2/c_k^2, 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 σ2\sigma^2 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 σ2I\sigma^2\mat{I}.

InteractiveFrom EM to Lloyd
EM with Σk=σ2I\Sigma_k = \sigma^2\mathbf I (circles of radius 2σ2\sigma at final means) and mean trajectories
Fraction of points with responsibility above 0.99 versus σ\sigma
Maximum separation between EM and Lloyd means over all iterations (log scale; below 10−410^{-4} is plotted at 10−410^{-4})
Lloyd and EM coincide
  • EM trajectories (component color)
  • Lloyd trajectory
  • point shared across components: mixed color
1.500
k-means++ seed
Points with max⁡krik>0.99\max_k r_{ik} > 0.9952.7 %
Mean responsibility entropy (nats)0.137
Maximum EM–Lloyd mean separation across all iterations2.3134
Same hard assignment as Lloyd99.3 %
Iterations: EM / Lloyd19 / 6
With σ = 1.50, 53 % of points have responsibility above 0.99; others remain split between means. EM means differ from Lloyd by up to 2.31 units and need 19 iterations versus 6.
150 points from three spherical Gaussians of standard deviation 1 (fixed seed), with three draggable initial k-means++ centroids (rings), and trajectories of EM means with fixed covariance σ2I\sigma^2 I (solid) and Lloyd means (dashed) from those same centroids. With seed 4 and σ=1.5\sigma = 1.5 (initial state), only 52.7% of points have responsibility above 0.99, EM takes 19 iterations versus Lloyd's 6, and means separate by up to 2.31 units along the way. Lower σ\sigma: at 1.0, 89.3% of points are hard and separation is 1.36; at 0.316, 99.3% and 0.05; at 0.1, 100% and 0.03. The two plots below sweep 28 values of σ\sigma. With σ=3\sigma = 3, no point has responsibility above 0.99 and EM means bear no resemblance to Lloyd's.
[ ]From EM to Lloyd: separation shrinks with σ² and linear space breaksBrowser
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 σ2=4\sigma^2 = 4 to 0.0077 with σ2=1\sigma^2 = 1, to 1.3⋅10−51.3 \cdot 10^{-5} with 0.250.25 and to zero (below machine precision) from 0.040.04 onward; the maximum distance of responsibilities from a hard assignment falls in parallel, from 0.381 to 9⋅10−249 \cdot 10^{-24}. The last column repeats the implementation lesson: with σ2=10−3\sigma^2 = 10^{-3}, 46% of points have all linear-space densities exactly 0, and with 10−510^{-5}, 99%. The entire σ→0\sigma \to 0 limit is impossible to study without log-sum-exp.

The mixture as a density estimator and classifier

A fitted GMM is a density model p^(x)=∑kπ^kN(x;μ^k,Σ^k)\hat p(\vb{x}) = \sum_k\hat\pi_k\Normal(\vb{x}; \hat{\vb{\mu}}_k, \hat{\mat{\Sigma}}_k) 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 K=nK = n 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, p^(x∣y=c)\hat p(\vb{x} \given y = c), and combine it with class frequencies, Bayes’ theorem gives the generative classifier y^=arg max⁡clog⁡p^(y=c)+log⁡p^(x∣y=c)\hat y = \argmax_c \log\hat p(y = c) + \log\hat p(\vb{x} \given y = c). With K=1K = 1 per class and full covariance this is QDA; with K=1K = 1 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 K=1K = 1 per class, tied and full coincide); with K=1K = 1 and diagonal covariance, Gaussian naive Bayes. With K>1K > 1 it interpolates toward multimodal class densities.

[ ]GMM as a density model: validation, KDE comparison and generated dataBrowser
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 K=6K = 6 achieves −1.107-1.107 per validation point, and KDE with cross-validated bandwidth (h=0.081h = 0.081) achieves −1.087-1.087: slightly better, but with 240 stored points versus 35 parameters; the diagonal mixture with K=8K = 8, −1.378-1.378, does worse. KDE’s narrow win is no surprise: with d=2d = 2 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.

[ ]Generative classifier with one mixture per class on digitsBrowser
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 K=3K = 3 and 55 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

ProofThe M-step updates
Prove: With fixed responsibilities rikr_{ik}, let Q(θ)=∑i∑krik[log⁡πk+log⁡N(xi;μk,Σk)]Q(\theta) = \sum_i\sum_k r_{ik}\big[\log\pi_k + \log\mathcal N(\mathbf x_i; \boldsymbol\mu_k, \boldsymbol\Sigma_k)\big] with ∑kπk=1\sum_k\pi_k = 1 and Nk=∑irikN_k = \sum_i r_{ik}. Assuming Nk>0N_k > 0 and the resulting weighted covariance is positive definite (otherwise the supremum is not attained), prove that its maximizers are μk=1Nk∑irikxi\boldsymbol\mu_k = \frac1{N_k}\sum_i r_{ik}\mathbf x_i, Σk=1Nk∑irik(xi−μk)(xi−μk)T\boldsymbol\Sigma_k = \frac1{N_k}\sum_i r_{ik}(\mathbf x_i - \boldsymbol\mu_k)(\mathbf x_i - \boldsymbol\mu_k)^{\mathsf T} and πk=Nk/n\pi_k = N_k/n.
0
Rewrite Q separating terms depending on each parameter. For Σk\boldsymbol\Sigma_k, use ∂log⁡det⁡Σ=Σ−1\partial\log\det\boldsymbol\Sigma = \boldsymbol\Sigma^{-1} and ∂ tr(Σ−1S)=−Σ−1SΣ−1\partial\,\mathrm{tr}(\boldsymbol\Sigma^{-1}\mathbf S) = -\boldsymbol\Sigma^{-1}\mathbf S\boldsymbol\Sigma^{-1}.

Step 1 of 4. How is QQ structured, and what does this allow?

ProofFrom EM to Lloyd
Prove: Consider a mixture with Σk=εI\boldsymbol\Sigma_k = \varepsilon\mathbf I for all components, weights πk>0\pi_k > 0 and distinct means. Prove that as ε→0\varepsilon \to 0, responsibilities of a point with a unique nearest center tend to a hard assignment and the M-step tends to Lloyd's.
0
Write rikr_{ik} as a softmax and identify factors that cancel between components. Then compare the M-step with hard assignments.

Step 1 of 4. How is rikr_{ik} written when Σk=εI\mat{\Sigma}_k = \varepsilon\mat{I} for all components?

NumericA responsibility by hand
A two-component mixture has π=(0.5,0.5)\pi = (0.5, 0.5) and components N(0,1)\mathcal N(0, 1) and N(3,1)\mathcal N(3, 1). What is the first component's responsibility for x=1x = 1?
NumericHeight of a collapsed component
In d=2d = 2, a component of weight π1=0.2\pi_1 = 0.2 has its mean at observation x1\mathbf x_1 and covariance 10−6I10^{-6}\mathbf I. What is its contribution π1 N(x1;x1,10−6I)\pi_1\,\mathcal N(\mathbf x_1; \mathbf x_1, 10^{-6}\mathbf I) to density at x1\mathbf x_1?
NumericParameters of a tied-covariance mixture
How many free parameters does a mixture of K=4K = 4 components in d=8d = 8 have with tied covariance (one shared symmetric matrix Σ\mathbf\Sigma)?
NumericBIC and AIC need not agree
With n=500n = 500 observations in d=2d = 2, model A is a K=2K = 2 mixture with full covariance and ℓ^A=−1520.0\hat\ell_A = -1520.0, and model B is a K=3K = 3 mixture with diagonal covariance and ℓ^B=−1512.0\hat\ell_B = -1512.0. What is BICB−BICA\mathrm{BIC}_B - \mathrm{BIC}_A? (Positive means BIC prefers A.)
CodeThe stable E-step
Implement 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 Lk\mathbf L_k with Σk=LkLkT\boldsymbol\Sigma_k = \mathbf L_k\mathbf L_k^{\mathsf T}. Return (log_resp, ll): log-responsibilities (n, K) and total log-likelihood ∑ilog⁡∑kπkN(xi;μk,Σk)\sum_i\log\sum_k\pi_k\mathcal N(\mathbf x_i; \boldsymbol\mu_k, \boldsymbol\Sigma_k). 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.0
Shift+Enter to run
QuizWhy training likelihood cannot select K
Why can't you use training log-likelihood to select the number of components KK?
QuizThe boundary with the same mean
Two 1D components have equal weights, the same mean μ\mu and standard deviations σ1<σ2\sigma_1 < \sigma_2. How many points satisfy r1(x)=1/2r_1(x) = 1/2?
QuizSix components for two moons
You fit Gaussian mixtures to two interlocking moons and minimum BIC occurs at K=6K = 6 with full covariance. Which interpretation is correct?

Summary

Key idea
A Gaussian mixture explains data as generated by one of KK randomly selected Gaussians. EM fits it by alternating two steps: responsibilities (the component posterior, a softmax of scores) and re-estimating weights, means and covariances as weighted Gaussian MLEs. Likelihood is unbounded (a component collapsing on one observation sends it upward), invariant to label permutations and has local optima: log-space, Cholesky, a variance floor, good initialization and multiple restarts are needed. And k-means is the σ→0\sigma \to 0 limit of the shared spherical covariance GMM.
  • Model: z∼Cat(π)z \sim \mathrm{Cat}(\vb{\pi}), x∣z=k∼N(μk,Σk)\vb{x} \given z = k \sim \Normal(\vb{\mu}_k, \mat{\Sigma}_k), p(x)=∑kπkN(x;μk,Σk)p(\vb{x}) = \sum_k\pi_k\Normal(\vb{x}; \vb{\mu}_k, \mat{\Sigma}_k); free parameters are (K−1)+Kd+(K - 1) + Kd + covariance parameters (full: K d(d+1)/2K\,d(d+1)/2; tied: d(d+1)/2d(d+1)/2; diagonal: KdKd; spherical: KK).
  • Responsibilities: rik=softmax⁡k(log⁡πk−12log⁡det⁡Σk−12Δk2)r_{ik} = \softmax_k\big(\log\pi_k - \tfrac12\log\det\mat{\Sigma}_k - \tfrac12\Delta_k^2\big); with equal covariances the posterior is a sigmoid (logistic regression); with distinct covariances the boundary is a quadric with two crossings in 1D.
  • Stationarity: ∂ℓ/∂θk=∑irik ∂θklog⁡(πkNk)\partial\ell/\partial\theta_k = \sum_i r_{ik}\,\partial_{\theta_k}\log(\pi_k\Normal_k), yielding μk=1Nk∑irikxi\mu_k = \frac1{N_k}\sum_i r_{ik}x_i, Σk=Sk/Nk\mat{\Sigma}_k = \mat{S}_k/N_k and πk=Nk/n\pi_k = N_k/n; EM iterates these equations and cannot decrease ℓ\ell (lesson 9).
  • Implementation: log-sum-exp and Cholesky; in d=600d = 600, linear-space densities are 0 and responsibilities nan. With the same initial conditions the from-scratch implementation matches scikit-learn to 10−1610^{-16}.
  • Pathologies: ℓ\ell is unbounded (collapse onto a point, with ℓ\ell rising d2log⁡10\tfrac d2\log 10 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 K!K! permutations; local optima and slow convergence under overlap require k-means initialization and multiple restarts.
  • Selection: training likelihood is unsuitable; BIC (pln⁡np\ln n) and AIC (2p2p) penalize, and validation likelihood measures directly. Components are not clusters: two moons need six.
  • k-means is the σ→0\sigma \to 0 limit of EM with shared Σk=σ2I\mat{\Sigma}_k = \sigma^2\mat{I}, with exponential tail e−g/(2σ2)e^{-g/(2\sigma^2)}; the mixture is also a density estimator (KDE is a mixture with K=nK = n), a generator, and, with one mixture per class, a generative classifier generalizing LDA and QDA.