> ## Documentation Index
> Fetch the complete documentation index at: https://aegean.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# The Expectation-Maximization (EM) Algorithm

> EM for mixtures of Gaussians, from the single-Gaussian MLE.

[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/pantelis/eng-ai-agents/blob/main/notebooks/mixture-of-gaussians/em-algorithm/index.ipynb)

The expectation-maximization (EM) algorithm finds maximum likelihood estimates for models with latent variables. This section develops it on the mixture of Gaussians, as an extension of the [maximum likelihood estimate of a Gaussian](https://aegean.ai/aiml-common/lectures/optimization/maximum-likelihood/mle-gaussian-parameters.md). For one Gaussian the estimate has a closed form. With several components it does not, and EM replaces it with two steps that each have a closed form and are repeated until the estimate stops changing. The derivations follow Bishop, Chapter 9 (Bishop, n.d.), and the equation numbers cited are his. The symbols follow the rest of this book: data points are indexed by $i = 1, \ldots, m$ where Bishop writes $n = 1, \ldots, N$, so his responsibilities $\gamma(z_{nk})$ appear here as $\gamma(z_{ik})$ and his effective counts $N_k$ as $m_k$.

You need the [marginal maximum likelihood](https://aegean.ai/aiml-common/lectures/optimization/maximum-likelihood/marginal_maximum_likelihood.md) principle and the multivariate Gaussian density. The previous section, [k-means](https://aegean.ai/aiml-common/lectures/unsupervised/k-means.md), is used twice here. Its output is a good starting point for EM, and k-means itself is the limit of EM when all components share a covariance that shrinks to zero.

> [accordion] Code
>
> ```python theme={null}
> import numpy as np
> from scipy.special import logsumexp
> from scipy.stats import multivariate_normal, norm
> ```

## One Gaussian in closed form

Take a data set $\mathbf X$ of $m$ observations $\mathbf x_1, \ldots, \mathbf x_m$ in $n$ dimensions, drawn independently from a Gaussian $\mathcal N(\mathbf x \mid \boldsymbol\mu, \boldsymbol\Sigma)$. The log likelihood is a sum of logs of Gaussians (Bishop, Eq. 2.118):

$$
\ln p(\mathbf X \mid \boldsymbol\mu, \boldsymbol\Sigma) = -\frac{mn}{2}\ln(2\pi) - \frac{m}{2}\ln|\boldsymbol\Sigma| - \frac{1}{2}\sum_{i=1}^{m} (\mathbf x_i - \boldsymbol\mu)^\top \boldsymbol\Sigma^{-1} (\mathbf x_i - \boldsymbol\mu).
$$

The logarithm acts directly on each Gaussian, so every term is a quadratic in $\boldsymbol\mu$. Setting the derivatives to zero gives the sample mean and the sample covariance (Eqs. 2.121 and 2.122):

$$
\boldsymbol\mu_{\text{ML}} = \frac{1}{m}\sum_{i=1}^{m}\mathbf x_i, \qquad
\boldsymbol\Sigma_{\text{ML}} = \frac{1}{m}\sum_{i=1}^{m}(\mathbf x_i - \boldsymbol\mu_{\text{ML}})(\mathbf x_i - \boldsymbol\mu_{\text{ML}})^\top.
$$

The data below come from three Gaussians in the plane, 100 points each. You fit a single Gaussian to all 300 points with these two formulas.

> [accordion] Code
>
> ```python theme={null}
> rng = np.random.default_rng(42)
> true_means = np.array([[0.0, 0.0], [6.0, 6.0], [-4.0, 5.0]])
> true_covs = np.array([[[1.0, 0.5], [0.5, 1.0]], [[1.5, -0.7], [-0.7, 1.5]], [[0.8, 0.0], [0.0, 2.0]]])
> X = np.vstack([rng.multivariate_normal(mu_k, S_k, 100) for mu_k, S_k in zip(true_means, true_covs)])
> m, n = X.shape
> ```
>
> ```python theme={null}
> mu_ml = X.mean(axis=0)
> Sigma_ml = (X - mu_ml).T @ (X - mu_ml) / m
> ll_single = multivariate_normal.logpdf(X, mu_ml, Sigma_ml).sum()
> print("mu_ML    =", np.round(mu_ml, 2))
> print("Sigma_ML =", np.round(Sigma_ml, 2).tolist())
> print(f"log likelihood of one Gaussian: {ll_single:.1f}")
> ```

```output theme={null}
mu_ML    = [0.65 3.63]
Sigma_ML = [[17.8, 3.1], [3.1, 8.3]]
log likelihood of one Gaussian: -1590.6
```

![Scatter of 300 points in three clusters with a single Gaussian's one and two standard deviation ellipses drawn over them. The mean falls between the clusters, where there are almost no data.](https://mintcdn.com/aegeanaiinc/0ApiccrGMnyvyrYq/aiml-common/lectures/mixture-of-gaussians/em-algorithm/images/cell_5_output_1.svg?fit=max\&auto=format\&n=0ApiccrGMnyvyrYq\&q=85\&s=2f2f30b12c720c116843b56d468e219b)

*One Gaussian fitted to data from three clusters. The ellipses mark one and two standard deviations. The mean sits between the clusters, in a region with almost no data.*

This is the best single Gaussian for the data, yet it puts its highest density where there are no points. One Gaussian per cluster would fit much better, but the data do not say which point came from which cluster.

## The mixture of Gaussians

A mixture of $K$ Gaussians is the density (Bishop, Eq. 9.7)

$$
p(\mathbf x) = \sum_{k=1}^{K} \pi_k\, \mathcal N(\mathbf x \mid \boldsymbol\mu_k, \boldsymbol\Sigma_k),
$$

where the mixing coefficients satisfy $0 \le \pi_k \le 1$ and $\sum_k \pi_k = 1$ (Eqs. 9.8 and 9.9). Each component has its own mean $\boldsymbol\mu_k$ and covariance $\boldsymbol\Sigma_k$.

The mixture can also be read as a model of how the data are generated. Introduce a latent variable $\mathbf z$ in the one-of-$K$ coding: exactly one element $z_k$ equals 1 and the others are 0. Draw $\mathbf z$ with $p(z_k = 1) = \pi_k$, then draw $\mathbf x$ from the Gaussian that $\mathbf z$ selects, $p(\mathbf x \mid z_k = 1) = \mathcal N(\mathbf x \mid \boldsymbol\mu_k, \boldsymbol\Sigma_k)$. Summing the joint $p(\mathbf z)p(\mathbf x \mid \mathbf z)$ over the $K$ values of $\mathbf z$ gives back the mixture (Eqs. 9.10 to 9.12). Every observation $\mathbf x_i$ has its own latent $\mathbf z_i$, with elements $z_{ik}$.

Once you have observed $\mathbf x$, Bayes' theorem gives the posterior probability that component $k$ generated it (Eq. 9.13):

$$
\gamma(z_k) \equiv p(z_k = 1 \mid \mathbf x) = \frac{\pi_k\, \mathcal N(\mathbf x \mid \boldsymbol\mu_k, \boldsymbol\Sigma_k)}{\sum_{j=1}^{K} \pi_j\, \mathcal N(\mathbf x \mid \boldsymbol\mu_j, \boldsymbol\Sigma_j)}.
$$

Bishop calls $\gamma(z_k)$ the *responsibility* of component $k$ for $\mathbf x$. The mixing coefficient $\pi_k$ is the prior probability of $z_k = 1$, and $\gamma(z_k)$ is the posterior. For data point $\mathbf x_i$ it is written $\gamma(z_{ik})$.

The log likelihood of the data set is (Eq. 9.14)

$$
\ln p(\mathbf X \mid \boldsymbol\pi, \boldsymbol\mu, \boldsymbol\Sigma) = \sum_{i=1}^{m} \ln \bigl\{ \sum_{k=1}^{K} \pi_k\, \mathcal N(\mathbf x_i \mid \boldsymbol\mu_k, \boldsymbol\Sigma_k) \bigr\}.
$$

In the single-Gaussian case the logarithm acted directly on each Gaussian. Here the sum over $k$ sits inside the logarithm, so the terms are not quadratic in the means and setting the derivatives to zero does not give a closed form.

The log likelihood is evaluated with the log-sum-exp identity, which computes $\ln \sum_k e^{a_k}$ without underflow when the densities are very small. Its inputs $a_{ik} = \ln \pi_k + \ln \mathcal N(\mathbf x_i \mid \boldsymbol\mu_k, \boldsymbol\Sigma_k)$ are also the log numerators of the responsibilities.

> [accordion] Code
>
> ```python theme={null}
> def log_weighted_densities(X, pi, mu, Sigma):
>     # a_ik = ln pi_k + ln N(x_i | mu_k, Sigma_k), shape (m, K)
>     return np.column_stack(
>         [np.log(pi[k]) + multivariate_normal.logpdf(X, mu[k], Sigma[k]) for k in range(len(pi))]
>     )
>
>
> def log_likelihood(X, pi, mu, Sigma):
>     # Bishop Eq. 9.14: sum over i of ln sum over k of pi_k N(x_i | mu_k, Sigma_k)
>     return logsumexp(log_weighted_densities(X, pi, mu, Sigma), axis=1).sum()
> ```

## Stationarity conditions weighted by responsibilities

Setting the derivatives to zero still gives useful conditions. The derivative with respect to $\boldsymbol\mu_k$ is (Bishop, Eq. 9.16)

$$
0 = \sum_{i=1}^{m} \underbrace{\frac{\pi_k\, \mathcal N(\mathbf x_i \mid \boldsymbol\mu_k, \boldsymbol\Sigma_k)}{\sum_j \pi_j\, \mathcal N(\mathbf x_i \mid \boldsymbol\mu_j, \boldsymbol\Sigma_j)}}_{\gamma(z_{ik})} \boldsymbol\Sigma_k^{-1} (\mathbf x_i - \boldsymbol\mu_k).
$$

The fraction inside the sum is the responsibility of Eq. 9.13. Multiply by $\boldsymbol\Sigma_k$ and rearrange to get (Eqs. 9.17 and 9.18)

$$
\boldsymbol\mu_k = \frac{1}{m_k}\sum_{i=1}^{m} \gamma(z_{ik})\, \mathbf x_i, \qquad m_k = \sum_{i=1}^{m} \gamma(z_{ik}).
$$

This is the sample mean of the single Gaussian with each point weighted by the responsibility of component $k$ for it. $m_k$ is the effective number of points assigned to component $k$. The same steps for $\boldsymbol\Sigma_k$ give a weighted sample covariance (Eq. 9.19):

$$
\boldsymbol\Sigma_k = \frac{1}{m_k}\sum_{i=1}^{m} \gamma(z_{ik})(\mathbf x_i - \boldsymbol\mu_k)(\mathbf x_i - \boldsymbol\mu_k)^\top.
$$

The mixing coefficients must sum to one. Maximizing $\ln p(\mathbf X \mid \boldsymbol\pi, \boldsymbol\mu, \boldsymbol\Sigma) + \lambda\bigl(\sum_k \pi_k - 1\bigr)$ with a Lagrange multiplier $\lambda$ gives $\lambda = -m$ and (Eqs. 9.20 to 9.22)

$$
\pi_k = \frac{m_k}{m},
$$

the average responsibility that component $k$ takes for the data.

The three equations do not give the parameters directly, because the responsibilities on the right-hand side depend on $\boldsymbol\pi$, $\boldsymbol\mu$ and $\boldsymbol\Sigma$ through Eq. 9.13. Each equation has the unknowns on both sides. Given the responsibilities, the parameters follow in closed form, and given the parameters, the responsibilities follow from Bayes' theorem.

## The E step and the M step

EM alternates between these two computations. Start from some values of the parameters and evaluate the log likelihood. Then repeat two steps (Bishop, Section 9.2.2).

In the E step, evaluate the responsibilities with the current parameters (Eq. 9.23):

$$
\gamma(z_{ik}) = \frac{\pi_k\, \mathcal N(\mathbf x_i \mid \boldsymbol\mu_k, \boldsymbol\Sigma_k)}{\sum_{j=1}^{K} \pi_j\, \mathcal N(\mathbf x_i \mid \boldsymbol\mu_j, \boldsymbol\Sigma_j)}.
$$

In the M step, hold the responsibilities fixed and re-estimate the parameters with the weighted maximum likelihood formulas (Eqs. 9.24 to 9.27):

$$
\boldsymbol\mu_k^{\text{new}} = \frac{1}{m_k}\sum_{i=1}^{m} \gamma(z_{ik})\, \mathbf x_i,
$$

$$
\boldsymbol\Sigma_k^{\text{new}} = \frac{1}{m_k}\sum_{i=1}^{m} \gamma(z_{ik})(\mathbf x_i - \boldsymbol\mu_k^{\text{new}})(\mathbf x_i - \boldsymbol\mu_k^{\text{new}})^\top,
$$

$$
\pi_k^{\text{new}} = \frac{m_k}{m}.
$$

After each M step, evaluate the log likelihood (Eq. 9.28) and stop when it no longer changes. The new means are computed first and then used in the covariance, as for the single Gaussian.

The E step works in log space. It subtracts the log-sum-exp of each row before exponentiating, which is the division in Eq. 9.23.

> [accordion] Code
>
> ```python theme={null}
> def e_step(X, pi, mu, Sigma):
>     # Bishop Eq. 9.23: responsibilities gamma(z_ik), shape (m, K)
>     a = log_weighted_densities(X, pi, mu, Sigma)
>     return np.exp(a - logsumexp(a, axis=1, keepdims=True))
> ```
>
> ```python theme={null}
> def m_step(X, gamma, reg=0.0):
>     # Bishop Eqs. 9.24 to 9.27; reg adds reg * I to each covariance (used later against collapse)
>     m_k = gamma.sum(axis=0)
>     pi = m_k / len(X)
>     mu = gamma.T @ X / m_k[:, None]
>     Sigma = np.array(
>         [(gamma[:, k, None] * (X - mu[k])).T @ (X - mu[k]) / m_k[k] + reg * np.eye(X.shape[1]) for k in range(len(m_k))]
>     )
>     return pi, mu, Sigma
> ```
>
> ```python theme={null}
> def em(X, pi, mu, Sigma, max_iter=500, tol=1e-8, reg=0.0):
>     # alternate E and M steps until the log likelihood stops increasing by more than tol
>     history = [(pi, mu, Sigma)]
>     ll = [log_likelihood(X, pi, mu, Sigma)]
>     for _ in range(max_iter):
>         gamma = e_step(X, pi, mu, Sigma)
>         pi, mu, Sigma = m_step(X, gamma, reg)
>         history.append((pi, mu, Sigma))
>         ll.append(log_likelihood(X, pi, mu, Sigma))
>         if ll[-1] - ll[-2] < tol:
>             break
>     return history, np.array(ll)
> ```

The run below starts from a deliberately poor guess. All three means sit in a row near the middle of the data, every covariance is the identity, and the mixing coefficients are equal.

> [accordion] Code
>
> ```python theme={null}
> pi0 = np.full(3, 1 / 3)
> mu0 = np.array([[0.0, 2.0], [1.0, 3.0], [2.0, 4.0]])
> Sigma0 = np.array([np.eye(2)] * 3)
>
> history, ll = em(X, pi0, mu0, Sigma0)
> pi_em, mu_em, Sigma_em = history[-1]
> print(f"EM stopped after {len(ll) - 1} iterations")
> print(f"log likelihood: start {ll[0]:.1f}, end {ll[-1]:.1f} (one Gaussian: {ll_single:.1f})")
> print("pi    =", np.round(pi_em, 3))
> print("means =", np.round(mu_em, 2).tolist())
> ```

```output theme={null}
EM stopped after 31 iterations
log likelihood: start -3615.4, end -1191.7 (one Gaussian: -1590.6)
pi    = [0.333 0.334 0.333]
means = [[0.04, -0.01], [-4.02, 4.83], [5.93, 6.05]]
```

![Four panels of the same 300 points after 0, 1, 5 and the final number of EM iterations. Points are colored by a mix of three colors in proportion to their responsibilities, and each component is drawn as a one standard deviation ellipse. The ellipses start small and close together and end on the three clusters.](https://mintcdn.com/aegeanaiinc/0ApiccrGMnyvyrYq/aiml-common/lectures/mixture-of-gaussians/em-algorithm/images/cell_11_output_1.svg?fit=max\&auto=format\&n=0ApiccrGMnyvyrYq\&q=85\&s=545c4107abfb75da3949d8f9e81898b0)

*EM iterations on the three-cluster data. Each point's color mixes the three component colors in proportion to its responsibilities $\gamma(z_{ik})$, and the ellipses mark one standard deviation of each component. Panel 0 shows the starting parameters.*

After the first M step each mean has moved to the responsibility-weighted center of the points, and each covariance has grown to the weighted spread. Points between components take mixed colors, because their responsibilities are split. By the last iteration each component sits on one cluster and almost every point belongs to one component with responsibility near 1.

![Log likelihood against EM iteration. The curve rises steeply over the first few iterations and then flattens, staying above the dashed line of the single Gaussian fit once it crosses it.](https://mintcdn.com/aegeanaiinc/0ApiccrGMnyvyrYq/aiml-common/lectures/mixture-of-gaussians/em-algorithm/images/cell_12_output_1.svg?fit=max\&auto=format\&n=0ApiccrGMnyvyrYq\&q=85\&s=b1fdff5d1b022c0ccd232c3ae48de576)

*The log likelihood after each EM iteration. The dashed line is the log likelihood of the single Gaussian.*

The log likelihood increases at every iteration. Bishop shows that an E step followed by an M step cannot decrease it (Section 9.4), and the section [EM in general](#em-in-general) below gives the argument. The check below confirms it for this run, up to floating-point rounding.

> [accordion] Code
>
> ```python theme={null}
> steps = np.diff(ll)
> print(f"smallest change between iterations: {steps.min():.2e}")
> print("log likelihood non-decreasing:", bool(np.all(steps > -1e-9)))
> ```

```output theme={null}
smallest change between iterations: 2.40e-09
log likelihood non-decreasing: True
```

The data were generated by a known mixture, so you can compare the estimate with the truth. Each component is matched to the true cluster whose mean is nearest.

> [accordion] Code
>
> ```python theme={null}
> order = [int(np.argmin(np.linalg.norm(mu_em - mu_true, axis=1))) for mu_true in true_means]
> for k, j in enumerate(order):
>     print(f"cluster {k}: true mean {true_means[k]}, EM mean {np.round(mu_em[j], 2)}, EM pi = {pi_em[j]:.3f} (true 1/3)")
>     print(f"           true covariance {true_covs[k].tolist()}, EM covariance {np.round(Sigma_em[j], 2).tolist()}")
> ```

```output theme={null}
cluster 0: true mean [0. 0.], EM mean [ 0.04 -0.01], EM pi = 0.333 (true 1/3)
           true covariance [[1.0, 0.5], [0.5, 1.0]], EM covariance [[0.88, 0.44], [0.44, 0.7]]
cluster 1: true mean [6. 6.], EM mean [5.93 6.05], EM pi = 0.333 (true 1/3)
           true covariance [[1.5, -0.7], [-0.7, 1.5]], EM covariance [[1.63, -0.85], [-0.85, 1.59]]
cluster 2: true mean [-4.  5.], EM mean [-4.02  4.83], EM pi = 0.334 (true 1/3)
           true covariance [[0.8, 0.0], [0.0, 2.0]], EM covariance [[0.83, 0.38], [0.38, 2.1]]
```

![Filled contours of the fitted three-component mixture density over the data. Three density peaks sit on the three clusters, and the EM means (black crosses) fall inside the circles that mark the true means.](https://mintcdn.com/aegeanaiinc/0ApiccrGMnyvyrYq/aiml-common/lectures/mixture-of-gaussians/em-algorithm/images/cell_15_output_1.svg?fit=max\&auto=format\&n=0ApiccrGMnyvyrYq\&q=85\&s=bc70340785e66875803cd6a74c0299a8)

*Density of the fitted mixture, $p(\mathbf x) = \sum_k \pi_k \mathcal N(\mathbf x \mid \boldsymbol\mu_k, \boldsymbol\Sigma_k)$, with the true means (circles) and the EM means (crosses).*

## Singularities and initialization

Maximum likelihood for a mixture has a problem that does not arise for a single Gaussian. Suppose component $j$ has covariance $\sigma_j^2 \mathbf I$ and its mean lands exactly on one data point, $\boldsymbol\mu_j = \mathbf x_i$. That point contributes the density

$$
\mathcal N(\mathbf x_i \mid \mathbf x_i, \sigma_j^2 \mathbf I) = \frac{1}{(2\pi)^{n/2}}\frac{1}{\sigma_j^n},
$$

which grows without bound as $\sigma_j \to 0$. Bishop's Eq. 9.15 gives the case $n = 1$. A single Gaussian that collapses onto one point drives the density of every other point to zero, so its likelihood goes to zero. In a mixture, another component can keep a finite variance and cover the other points while component $j$ shrinks. The log likelihood then goes to infinity (Bishop, Section 9.2.1).

The code builds such a mixture. One component is the single Gaussian fitted above, with mixing coefficient 0.99. The other has mixing coefficient 0.01 and sits on the first data point with a shrinking $\sigma_j$.

> [accordion] Code
>
> ```python theme={null}
> pi_c, mu_c = np.array([0.01, 0.99]), np.array([X[0], mu_ml])
> for sigma_j in [1e-1, 1e-2, 1e-4, 1e-8, 1e-16]:
>     Sigma_c = np.array([sigma_j**2 * np.eye(2), Sigma_ml])
>     print(f"sigma_j = {sigma_j:7.0e}   log likelihood = {log_likelihood(X, pi_c, mu_c, Sigma_c):8.1f}")
> ```

```output theme={null}
sigma_j =   1e-01   log likelihood =  -1577.8
sigma_j =   1e-02   log likelihood =  -1585.3
sigma_j =   1e-04   log likelihood =  -1576.1
sigma_j =   1e-08   log likelihood =  -1557.7
sigma_j =   1e-16   log likelihood =  -1520.8
```

Below $\sigma_j = 10^{-2}$, each further factor of 100 adds $n \ln 100 \approx 9.2$ to the log likelihood, and the growth has no limit. (At $\sigma_j = 0.1$ the narrow component still covers a few neighbors of $\mathbf x_1$, which is why the first value is higher than the second.) The global maximum of the log likelihood is therefore one of these degenerate solutions, and what EM should find is a well-behaved local maximum. Practical implementations guard against collapse. They add a small multiple of the identity to every covariance in the M step (the `reg` argument of `m_step`), or they detect a collapsing component and reset its mean and covariance. A prior on the parameters also removes the singularities. EM then maximizes $Q(\boldsymbol\theta, \boldsymbol\theta^{\text{old}}) + \ln p(\boldsymbol\theta)$ in the M step (Bishop, Section 9.3).

A second issue is that the log likelihood has several local maxima, and EM climbs to the one nearest its start. The run below starts EM ten times, each from three data points drawn at random as means, the overall sample covariance for every component, and equal mixing coefficients.

> [accordion] Code
>
> ```python theme={null}
> def random_start(X, K, rng):
>     # means at K random data points, every covariance the sample covariance, equal weights
>     mu = X[rng.choice(len(X), K, replace=False)]
>     return np.full(K, 1 / K), mu, np.array([np.cov(X.T, bias=True)] * K)
>
>
> start_rng = np.random.default_rng(0)
> for run in range(10):
>     hist, ll_run = em(X, *random_start(X, 3, start_rng))
>     print(f"start {run}: {len(ll_run) - 1:3d} iterations, final log likelihood {ll_run[-1]:8.1f}")
> ```

```output theme={null}
start 0:  21 iterations, final log likelihood  -1191.7
start 1:  27 iterations, final log likelihood  -1191.7
```

```output theme={null}
start 2: 210 iterations, final log likelihood  -1343.9
start 3:  18 iterations, final log likelihood  -1191.7
```

```output theme={null}
start 4:  91 iterations, final log likelihood  -1191.7
start 5:  19 iterations, final log likelihood  -1191.7
start 6:  29 iterations, final log likelihood  -1191.7
```

```output theme={null}
start 7:  31 iterations, final log likelihood  -1191.7
start 8:  27 iterations, final log likelihood  -1191.7
start 9:  45 iterations, final log likelihood  -1191.7
```

Starts that reach the same final value have found the same solution, up to relabeling the components. A mixture of $K$ components has $K!$ equivalent maxima of this kind, one for each way of assigning the parameter sets to the labels. Starts that end lower have stopped at a worse local maximum.

The usual remedy is to start EM from the output of [k-means](https://aegean.ai/aiml-common/lectures/unsupervised/k-means.md) (Bishop, Section 9.2.2). K-means alternates two steps that are cheaper than EM's: assign each point to its nearest center, $r_{ik} = 1$ for $k = \arg\min_j \lVert \mathbf x_i - \boldsymbol\mu_j \rVert^2$ and 0 otherwise (Eq. 9.2), then move each center to the mean of its points (Eq. 9.4). The cluster means, the cluster sample covariances and the cluster fractions then serve as the starting $\boldsymbol\mu_k$, $\boldsymbol\Sigma_k$ and $\pi_k$.

> [accordion] Code
>
> ```python theme={null}
> def kmeans(X, K, rng, max_iter=100):
>     # Bishop Eqs. 9.2 and 9.4: hard assignment r_ik, then the mean of each cluster
>     mu = X[rng.choice(len(X), K, replace=False)]
>     for _ in range(max_iter):
>         r = np.argmin(((X[:, None, :] - mu[None]) ** 2).sum(axis=-1), axis=1)
>         new_mu = np.array([X[r == k].mean(axis=0) if np.any(r == k) else mu[k] for k in range(K)])
>         if np.allclose(new_mu, mu):
>             break
>         mu = new_mu
>     return mu, r
> ```
>
> ```python theme={null}
> def kmeans_start(X, K, rng):
>     # EM starting point from k-means: cluster fractions, means and sample covariances
>     mu, r = kmeans(X, K, rng)
>     pi = np.array([np.mean(r == k) for k in range(K)])
>     Sigma = np.array([np.cov(X[r == k].T, bias=True) for k in range(K)])
>     return pi, mu, Sigma
>
>
> hist_km, ll_km = em(X, *kmeans_start(X, 3, np.random.default_rng(0)))
> print(f"k-means start: {len(ll_km) - 1} iterations, final log likelihood {ll_km[-1]:.1f}")
> ```

```output theme={null}
k-means start: 11 iterations, final log likelihood -1191.7
```

Started from k-means, EM reaches the best value of the random starts in fewer iterations than any of them.

## K-means as a limit of EM

K-means makes a hard assignment of each point to one cluster, and EM makes a soft one. The two are related exactly (Bishop, Section 9.3.2). Give every component the same covariance $\epsilon \mathbf I$, with $\epsilon$ a fixed constant that EM does not re-estimate, so that

$$
p(\mathbf x \mid \boldsymbol\mu_k, \boldsymbol\Sigma_k) = \frac{1}{(2\pi\epsilon)^{n/2}} \exp\left\{-\frac{1}{2\epsilon}\lVert \mathbf x - \boldsymbol\mu_k \rVert^2\right\}.
$$

Bishop writes this as Eq. 9.41. The responsibilities become (Eq. 9.42)

$$
\gamma(z_{ik}) = \frac{\pi_k \exp\{-\lVert \mathbf x_i - \boldsymbol\mu_k \rVert^2 / 2\epsilon\}}{\sum_j \pi_j \exp\{-\lVert \mathbf x_i - \boldsymbol\mu_j \rVert^2 / 2\epsilon\}}.
$$

As $\epsilon \to 0$, the term with the smallest distance $\lVert \mathbf x_i - \boldsymbol\mu_j \rVert^2$ decays most slowly. Its responsibility goes to 1 and all others go to 0, whatever the values of $\pi_k$ as long as none is zero. The responsibility $\gamma(z_{ik})$ becomes the k-means indicator $r_{ik}$, and the M step for the means, Eq. 9.17, becomes the k-means update, Eq. 9.4. In the same limit, the expected complete-data log likelihood introduced in the next section tends to $-\frac{1}{2}\sum_i \sum_k r_{ik} \lVert \mathbf x_i - \boldsymbol\mu_k \rVert^2$ plus a constant (Eq. 9.43). Maximizing it is the same as minimizing the k-means loss $L = \sum_i \sum_k r_{ik} \lVert \mathbf x_i - \boldsymbol\mu_k \rVert^2$ of the previous section, which Bishop calls the distortion $J$ (Eq. 9.1).

The code holds the means at the values EM found and shrinks $\epsilon$. For each $\epsilon$ it reports the average of the largest responsibility of each point, and the largest gap over all points and components between $\gamma(z_{ik})$ and the k-means indicator $r_{ik}$ of the nearest mean.

> [accordion] Code
>
> ```python theme={null}
> def shared_isotropic_responsibilities(X, pi, mu, eps):
>     # Bishop Eq. 9.42: responsibilities when every covariance is eps * I
>     a = np.log(pi)[None] - ((X[:, None, :] - mu[None]) ** 2).sum(axis=-1) / (2 * eps)
>     return np.exp(a - logsumexp(a, axis=1, keepdims=True))
>
>
> r_ik = np.eye(3)[np.argmin(((X[:, None, :] - mu_em[None]) ** 2).sum(axis=-1), axis=1)]  # Eq. 9.2
> for eps in [16.0, 4.0, 1.0, 0.25, 0.05]:
>     g = shared_isotropic_responsibilities(X, pi_em, mu_em, eps)
>     print(f"eps = {eps:5.2f}   mean largest responsibility = {g.max(axis=1).mean():.4f}   max |gamma - r| = {np.abs(g - r_ik).max():.2e}")
> ```

```output theme={null}
eps = 16.00   mean largest responsibility = 0.7670   max |gamma - r| = 4.68e-01
eps =  4.00   mean largest responsibility = 0.9885   max |gamma - r| = 3.54e-01
eps =  1.00   mean largest responsibility = 0.9997   max |gamma - r| = 8.32e-02
eps =  0.25   mean largest responsibility = 1.0000   max |gamma - r| = 6.90e-05
eps =  0.05   mean largest responsibility = 1.0000   max |gamma - r| = 1.60e-21
```

![Three panels of the data colored by responsibilities under a shared covariance epsilon times the identity, for epsilon equal to 16, 4 and 0.1. At 16 the colors are blended across the plane; at 0.1 every point has one pure color, the color of its nearest mean.](https://mintcdn.com/aegeanaiinc/0ApiccrGMnyvyrYq/aiml-common/lectures/mixture-of-gaussians/em-algorithm/images/cell_21_output_1.svg?fit=max\&auto=format\&n=0ApiccrGMnyvyrYq\&q=85\&s=a135798370dcf8a53c6bd2a5f64f6e71)

*Responsibilities with a shared covariance $\epsilon \mathbf I$ and the means held at the EM solution (gray crosses). As $\epsilon$ shrinks, the blended colors turn into pure ones and each point takes the color of its nearest mean, which is the k-means assignment.*

K-means is therefore EM for a mixture whose components are round, equal in size and infinitely narrow. It estimates the means only. This is also why k-means is a good starting point for EM. It solves a simplified version of the same problem, and its iterations are fewer and cheaper.

## EM in general

The mixture of Gaussians is one instance of a general algorithm. Collect the observed data in $\mathbf X$, the latent variables in $\mathbf Z$ (row $i$ is $\mathbf z_i^\top$), and all parameters in $\boldsymbol\theta$. The log likelihood is (Bishop, Eq. 9.29)

$$
\ln p(\mathbf X \mid \boldsymbol\theta) = \ln \bigl\{ \sum_{\mathbf Z} p(\mathbf X, \mathbf Z \mid \boldsymbol\theta) \bigr\},
$$

with the sum over the latent variables inside the logarithm, as in Eq. 9.14.

If you were also given $\mathbf Z$, the *complete-data* log likelihood would be easy to maximize. For the mixture it is (Eq. 9.36)

$$
\ln p(\mathbf X, \mathbf Z \mid \boldsymbol\mu, \boldsymbol\Sigma, \boldsymbol\pi) = \sum_{i=1}^{m}\sum_{k=1}^{K} z_{ik}\{\ln \pi_k + \ln \mathcal N(\mathbf x_i \mid \boldsymbol\mu_k, \boldsymbol\Sigma_k)\}.
$$

The logarithm now acts on each Gaussian, and the maximization splits into one single-Gaussian fit per component on the points assigned to it.

In practice $\mathbf Z$ is unknown, and the only information about it is its posterior $p(\mathbf Z \mid \mathbf X, \boldsymbol\theta^{\text{old}})$ under the current parameters. EM therefore maximizes the expected complete-data log likelihood under that posterior (Eq. 9.30):

$$
Q(\boldsymbol\theta, \boldsymbol\theta^{\text{old}}) = \sum_{\mathbf Z} p(\mathbf Z \mid \mathbf X, \boldsymbol\theta^{\text{old}}) \ln p(\mathbf X, \mathbf Z \mid \boldsymbol\theta).
$$

The E step evaluates the posterior $p(\mathbf Z \mid \mathbf X, \boldsymbol\theta^{\text{old}})$. The M step sets $\boldsymbol\theta^{\text{new}} = \arg\max_{\boldsymbol\theta} Q(\boldsymbol\theta, \boldsymbol\theta^{\text{old}})$ (Eq. 9.31). For the mixture, the posterior factorizes over the data points and the expected value of $z_{ik}$ is the responsibility, $\mathbb E[z_{ik}] = \gamma(z_{ik})$ (Eq. 9.39). Substituting it gives (Eq. 9.40)

$$
\mathbb E_{\mathbf Z}[\ln p(\mathbf X, \mathbf Z \mid \boldsymbol\mu, \boldsymbol\Sigma, \boldsymbol\pi)] = \sum_{i=1}^{m}\sum_{k=1}^{K} \gamma(z_{ik})\{\ln \pi_k + \ln \mathcal N(\mathbf x_i \mid \boldsymbol\mu_k, \boldsymbol\Sigma_k)\},
$$

and maximizing it gives the M-step formulas derived above.

The guarantee that the log likelihood never decreases comes from a decomposition that holds for any distribution $q(\mathbf Z)$ (Bishop, Section 9.4, Eqs. 9.70 to 9.72):

$$
\ln p(\mathbf X \mid \boldsymbol\theta) = \mathcal L(q, \boldsymbol\theta) + \mathrm{KL}(q \,\|\, p), \qquad
\mathcal L(q, \boldsymbol\theta) = \sum_{\mathbf Z} q(\mathbf Z) \ln \frac{p(\mathbf X, \mathbf Z \mid \boldsymbol\theta)}{q(\mathbf Z)}, \qquad
\mathrm{KL}(q \,\|\, p) = -\sum_{\mathbf Z} q(\mathbf Z) \ln \frac{p(\mathbf Z \mid \mathbf X, \boldsymbol\theta)}{q(\mathbf Z)}.
$$

The KL divergence is non-negative, so $\mathcal L(q, \boldsymbol\theta)$ is a lower bound on the log likelihood. The E step sets $q(\mathbf Z) = p(\mathbf Z \mid \mathbf X, \boldsymbol\theta^{\text{old}})$, which makes the KL term zero and the bound touch the log likelihood at $\boldsymbol\theta^{\text{old}}$. With this $q$, $\mathcal L(q, \boldsymbol\theta)$ equals $Q(\boldsymbol\theta, \boldsymbol\theta^{\text{old}})$ plus a constant that does not depend on $\boldsymbol\theta$ (Eq. 9.74). The M step raises the bound by maximizing $Q$. The log likelihood rises at least as much, because the KL term, zero before the M step, can only be non-negative after it.

The cell below checks the decomposition numerically for the mixture. It takes $q$ as the responsibilities computed at the starting parameters and evaluates both terms at the parameters after the first M step.

> [accordion] Code
>
> ```python theme={null}
> theta_old, theta_new = history[0], history[1]
> q = e_step(X, *theta_old)                    # q(Z) = p(Z | X, theta_old), factorized over n
> a_new = log_weighted_densities(X, *theta_new)  # ln p(x_i, z_ik = 1 | theta_new)
> log_post_new = a_new - logsumexp(a_new, axis=1, keepdims=True)  # ln p(z_ik = 1 | x_i, theta_new)
>
> lower_bound = np.sum(q * (a_new - np.log(q)))
> kl = -np.sum(q * (log_post_new - np.log(q)))
> print(f"L(q, theta_new)          = {lower_bound:10.3f}")
> print(f"KL(q || p)               = {kl:10.3f}")
> print(f"sum                      = {lower_bound + kl:10.3f}")
> print(f"ln p(X | theta_new)      = {log_likelihood(X, *theta_new):10.3f}")
> ```

```output theme={null}
L(q, theta_new)          =  -1395.654
KL(q || p)               =     23.306
sum                      =  -1372.347
ln p(X | theta_new)      =  -1372.347
```

EM applies to any model whose complete-data log likelihood is easy to maximize, with discrete or continuous latent variables. Dempster, Laird and Rubin (1977) gave the general formulation. The [latent variable models](https://aegean.ai/aiml-common/lectures/mixture-of-gaussians/index) section uses the same structure, a latent $\mathbf z$ and a conditional $p(\mathbf x \mid \mathbf z)$, for generative models whose latent space is continuous.

## Inliers and outliers as a two-component mixture

A mixture can also model measurements that should not be trusted. Consider fitting a line $g(x; \boldsymbol\theta) = \boldsymbol\theta^\top \boldsymbol\phi(x)$ with $\boldsymbol\phi(x) = (1, x)^\top$ to pairs $(x^{(i)}, y^{(i)})$, in the notation of the [linear regression](https://aegean.ai/aiml-common/lectures/regression/linear-regression.md) section. Ordinary least squares assumes every target is the line plus Gaussian noise of variance $\sigma^2$. Suppose instead that a fraction of the points are gross errors, spread over the whole range of $y$. Model each target as coming from one of two components, an inlier component around the line and an outlier component that is uniform over the range of the data:

$$
p(y^{(i)} \mid x^{(i)}) = \pi\, \mathcal N\big(y^{(i)} \mid \boldsymbol\theta^\top \boldsymbol\phi(x^{(i)}), \sigma^2\big) + (1 - \pi)\, \mathcal U(y^{(i)}).
$$

The mixing coefficient $\pi$ is the inlier fraction. It differs from the earlier mixture in two ways: the Gaussian component is conditional on $x^{(i)}$, as in Bishop's mixture of linear regression models (Section 14.5.1, Eq. 14.34), and the second component is uniform and has no parameters. Bishop writes the weights as $\mathbf w$, the targets as $t_n$ and the noise as a precision $\beta = 1/\sigma^2$; the equations below are his with those symbols replaced.

The E step computes the responsibility of the inlier component for each point,

$$
\gamma(z_i) = \frac{\pi\, \mathcal N\big(y^{(i)} \mid \boldsymbol\theta^\top \boldsymbol\phi(x^{(i)}), \sigma^2\big)}{\pi\, \mathcal N\big(y^{(i)} \mid \boldsymbol\theta^\top \boldsymbol\phi(x^{(i)}), \sigma^2\big) + (1 - \pi)\, \mathcal U(y^{(i)})}.
$$

The M step maximizes the expected complete-data log likelihood. For $\boldsymbol\theta$ it is a weighted least squares problem, with the responsibilities as weights. With $\mathbf R = \operatorname{diag}(\gamma(z_i))$ and the design matrix $\boldsymbol\Phi$ whose rows are $\boldsymbol\phi(x^{(i)})^\top$, the solution is (Bishop, Eq. 14.42)

$$
\boldsymbol\theta = (\boldsymbol\Phi^\top \mathbf R \boldsymbol\Phi)^{-1} \boldsymbol\Phi^\top \mathbf R\, \mathbf y.
$$

The noise variance and the inlier fraction follow the same pattern as $\boldsymbol\Sigma_k$ and $\pi_k$:

$$
\sigma^2 = \frac{\sum_i \gamma(z_i)\big\{y^{(i)} - \boldsymbol\theta^\top \boldsymbol\phi(x^{(i)})\big\}^2}{\sum_i \gamma(z_i)}, \qquad \pi = \frac{1}{m}\sum_i \gamma(z_i).
$$

These are the single-component versions of Bishop's Eqs. 14.44 and 14.38. With $\gamma(z_i) = 1$ for every point, the weighted solution reduces to the ordinary least squares solution $\boldsymbol\theta = (\boldsymbol\Phi^\top \boldsymbol\Phi)^{-1}\boldsymbol\Phi^\top \mathbf y$ (Bishop, Eq. 3.15).

The data below have 60 points. 42 lie on the line $y = 1 + 0.5x$ with noise of standard deviation 0.3, and 18 are outliers drawn uniformly over the range of $y$.

> [accordion] Code
>
> ```python theme={null}
> line_rng = np.random.default_rng(1)
> n_in, n_out = 42, 18
> x_line = line_rng.uniform(0, 10, n_in + n_out)
> y_line = 1.0 + 0.5 * x_line + 0.3 * line_rng.standard_normal(n_in + n_out)
> is_outlier = np.zeros(n_in + n_out, dtype=bool)
> is_outlier[n_in:] = True
> y_line[is_outlier] = line_rng.uniform(-4, 12, n_out)
> Phi = np.column_stack([np.ones_like(x_line), x_line])
> theta_ols = np.linalg.lstsq(Phi, y_line, rcond=None)[0]
> ```
>
> ```python theme={null}
> def inlier_responsibilities(Phi, y, theta, sigma2, pi, u):
>     # E step: gamma(z_i) of the inlier component; u is the constant uniform density
>     inlier = pi * norm.pdf(y, Phi @ theta, np.sqrt(sigma2))
>     return inlier / (inlier + (1 - pi) * u)
> ```
>
> ```python theme={null}
> def weighted_line_fit(Phi, y, gamma):
>     # M step: weighted least squares (Bishop Eq. 14.42), then sigma^2 and pi
>     theta = np.linalg.solve(Phi.T @ (gamma[:, None] * Phi), Phi.T @ (gamma * y))
>     sigma2 = np.sum(gamma * (y - Phi @ theta) ** 2) / gamma.sum()
>     return theta, sigma2, gamma.mean()
> ```
>
> ```python theme={null}
> u = 1 / (y_line.max() - y_line.min())
> theta, sigma2, pi_in = theta_ols, np.var(y_line - Phi @ theta_ols), 0.5
> for _ in range(100):
>     gamma_line = inlier_responsibilities(Phi, y_line, theta, sigma2, pi_in, u)
>     theta, sigma2, pi_in = weighted_line_fit(Phi, y_line, gamma_line)
>
> print(f"true line:     theta = [1.00, 0.50]")
> print(f"least squares: theta = [{theta_ols[0]:.2f}, {theta_ols[1]:.2f}]")
> theta_inliers = np.linalg.lstsq(Phi[~is_outlier], y_line[~is_outlier], rcond=None)[0]
> print(f"least squares on the true inliers only: theta = [{theta_inliers[0]:.2f}, {theta_inliers[1]:.2f}]")
> print(f"EM mixture:    theta = [{theta[0]:.2f}, {theta[1]:.2f}],  noise std = {np.sqrt(sigma2):.2f},  inlier fraction pi = {pi_in:.2f}")
> flagged = gamma_line < 0.5
> print(f"points with gamma < 0.5: {flagged.sum()}, of which true outliers: {(flagged & is_outlier).sum()} of {n_out}")
> ```

```output theme={null}
true line:     theta = [1.00, 0.50]
least squares: theta = [2.10, 0.34]
least squares on the true inliers only: theta = [0.92, 0.51]
EM mixture:    theta = [0.91, 0.51],  noise std = 0.24,  inlier fraction pi = 0.73
points with gamma < 0.5: 15, of which true outliers: 15 of 18
```

![Scatter of 60 points colored by inlier responsibility, with three lines: the true line, the least squares fit pulled toward the outliers, and the EM mixture fit lying on the true line. Points far from the line are dark, meaning low responsibility.](https://mintcdn.com/aegeanaiinc/0ApiccrGMnyvyrYq/aiml-common/lectures/mixture-of-gaussians/em-algorithm/images/cell_27_output_1.svg?fit=max\&auto=format\&n=0ApiccrGMnyvyrYq\&q=85\&s=7ba4f2615ea82918280589bcdf0c5cbe)

*Line fitting with 18 outliers among 60 points. The color of each point is its inlier responsibility $\gamma(z_i)$. Least squares gives every point the same weight. EM gives the outliers responsibilities near zero and fits the line to the rest.*

The EM line is almost exactly the least squares line of the 42 true inliers, which is the fit you would get if the labels were known. Its inlier fraction, 0.73, is above the true 0.70 because 3 of the 18 outliers happened to land close to the line. EM counts them as inliers, and nothing in the data distinguishes them from the true inliers.

The responsibilities weight the fit and also label the points: the model attributes a point with $\gamma(z_i)$ near 0 to the outlier component. Replace the soft weight with a hard test, inlier if the residual is below a threshold set by $\sigma$, and you get the inlier test of RANSAC. The inlier fraction $\pi$ is the quantity that sets how many random samples RANSAC needs. The next chapter, [robust estimation](https://aegean.ai/aiml-common/lectures/robust-estimation/least-squares-outliers.md), starts from this model.

## Lecture video

[https://www.youtube.com/embed/qMTuMa86NzU](https://www.youtube.com/embed/qMTuMa86NzU)

**Key references**: (Bishop, n.d.; Dempster et al., n.d.)

## References

* Dempster, A., Laird, N., Rdin, D. (n.d.). *Maximum Likelihood from Incomplete Data via the EM Algorithm*.
* Bishop (n.d.). *Pattern Recognition and Machine Learning*. [Link](https://www.microsoft.com/en-us/research/uploads/prod/2006/01/Bishop-Pattern-Recognition-and-Machine-Learning-2006.pdf)

***

Found an error on this page? [Report an issue](https://github.com/aegean-ai/eaia-feedback/issues/new?template=page-issue.yml\&page=/aiml-common/lectures/mixture-of-gaussians/em-algorithm).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.