Course contents 07 / 15

07 / 15 · Latent Variables and Approximate Inference

EM and Bayesian PCA

EM as a lower bound climbed one block at a time, true labels recovered from annotators of unknown skill, what changes when the E-step cannot be exact, and a Bayesian PCA that chooses its own dimension.

On this page 7

Here are 100 points in ten dimensions. The eigenvalues of their sample covariance are 62.2362.23, 12.0012.00 and 4.454.45, then 1.521.52, 1.351.35 and a slow decline to 0.390.39. How many principal components do the data contain? Probabilistic PCA answers in terms of likelihood, and the answer is unhelpful: the maximized likelihood grows with every component added.

A Bayesian model can do better. Put a prior on the loadings with one precision per column, as the relevance vector machine did for weights, and let the evidence switch unneeded columns off. The evidence is now an integral over the loadings with no closed form, and the tool that handles it is the EM algorithm of the Machine Learning course (Dempster, Laird and Rubin, 1977), restated as a bound that the rest of this part of the course builds on.

Probabilistic PCA cannot choose its dimension#

Probabilistic PCA explains each observation xi∈Rdx_i \in \mathbb R^d, centred so that the data have mean zero, by a kk-dimensional code ziz_i:

zi∼N(0,Ik),xi∣zi∼N(Wzi,σ2Id),xi∼N(0,  WW⊤+σ2Id),\begin{aligned} z_i &\sim \mathcal N(0, I_k), \\ x_i \mid z_i &\sim \mathcal N(W z_i, \sigma^2 I_d), \\ x_i &\sim \mathcal N(0,\; W W^\top + \sigma^2 I_d) , \end{aligned}

where W∈Rd×kW \in \mathbb R^{d \times k} is the loading matrix with columns w1,…,wkw_1, \dots, w_k and σ2\sigma^2 the noise variance.

Centring costs nothing. With a mean, the marginal is xi∼N(μ,C)x_i \sim \mathcal N(\mu, C) with C=WW⊤+σ2IdC = W W^\top + \sigma^2 I_d, and μ\mu enters the log-likelihood only through −12∑i(xi−μ)⊤C−1(xi−μ)-\frac12 \sum_i (x_i - \mu)^\top C^{-1} (x_i - \mu). The gradient of this quadratic form, with C−1C^{-1} symmetric, gives

∇μlog⁡p(X)=C−1∑i=1n(xi−μ)=0  ⟺  ∑i=1n(xi−μ)=0(C−1 invertible)  ⟺  μ=xˉ.\begin{aligned} \nabla_\mu \log p(X) &= C^{-1} \sum_{i=1}^n (x_i - \mu) = 0 \\ \iff\quad \sum_{i=1}^n (x_i - \mu) &= 0 \quad (C^{-1} \text{ invertible}) \\ \iff\quad \mu &= \bar x . \end{aligned}

The log-likelihood is concave in μ\mu, because C−1C^{-1} is positive definite, so this stationary point is the maximum. It does not depend on WW or σ2\sigma^2, so we set μ=xˉ\mu = \bar x once, centre the data and fit WW and σ2\sigma^2 to the centred points.

The maximum likelihood solution is known in closed form. Let λ1≥⋯≥λd\lambda_1 \ge \dots \ge \lambda_d be the eigenvalues of the sample covariance S=1n∑ixixi⊤S = \frac1n \sum_i x_i x_i^\top. The columns of WW span the kk leading eigenvectors of SS, the directions of PCA. In the solution with orthogonal columns, column jj has length λj−σ2\sqrt{\lambda_j - \sigma^2}, and σ2\sigma^2 is the average of the d−kd - k discarded eigenvalues.

Why

The log-likelihood depends on the data only through SS: with C=WW⊤+σ2IdC = W W^\top + \sigma^2 I_d, it is −n2(log⁡det⁡C+tr⁡(C−1S))-\frac n2\big(\log\det C + \operatorname{tr}(C^{-1} S)\big) plus a constant. Suppose CC has the eigenvectors of SS, with eigenvalues cjc_j. The determinant is the product of the cjc_j and the trace is ∑jλj/cj\sum_j \lambda_j / c_j, so the log-likelihood splits into one term per direction, −n2(log⁡cj+λj/cj)-\frac n2 (\log c_j + \lambda_j/c_j), and its derivative in cjc_j, −n2(1/cj−λj/cj2)-\frac n2 (1/c_j - \lambda_j/c_j^2), vanishes at cj=λjc_j = \lambda_j. A rank-kk WW sets kk of them freely above σ2\sigma^2, cj=∥wj∥2+σ2=λjc_j = \lVert w_j \rVert^2 + \sigma^2 = \lambda_j, which gives the lengths λj−σ2\sqrt{\lambda_j - \sigma^2}; the other d−kd - k equal σ2\sigma^2. Setting the derivative of ∑j>k(log⁡σ2+λj/σ2)\sum_{j \gt k} (\log\sigma^2 + \lambda_j/\sigma^2) in σ2\sigma^2 to zero gives their average. That the optimal CC has the eigenvectors of SS, and keeps the largest eigenvalues, is proved in Tipping and Bishop (1999), Appendices A.1–A.2.

One case has no maximum. If all d−kd - k discarded eigenvalues are zero, the data lie in a kk-dimensional subspace, as they always do when n≤k+1n \le k + 1, because nn centred points span at most n−1n - 1 dimensions. Each discarded direction then contributes −n2log⁡σ2-\frac n2 \log \sigma^2 to the log-likelihood, which grows without bound as σ2→0\sigma^2 \to 0: there is no maximizer with σ2>0\sigma^2 > 0.

If the noise variance is fixed instead of fitted, each column is decided on its own. Column jj sets cj=∥wj∥2+σ2c_j = \lVert w_j \rVert^2 + \sigma^2, which cannot go below σ2\sigma^2. Its term −n2(log⁡cj+λj/cj)-\frac n2 (\log c_j + \lambda_j / c_j) has the derivative n2(λj−cj)/cj2\frac n2 (\lambda_j - c_j)/c_j^2, positive below λj\lambda_j and negative above. So cj=λjc_j = \lambda_j when λj>σ2\lambda_j > \sigma^2, and otherwise cjc_j stays at the boundary σ2\sigma^2, a zero column:

∥wj∥2=max⁡(λj−σ2, 0),W=Uk(max⁡(Λk−σ2Ik, 0))1/2R,\begin{aligned} \lVert w_j \rVert^2 &= \max(\lambda_j - \sigma^2,\ 0), \\ W &= U_k \big(\max(\Lambda_k - \sigma^2 I_k,\ 0)\big)^{1/2} R , \end{aligned}

where UkU_k holds the kk leading eigenvectors, Λk\Lambda_k is the diagonal matrix of their eigenvalues, the maximum is taken entry by entry, and RR is any orthogonal k×kk \times k matrix, since WR(WR)⊤=WW⊤W R (W R)^\top = W W^\top leaves the likelihood unchanged. The leading eigenvectors are the right ones: moving cjc_j from σ2\sigma^2 to λj\lambda_j raises the log-likelihood by n2(t−1−log⁡t)\frac n2 (t - 1 - \log t) with t=λj/σ2t = \lambda_j / \sigma^2, which increases with tt for t>1t > 1.

A fixed σ2\sigma^2 can therefore leave fewer than kk active columns. On the data of the opening, with the true σ2=1\sigma^2 = 1 and k=9k = 9, the columns along 0.890.89, 0.840.84 and 0.630.63 vanish. Six survive, with lengths down to 0.420.42, because sampling noise has lifted λ4\lambda_4, λ5\lambda_5 and λ6\lambda_6 above 1.

What maximum likelihood cannot do is choose kk. The models are nested: a model with k+1k + 1 columns can set one of them to zero, so the maximized log-likelihood never decreases with kk. The data of the opening come from a model with three latent dimensions and unit noise:

kk123456789
log-likelihood−2052.4-2052.4−1885.9-1885.9−1813.9-1813.9−1806.6-1806.6−1799.7-1799.7−1793.2-1793.2−1790.6-1790.6−1786.4-1786.4−1783.4-1783.4

The gains are 166.5166.5 and 72.072.0 up to k=3k = 3, then 7.37.3, 6.96.9 and less, but the likelihood keeps growing. With k=9k = 9 every column is used. The lengths λj−σ2\sqrt{\lambda_j - \sigma^2} are 7.867.86, 3.413.41 and 2.022.02 for the signal and 1.071.07 down to 0.490.49 for six directions that carry only noise. The noise variance comes out as σ2=0.388\sigma^2 = 0.388, well below the true value 1, because the extra columns have absorbed most of the noise. Choosing kk by BIC or by held-out likelihood means fitting every kk separately.

EM as coordinate ascent on the evidence lower bound#

Let X={x1,…,xn}X = \{x_1, \dots, x_n\} be the observations, Z={z1,…,zn}Z = \{z_1, \dots, z_n\} the latent variables and θ\theta the parameters. For any distribution q(Z)q(Z) that is positive wherever the posterior is,

log⁡p(X∣θ)=L(q,θ)+DKL(q ∥ p(Z∣X,θ)),L(q,θ)=Eq[log⁡p(X,Z∣θ)]−Eq[log⁡q(Z)].\begin{aligned} \log p(X \mid \theta) &= \mathcal L(q, \theta) + D_{\mathrm{KL}}\big(q \,\|\, p(Z \mid X, \theta)\big), \\ \mathcal L(q, \theta) &= \mathbb E_q\big[\log p(X, Z \mid \theta)\big] - \mathbb E_q\big[\log q(Z)\big] . \end{aligned}

The EM note derives the identity: write log⁡p(X∣θ)=log⁡p(X,Z∣θ)−log⁡p(Z∣X,θ)\log p(X \mid \theta) = \log p(X, Z \mid \theta) - \log p(Z \mid X, \theta), add and subtract log⁡q(Z)\log q(Z), and average over qq. The KL divergence is non-negative, so L\mathcal L, the evidence lower bound (ELBO), is a lower bound on the log evidence, tight exactly when qq is the posterior. The Code section checks the identity for a randomly drawn qq: both sides equal −14.691242-14.691242.

EM is coordinate ascent on L\mathcal L. The E-step maximizes over qq with θ\theta fixed. Since log⁡p(X∣θ)\log p(X \mid \theta) does not depend on qq, this minimizes the KL divergence: qq becomes the posterior and the gap closes. The M-step maximizes over θ\theta with qq fixed. The entropy of qq does not depend on θ\theta, so the M-step maximizes the expected complete-data log-likelihood Eq[log⁡p(X,Z∣θ)]\mathbb E_q[\log p(X, Z \mid \theta)].

Why does adding unknowns help? The log-likelihood of a mixture of Gaussians is a sum over points of the logarithm of a sum over components. It does not split into separate fits, and it has many local maxima: relabelling the KK components alone turns one maximum into K!K!. If we knew which component produced each point, the fit would split into one Gaussian fit per component. Latent variables are chosen so that the complete-data distribution p(X,Z∣θ)p(X, Z \mid \theta) is in the exponential family. Then log⁡p(X,Z∣θ)\log p(X, Z \mid \theta) is a linear function of the natural parameters minus the log-partition function, which is convex because its Hessian is a covariance; so it is concave. Its average over qq is concave too, because a sum of concave functions with non-negative weights is concave. The M-step is a concave maximization, solved by moment matching with the expected sufficient statistics, in closed form or by a few steps of a convex solver.

EM itself does not need the exponential family. The decomposition and the monotonicity argument hold for any model, and the M-step only has to raise Eq[log⁡p(X,Z∣θ)]\mathbb E_q[\log p(X, Z \mid \theta)]. Outside the exponential family, or in parameters that are not natural, that function need not be concave. The crowd-label model below is built from terms log⁡σ(ab)\log \sigma(ab), in an annotator’s skill aa and an item’s easiness bb. With (log⁡σ)′(x)=σ(−x)(\log \sigma)'(x) = \sigma(-x), σ′(x)=σ(x)σ(−x)\sigma'(x) = \sigma(x)\sigma(-x) and the chain rule,

∂a2log⁡σ(ab)=−b2 σ(ab) σ(−ab),∂a∂blog⁡σ(ab)=σ(−ab)−ab σ(ab) σ(−ab),\begin{aligned} \partial_a^2 \log \sigma(ab) &= -b^2\, \sigma(ab)\, \sigma(-ab), \\ \partial_a \partial_b \log \sigma(ab) &= \sigma(-ab) - ab\, \sigma(ab)\, \sigma(-ab), \end{aligned}

and ∂b2log⁡σ(ab)=−a2 σ(ab) σ(−ab)\partial_b^2 \log \sigma(ab) = -a^2\, \sigma(ab)\, \sigma(-ab) by symmetry. At a=b=0a = b = 0 they equal 00, 12\frac12 and 00, so the Hessian has the eigenvalues ±12\pm\frac12: a saddle. That M-step objective is not concave, and a few gradient steps that raise it are all that the generalized EM below asks for.

The M-step averages the complete-data log-likelihood over qq. Substituting the average of ZZ gives another function: in general Eq[log⁡p(X,Z∣θ)]≠log⁡p(X,Eq[Z]∣θ)\mathbb E_q[\log p(X, Z \mid \theta)] \ne \log p(X, \mathbb E_q[Z] \mid \theta). The two agree when log⁡p(X,Z∣θ)\log p(X, Z \mid \theta) is linear in ZZ. For a mixture with one-hot labels it is, log⁡p(x,z)=∑kzklog⁡(πk N(x∣μk,Σk))\log p(x, z) = \sum_k z_k \log\big(\pi_k\, \mathcal N(x \mid \mu_k, \Sigma_k)\big), which is why plugging in the responsibilities works there. In the PCA model below it is quadratic in zz, and the average needs E[zz⊤]\mathbb E[z z^\top], which contains the posterior covariance of zz.

A prior on the parameters gives MAP-EM. The log posterior of the parameters is log⁡p(θ∣X)=log⁡p(X∣θ)+log⁡p(θ)−log⁡p(X)\log p(\theta \mid X) = \log p(X \mid \theta) + \log p(\theta) - \log p(X), and the last term does not depend on θ\theta. Adding log⁡p(θ)\log p(\theta) to both sides of the decomposition,

log⁡p(θ∣X)+log⁡p(X)=L(q,θ)+log⁡p(θ)+DKL(q ∥ p(Z∣X,θ)).\begin{aligned} \log p(\theta \mid X) + \log p(X) ={}& \mathcal L(q, \theta) + \log p(\theta) \\ &+ D_{\mathrm{KL}}\big(q \,\|\, p(Z \mid X, \theta)\big) . \end{aligned}

The E-step is unchanged. The M-step maximizes Eq[log⁡p(X,Z∣θ)]+log⁡p(θ)\mathbb E_q[\log p(X, Z \mid \theta)] + \log p(\theta), and the same argument shows that the log posterior never decreases. A prior on the covariances of a Gaussian mixture, one of the defences against collapsing components, works this way: it turns the M-step into a regularized fit.

The roles can also be swapped. Make the weights of a linear model the latent variable and the prior precisions the parameters, and EM maximizes the evidence over the precisions. For the relevance vector machine this gives the update αi=1/(μi2+Σii)\alpha_i = 1/(\mu_i^2 + \Sigma_{ii}), which the RVM note compares with MacKay’s fixed point.

Neither step has to be solved exactly. A generalized EM only increases L\mathcal L in the M-step, for example by a few gradient steps or by maximizing over one group of parameters at a time, and each cycle still increases the likelihood. The E-step can be partial too: an incremental EM recomputes the posterior of one data point at a time and updates the sufficient statistics of the M-step accordingly (Neal and Hinton, 1998; Bishop, 2006, Section 9.4). What matters is that every step raises the bound.

EM for crowd labels#

Training labels are often bought on crowdsourcing platforms: each image goes to a few annotators, and their answers disagree. A majority vote treats every annotator as equally reliable and every image as equally hard. Whitehill et al. (2009) model both, in a model they call GLAD, for generative model of labels, abilities and difficulties. EM fits it, with the true labels as the latent variables and the abilities and difficulties as parameters.

Item i=1,…,ni = 1, \dots, n has an unknown true label zi∈{0,1}z_i \in \{0, 1\} and an easiness bi>0b_i > 0; its difficulty is 1/bi1/b_i. Annotator j=1,…,mj = 1, \dots, m has a skill aj∈Ra_j \in \mathbb R. The label lijl_{ij} that annotator jj gives item ii is correct with probability

p(lij=zi∣zi,aj,bi)=σ(ajbi)=11+e−ajbi.p(l_{ij} = z_i \mid z_i, a_j, b_i) = \sigma(a_j b_i) = \frac{1}{1 + e^{-a_j b_i}} .

The paper writes α\alpha and β\beta; in this course those letters are precisions. A skill of 0 is a coin flip, and a negative skill belongs to an annotator who tends to give the wrong label, by malice or by misunderstanding. An item with bi→0b_i \to 0 is a coin flip for everyone. The labels are independent given the true label, and an annotator need not label every item: write JiJ_i for those who labelled item ii.

The E-step is a weighted vote. By Bayes’ formula with the prior p(zi=1)=1/2p(z_i = 1) = 1/2, the posterior log-odds of the true label is the sum of the log-likelihood ratios of its labels, since they are independent given ziz_i. A label lij=1l_{ij} = 1 is correct under zi=1z_i = 1 and wrong under zi=0z_i = 0, so it contributes log⁡σ(ajbi)−log⁡σ(−ajbi)\log \sigma(a_j b_i) - \log \sigma(-a_j b_i); a label lij=0l_{ij} = 0 contributes the negative. Finally σ(x)/σ(−x)=(1+ex)/(1+e−x)=ex\sigma(x)/\sigma(-x) = (1 + e^{x})/(1 + e^{-x}) = e^x:

log⁡p(zi=1∣l,a,b)p(zi=0∣l,a,b)=∑j∈Ji(2lij−1)log⁡σ(ajbi)σ(−ajbi)=bi∑j∈Jiaj (2lij−1).\begin{aligned} \log \frac{p(z_i = 1 \mid l, a, b)}{p(z_i = 0 \mid l, a, b)} &= \sum_{j \in J_i} (2 l_{ij} - 1) \log \frac{\sigma(a_j b_i)}{\sigma(-a_j b_i)} \\ &= b_i \sum_{j \in J_i} a_j\, (2 l_{ij} - 1) . \end{aligned}

Each label votes +1+1 or −1-1 with the weight of its annotator’s skill. With equal skills this is the majority vote, and an annotator with a negative skill votes for the opposite of what they said. The easiness multiplies the whole sum: it changes how confident the posterior is, never which side wins.

A prior that is not uniform, p(zi=1)=πp(z_i = 1) = \pi, adds one factor to Bayes’ formula: the posterior odds are the prior odds π/(1−π)\pi / (1 - \pi) times the likelihood ratio, so

log⁡p(zi=1∣l,a,b)p(zi=0∣l,a,b)=log⁡π1−π+bi∑j∈Jiaj (2lij−1).\begin{aligned} \log \frac{p(z_i = 1 \mid l, a, b)}{p(z_i = 0 \mid l, a, b)} &= \log \frac{\pi}{1 - \pi} \\ &\quad + b_i \sum_{j \in J_i} a_j\, (2 l_{ij} - 1) . \end{aligned}

The prior casts a vote of fixed weight for the more common class, the same for every item, and vanishes at π=12\pi = \frac12.

For the M-step, let cijc_{ij} be the posterior probability that label lijl_{ij} is correct, qi(zi=lij)q_i(z_i = l_{ij}). The complete-data log-likelihood is a sum over labels of log⁡σ(ajbi)\log \sigma(a_j b_i) for a correct label and log⁡σ(−ajbi)\log \sigma(-a_j b_i) for a wrong one. Its expectation under qq replaces the indicator of a correct label by cijc_{ij}:

Q(a,b)=∑i∑j∈Ji[cijlog⁡σ(ajbi)+(1−cij)log⁡σ(−ajbi)]+const.\begin{aligned} Q(a, b) = \sum_{i} \sum_{j \in J_i} \Big[&c_{ij} \log \sigma(a_j b_i) \\ &+ (1 - c_{ij}) \log \sigma(-a_j b_i)\Big] + \text{const} . \end{aligned}

Since log⁡σ(x)=−log⁡(1+e−x)\log \sigma(x) = -\log(1 + e^{-x}), its derivative is e−x/(1+e−x)=σ(−x)e^{-x}/(1 + e^{-x}) = \sigma(-x), and that of log⁡σ(−x)\log\sigma(-x) is −σ(x)-\sigma(x). With σ(x)+σ(−x)=1\sigma(x) + \sigma(-x) = 1, each term has the derivative cij σ(−x)−(1−cij) σ(x)=cij−σ(x)c_{ij}\,\sigma(-x) - (1 - c_{ij})\,\sigma(x) = c_{ij} - \sigma(x) with respect to x=ajbix = a_j b_i, and the chain rule gives

∂Q∂aj=∑i: j∈Jibi(cij−σ(ajbi)),∂Q∂bi=∑j∈Jiaj(cij−σ(ajbi)).\begin{aligned} \frac{\partial Q}{\partial a_j} &= \sum_{i:\, j \in J_i} b_i \big(c_{ij} - \sigma(a_j b_i)\big), \\ \frac{\partial Q}{\partial b_i} &= \sum_{j \in J_i} a_j \big(c_{ij} - \sigma(a_j b_i)\big) . \end{aligned}

This is the gradient of a logistic regression: observed minus predicted probability of a correct label. There is no closed form, so the M-step takes a few gradient steps, a generalized EM. Whitehill et al. add the priors aj∼N(1,1)a_j \sim \mathcal N(1, 1) and log⁡bi∼N(1,1)\log b_i \sim \mathcal N(1, 1), which keeps bib_i positive and turns the method into MAP-EM.

Worked example. Take 1000 items, each labelled by 3 of 7 annotators chosen at random, with skills (3,2,1.5,1,0.5,0,−1)(3, 2, 1.5, 1, 0.5, 0, -1): experts, average annotators, a guesser and an adversary. The easiness is eN(1,1)e^{\mathcal N(1, 1)}, as in the paper’s simulations. EM starts from equal skills, so its first E-step is the majority vote:

majority voteGLAD, 24 EM iterations
wrong labels of 100013361
skillsequal(1.45,1.40,1.43,1.13,0.83,0.09,−1.03)(1.45, 1.40, 1.43, 1.13, 0.83, 0.09, -1.03)

GLAD fixes 91 items on which the majority was wrong and breaks 19 on which it was right. It finds the guesser and the adversary, whose votes now count reversed, but with three labels per item it does not separate the three best annotators.

Two symmetries show what the priors do. Changing the sign of every skill and flipping every true label leaves the likelihood unchanged: every correct label becomes wrong, and σ(ajbi)\sigma(a_j b_i) and σ(−ajbi)\sigma(-a_j b_i) swap places, so each factor stays the same. Doubling the skills while halving the easiness leaves every product ajbia_j b_i, and so the likelihood, unchanged. Only the prior mean of 1 on aja_j says that annotators are mostly helpful and fixes the scale.

A model with skills alone, every bi=1b_i = 1, also makes 61 errors on these data. Given the skills, the easiness never changes the winner of a vote; it acts through the M-step, where the gradient in aja_j weights item ii by bib_i, so hard items count less. Here the two fits find nearly proportional skills, (3.14,3.06,3.08,2.20,1.52,0.11,−2.01)(3.14, 3.06, 3.08, 2.20, 1.52, 0.11, -2.01) without the easiness, and the votes come out alike. Whitehill et al. found that this pays when half the items are hard: 4.5% errors against 8.4% for an EM model of skills alone and 11.2% for the majority vote.

Variational EM: when the E-step cannot be exact#

The exact E-step needs the posterior p(Z∣X,θ)p(Z \mid X, \theta). For a mixture it is a table of responsibilities. For most models with many interacting latent variables it is a distribution over exponentially many configurations, or a continuous density with no closed form. Variational EM (Neal and Hinton, 1998) keeps the bound and restricts the E-step to a family Q\mathcal Q of distributions it can handle:

qt+1=arg⁡max⁡q∈Q L(q,θt)=arg⁡min⁡q∈Q DKL(q ∥ p(Z∣X,θt)),θt+1=arg⁡max⁡θ L(qt+1,θ).\begin{aligned} q^{t+1} &= \arg\max_{q \in \mathcal Q}\, \mathcal L(q, \theta^t) \\ &= \arg\min_{q \in \mathcal Q}\, D_{\mathrm{KL}}\big(q \,\|\, p(Z \mid X, \theta^t)\big), \\ \theta^{t+1} &= \arg\max_\theta\, \mathcal L(q^{t+1}, \theta) . \end{aligned}

The two forms of the E-step are the same problem, because log⁡p(X∣θt)\log p(X \mid \theta^t) does not depend on qq. Each step still increases L\mathcal L, so the bound never decreases. What is lost is the tightness after the E-step: the gap is the smallest KL divergence within Q\mathcal Q, which is positive unless Q\mathcal Q contains the posterior. Write ℓ(θ)=log⁡p(X∣θ)\ell(\theta) = \log p(X \mid \theta). The monotonicity chain of exact EM is

ℓ(θt+1)≥L(qt+1,θt+1)≥L(qt+1,θt)=ℓ(θt),\ell(\theta^{t+1}) \ge \mathcal L(q^{t+1}, \theta^{t+1}) \ge \mathcal L(q^{t+1}, \theta^t) = \ell(\theta^t) ,

and with a restricted qq its last link becomes ≤\le. The log-likelihood can go down, and the fixed point maximizes the bound rather than the likelihood. The bound is the likelihood minus a gap that depends on θ\theta, so its maximizer is pulled towards parameters at which the posterior is easy to approximate by a member of Q\mathcal Q, a bias that can be large (Turner and Sahani, 2011).

Worked example: hard EM is variational EM. Take Q\mathcal Q to be the point masses, qi(zi)=[zi=z^i]q_i(z_i) = [z_i = \hat z_i]. The entropy of a point mass is zero, so L=∑ilog⁡p(xi,z^i∣θ)\mathcal L = \sum_i \log p(x_i, \hat z_i \mid \theta), maximized by giving each point its most probable component. The gap for one point is

DKL(qi ∥ p(zi∣xi,θ))=∑z[z=z^i]log⁡[z=z^i]p(z∣xi,θ)=−log⁡p(z^i∣xi,θ).\begin{aligned} &D_{\mathrm{KL}}\big(q_i \,\|\, p(z_i \mid x_i, \theta)\big) \\ &\quad= \sum_{z} [z = \hat z_i] \log \frac{[z = \hat z_i]}{p(z \mid x_i, \theta)} \\ &\quad= -\log p(\hat z_i \mid x_i, \theta) . \end{aligned}

This E-step is the assignment step of k-means and of the hard EM of the EM note, which therefore minimizes the same KL divergence over the narrowest family, point masses on the assignments (Vetrov and Kropotov, lecture 7). Take that note’s toy model, the mixture 12N(0,1)+12N(θ,1)\tfrac12 \mathcal N(0, 1) + \tfrac12 \mathcal N(\theta, 1) on seven points, and start at θ0=0.6\theta_0 = 0.6. The first three points go to the first component and the last four to the second:

xix_i−0.8-0.8−0.2-0.20.30.30.90.92.12.12.82.83.43.4
p(z^i∣xi,θ0)p(\hat z_i \mid x_i, \theta_0)0.6590.6590.5740.5740.5000.5000.5890.5890.7460.7460.8180.8180.8650.865
gap −log⁡p(z^i∣xi,θ0)-\log p(\hat z_i \mid x_i, \theta_0)0.4170.4170.5540.5540.6930.6930.5290.5290.2920.2920.2010.2010.1450.145

The gaps add up to 2.832.83. The M-step moves θ\theta to the mean of the four points, 2.3002.300, where the log-likelihood is −12.06-12.06 and the next E-step leaves a gap of 0.770.77. Hard EM converges to θ=2.767\theta = 2.767 with ℓ=−12.05\ell = -12.05 and a gap of 0.450.45. Exact EM converges to the maximum likelihood estimate θ=2.540\theta = 2.540 with ℓ=−12.00\ell = -12.00 and no gap. Hard EM even climbs faster at first, −12.06-12.06 against −12.83-12.83 after one M-step, and still stops at the wrong place. It maximizes its own bound, which at θ=2.767\theta = 2.767 is −12.50-12.50, higher than its value −12.57-12.57 at the maximum likelihood estimate.

Figure

An exact and a restricted E-step: ℓ = L + KL

An exact and a restricted E-step: ℓ = L + KLFour pairs of vertical segments. On each segment the top tick is the log-likelihood and the bottom dot the lower bound; the length of the segment is the KL gap. For exact EM the gap is zero after every E-step; for hard EM it stays positive: 2.83, 1.34, 0.77, 0.45.q = exact posterior (EM)q = point mass (hard EM)tick: ℓ(θ), dot: L(q, θ)−20−18−16−14−120.002.831E-step1.101.342M-step0.000.773E-step0.000.454convergedAn exact and a restricted E-step: ℓ = L + KLFour pairs of vertical segments. On each segment the top tick is the log-likelihood and the bottom dot the lower bound; the length of the segment is the KL gap. For exact EM the gap is zero after every E-step; for hard EM it stays positive: 2.83, 1.34, 0.77, 0.45.q = exact posterior (EM)q = point mass (hard EM)tick: ℓ(θ), dot: L(q, θ)−20−18−16−14−121E-step2M-step3E-step4converged
The mixture ½ N(0, 1) + ½ N(θ, 1) on seven points, both runs started at θ₀ = 0.6. Tick: the log-likelihood ℓ(θ); dot: the bound L(q, θ); the segment between them: the KL gap. Blue: exact EM closes the gap at every E-step. Amber: hard EM, with q a point mass, leaves gaps of 2.83, 1.34, 0.77, 0.45 and stops at θ = 2.767 instead of 2.540.

Point masses are the crudest family. The next note uses factorized distributions, q(Z)=∏jqj(Zj)q(Z) = \prod_j q_j(Z_j), for which the E-step has a closed-form coordinate update. It also lets qq cover the parameters, so that the M-step disappears and the whole posterior is approximated (Beal, 2003).

Bayesian PCA: a precision for every column#

Bayesian PCA (Bishop, 1999a) keeps probabilistic PCA and adds a prior on the loadings with one precision αj\alpha_j per column:

p(W∣α)=∏j=1kN(wj∣0, αj−1Id),k=d−1.\begin{aligned} p(W \mid \alpha) &= \prod_{j=1}^{k} \mathcal N\big(w_j \mid 0,\ \alpha_j^{-1} I_d\big), \\ k &= d - 1 . \end{aligned}

This is automatic relevance determination applied to latent dimensions instead of input features. A large αj\alpha_j forces column wjw_j towards zero, and a zero column removes latent dimension jj from the model, since WzW z no longer depends on zjz_j. k=d−1k = d - 1 is as many columns as can be useful: with all of them kept, WW⊤+σ2IW W^\top + \sigma^2 I can already represent any covariance matrix. Take σ2\sigma^2 equal to its smallest eigenvalue λd\lambda_d, and as columns the other d−1d - 1 eigenvectors vjv_j scaled to λj−λd vj\sqrt{\lambda_j - \lambda_d}\, v_j (Bishop, 2006, Section 12.2.3).

The ideal would be to choose α\alpha and σ2\sigma^2 by maximizing the evidence p(X∣α,σ2)=∫p(X∣W,σ2) p(W∣α) dWp(X \mid \alpha, \sigma^2) = \int p(X \mid W, \sigma^2)\, p(W \mid \alpha)\, dW. But WW enters the covariance of xx quadratically, and the integral has no closed form. Bishop’s scheme, also the one of Vetrov and Kropotov, approximates it in the spirit of the Laplace approximation and alternates two steps:

  1. with α\alpha fixed, find the MAP estimate of WW and σ2\sigma^2 by MAP-EM, with the codes ziz_i as latent variables;
  2. with WW fixed, set αj=d/∥wj∥2\alpha_j = d / \lVert w_j \rVert^2.

The second update is the evidence fixed point of the relevance vector machine, αj=γj/∥wj∥2\alpha_j = \gamma_j / \lVert w_j \rVert^2, applied to a whole column of dd entries, each of them counted as well determined by the data, so that γj=d\gamma_j = d. It is also the value of αj\alpha_j that maximizes log⁡p(wj∣αj)=d2log⁡αj−αj2∥wj∥2\log p(w_j \mid \alpha_j) = \frac d2 \log \alpha_j - \frac{\alpha_j}{2} \lVert w_j \rVert^2 at the current wjw_j.

The E-step is exact, because ziz_i and xix_i are jointly Gaussian. Keep the terms of log⁡p(xi,zi)\log p(x_i, z_i) that contain ziz_i and complete the square:

log⁡p(zi∣xi)=−12zi⊤zi−∥xi−Wzi∥22σ2+const=−12zi⊤Mσ2zi+zi⊤W⊤xiσ2+const.\begin{aligned} \log p(z_i \mid x_i) &= -\tfrac12 z_i^\top z_i - \frac{\lVert x_i - W z_i \rVert^2}{2\sigma^2} + \text{const} \\ &= -\tfrac12 z_i^\top \frac{M}{\sigma^2} z_i + z_i^\top \frac{W^\top x_i}{\sigma^2} + \text{const} . \end{aligned}

The precision is M/σ2M/\sigma^2, the mean is the precision’s inverse times the linear term, and E[zz⊤]\mathbb E[z z^\top] is the covariance plus the outer product of the mean:

M=W⊤W+σ2Ik,E[zi]=M−1W⊤xi,E[zizi⊤]=σ2M−1+E[zi] E[zi]⊤.\begin{aligned} M &= W^\top W + \sigma^2 I_k, \\ \mathbb E[z_i] &= M^{-1} W^\top x_i, \\ \mathbb E[z_i z_i^\top] &= \sigma^2 M^{-1} + \mathbb E[z_i]\, \mathbb E[z_i]^\top . \end{aligned}

The M-step maximizes ∑iE[log⁡p(xi∣zi,W,σ2)]+log⁡p(W∣α)\sum_i \mathbb E\big[\log p(x_i \mid z_i, W, \sigma^2)\big] + \log p(W \mid \alpha). The terms with WW are −12σ2∑iE∥xi−Wzi∥2−12∑jαj∥wj∥2-\frac{1}{2\sigma^2} \sum_i \mathbb E\lVert x_i - W z_i \rVert^2 - \frac12 \sum_j \alpha_j \lVert w_j \rVert^2. Write A=diag⁡(α1,…,αk)A = \operatorname{diag}(\alpha_1, \dots, \alpha_k) and collect the two sums of E-step statistics,

G=∑ixi E[zi]⊤,R=∑iE[zizi⊤].\begin{aligned} G &= \sum_i x_i\, \mathbb E[z_i]^\top, \\ R &= \sum_i \mathbb E[z_i z_i^\top] . \end{aligned}

Expand E∥x−Wz∥2=∥x∥2−2 E[z]⊤W⊤x+tr⁡(E[zz⊤]W⊤W)\mathbb E\lVert x - W z \rVert^2 = \lVert x \rVert^2 - 2\, \mathbb E[z]^\top W^\top x + \operatorname{tr}\big(\mathbb E[z z^\top] W^\top W\big). By the trace rules, the gradient in WW of E[z]⊤W⊤x\mathbb E[z]^\top W^\top x is x E[z]⊤x\, \mathbb E[z]^\top and that of tr⁡(R W⊤W)\operatorname{tr}(R\, W^\top W), for a symmetric RR, is 2WR2 W R; the prior term gives −WA-W A. Summed over the points, the gradient and its zero are

0=1σ2(G−WR)−WA⟹G=W(R+σ2A)⟹W=G(R+σ2A)−1.\begin{aligned} 0 &= \frac{1}{\sigma^2} \big(G - W R\big) - W A \\ \Longrightarrow\quad G &= W \big(R + \sigma^2 A\big) \\ \Longrightarrow\quad W &= G \big(R + \sigma^2 A\big)^{-1} . \end{aligned}

With A=0A = 0 this is the EM algorithm for probabilistic PCA (Tipping and Bishop, 1999); the prior adds σ2A\sigma^2 A, a ridge penalty of its own size for every column. The prior does not involve the noise variance. Setting the derivative of −nd2log⁡σ2−12σ2∑iE∥xi−Wzi∥2-\frac{nd}{2} \log \sigma^2 - \frac{1}{2\sigma^2} \sum_i \mathbb E\lVert x_i - W z_i \rVert^2 to zero, with the new WW, gives

σ2=1nd∑i=1n(∥xi∥2−2 E[zi]⊤W⊤xi+tr⁡(E[zizi⊤] W⊤W)).\begin{aligned} \sigma^2 = \frac{1}{nd} \sum_{i=1}^n \Big(&\lVert x_i \rVert^2 - 2\, \mathbb E[z_i]^\top W^\top x_i \\ &+ \operatorname{tr}\big(\mathbb E[z_i z_i^\top]\, W^\top W\big)\Big) . \end{aligned}

Both updates use RR, the sum of E[zizi⊤]=σ2M−1+E[zi] E[zi]⊤\mathbb E[z_i z_i^\top] = \sigma^2 M^{-1} + \mathbb E[z_i]\, \mathbb E[z_i]^\top. Replacing it by the outer products of the means alone drops the posterior covariance of the codes, treats them as known, and gives a different algorithm. In the Code section, on the data of the opening with k=3k = 3 and A=0A = 0, EM converges to σ2=0.971\sigma^2 = 0.971 and the maximum likelihood lengths λj−σ2\sqrt{\lambda_j - \sigma^2}. The variant settles at σ2=0.679\sigma^2 = 0.679, and its columns grow without bound, to lengths of about 165 after 20,000 iterations.

Why the columns grow

Follow one eigenvector of SS with eigenvalue λ\lambda and a column of length ww along it. With xix_i the coordinates of the points along it, ∑ixi2=nλ\sum_i x_i^2 = n\lambda, and the mean codes are mi=wxi/(w2+σ2)m_i = w x_i / (w^2 + \sigma^2). The variant’s M-step regresses the xix_i on these means:

w′=∑iximi∑imi2=w nλw2+σ2⋅(w2+σ2)2w2 nλ=w+σ2w.\begin{aligned} w' &= \frac{\sum_i x_i m_i}{\sum_i m_i^2} \\ &= \frac{w\, n\lambda}{w^2 + \sigma^2} \cdot \frac{(w^2 + \sigma^2)^2}{w^2\, n\lambda} \\ &= w + \frac{\sigma^2}{w} . \end{aligned}

So w′2=w2+2σ2+σ4/w2w'^2 = w^2 + 2\sigma^2 + \sigma^4 / w^2, and w2w^2 grows by more than 2σ22\sigma^2 in every iteration: by more than 27,00027{,}000 over 20,00020{,}000 iterations with σ2=0.679\sigma^2 = 0.679, a length of about 165. With the posterior variance σ2/(w2+σ2)\sigma^2 / (w^2 + \sigma^2) of each code, the denominator gains nσ2/(w2+σ2)n\sigma^2 / (w^2 + \sigma^2), and the fixed point w′=ww' = w becomes λ=w2λ/(w2+σ2)+σ2\lambda = w^2 \lambda / (w^2 + \sigma^2) + \sigma^2, that is w2=λ−σ2w^2 = \lambda - \sigma^2.

The update divides by ndnd, while the closed form of the first section averages d−kd - k eigenvalues. At the maximum likelihood solution (A=0A = 0) they agree, because there each kept direction contributes nσ2n\sigma^2 to the expected residual and each discarded one nλjn\lambda_j:

nd σ2=∑i=1nE∥xi−Wzi∥2=nkσ2+n∑j>kλj  ⟺  σ2=1d−k∑j>kλj.\begin{aligned} nd\, \sigma^2 &= \sum_{i=1}^n \mathbb E\lVert x_i - W z_i \rVert^2 \\ &= n k \sigma^2 + n \sum_{j > k} \lambda_j \\ \iff\quad \sigma^2 &= \frac{1}{d - k} \sum_{j > k} \lambda_j . \end{aligned}

EM averages over all ndnd coordinates, and the posterior uncertainty of the codes puts σ2\sigma^2 of residual into each kept direction; the closed form has already eliminated WW and keeps only the d−kd - k directions that carry nothing but noise. The Code section’s EM with k=3k = 3 reaches 0.9710.971, the average of the seven discarded eigenvalues.

Why a kept direction contributes nσ²

With E[zz⊤]=σ2M−1+E[z] E[z]⊤\mathbb E[z z^\top] = \sigma^2 M^{-1} + \mathbb E[z]\, \mathbb E[z]^\top, the expansion of E∥x−Wz∥2\mathbb E\lVert x - W z \rVert^2 above becomes ∥x−W E[z]∥2+tr⁡(σ2M−1W⊤W)\lVert x - W\, \mathbb E[z] \rVert^2 + \operatorname{tr}(\sigma^2 M^{-1} W^\top W). Take the solution with orthogonal columns wj=λj−σ2 ujw_j = \sqrt{\lambda_j - \sigma^2}\, u_j along the eigenvectors uju_j; a rotation RR changes neither term. Then W⊤WW^\top W is diagonal with entries λj−σ2\lambda_j - \sigma^2 and MM diagonal with entries λj\lambda_j. Along uju_j the fitted mean W E[zi]W\, \mathbb E[z_i] has the coordinate (λj−σ2)xij/λj(\lambda_j - \sigma^2) x_{ij} / \lambda_j, where xij=uj⊤xix_{ij} = u_j^\top x_i and ∑ixij2=nλj\sum_i x_{ij}^2 = n\lambda_j. Summed over the points,

residual=∑i=1n(σ2λj xij)2=nσ4λj,trace part=nσ2 λj−σ2λj,sum=nσ2(σ2+λj−σ2)λj=nσ2.\begin{aligned} \text{residual} &= \sum_{i=1}^n \Big(\frac{\sigma^2}{\lambda_j}\, x_{ij}\Big)^2 = \frac{n\sigma^4}{\lambda_j}, \\ \text{trace part} &= n\sigma^2\, \frac{\lambda_j - \sigma^2}{\lambda_j}, \\ \text{sum} &= \frac{n\sigma^2 (\sigma^2 + \lambda_j - \sigma^2)}{\lambda_j} = n\sigma^2 . \end{aligned}

A discarded direction has no component of WW, so its whole energy ∑ixij2=nλj\sum_i x_{ij}^2 = n\lambda_j stays in the residual.

One iteration costs O(ndk+k3)O(ndk + k^3) and never forms the d×dd \times d covariance, which makes EM cheaper than an eigendecomposition when dd is large and kk small. EM for probabilistic PCA also handles values missing at random: the E-step then averages over the missing coordinates as well as over the codes (Bishop, 2006, Section 12.2.2).

Why a column switches off#

Take a fixed point at which the kept columns are orthogonal and lie along eigenvectors of SS. EM reaches such a point here: in the Code section the largest principal angle between the kept columns and the three leading eigenvectors is below 0.01°0.01°. Then C=WW⊤+σ2IC = W W^\top + \sigma^2 I has the eigenvectors of SS. Along the eigenvector of column jj, with eigenvalue λ\lambda of SS and u=∥wj∥2u = \lVert w_j \rVert^2, CC has the eigenvalue c=u+σ2c = u + \sigma^2, and as in the maximum likelihood solution above the log-likelihood splits into one term per direction. The MAP objective for uu and its stationary point are

f(u)=−n2(log⁡c+λc)−αj2 u,f′(u)=0  ⟺  αj=n(λ−c)c2.\begin{aligned} f(u) &= -\frac n2 \Big(\log c + \frac{\lambda}{c}\Big) - \frac{\alpha_j}{2}\, u, \\ f'(u) = 0 \iff \alpha_j &= \frac{n(\lambda - c)}{c^2} . \end{aligned}

Substituting the precision update αj=d/u\alpha_j = d/u and c=u+σ2c = u + \sigma^2, then expanding both sides and collecting powers of uu:

n(λ−σ2−u) u=d (u+σ2)2(n+d) u2−[n(λ−σ2)−2dσ2] u+dσ4=0.\begin{aligned} n(\lambda - \sigma^2 - u)\, u &= d\,(u + \sigma^2)^2 \\ (n + d)\, u^2 - \big[n(\lambda - \sigma^2) - 2d\sigma^2\big]\, u + d\sigma^4 &= 0 . \end{aligned}

The product of the roots, dσ4/(n+d)d\sigma^4/(n + d), is positive, so both roots have the same sign, that of their sum, the bracket divided by n+dn + d. The roots are real when the discriminant is non-negative. So a positive root exists only if the bracket is positive and its square is at least 4(n+d) dσ44(n + d)\, d\sigma^4, that is n(λ−σ2)−2dσ2≥2σ2d(n+d)n(\lambda - \sigma^2) - 2d\sigma^2 \ge 2\sigma^2\sqrt{d(n + d)}, or

  λσ2  ≥  1+2(d+d(n+d))n  \boxed{\;\frac{\lambda}{\sigma^2} \;\ge\; 1 + \frac{2\big(d + \sqrt{d(n + d)}\big)}{n}\;}

Below the threshold the only fixed point is wj=0w_j = 0 with αj=∞\alpha_j = \infty: the column is switched off. Maximum likelihood keeps a direction whenever λ>σ2\lambda > \sigma^2. The prior asks for extra evidence that shrinks as nn grows, about 2d/n2\sqrt{d/n} in relative terms when n≫dn \gg d. Above the threshold the larger root is the squared length u=∥wj∥2u = \lVert w_j \rVert^2 that EM reaches here. It is smaller than the maximum likelihood value λ−σ2\lambda - \sigma^2, because it is below the sum of the roots, [n(λ−σ2)−2dσ2]/(n+d)\big[n(\lambda - \sigma^2) - 2d\sigma^2\big]/(n + d).

Worked example. Return to the data of the opening, with n=100n = 100 and d=10d = 10. Bayesian PCA with k=9k = 9 columns removes six of them, at EM iterations 5555, 6767, 7676, 124124, 217217 and 218218 (a column is removed when αj\alpha_j exceeds 10810^8), and ends with σ2=0.977\sigma^2 = 0.977, close to the true noise variance. The threshold and the third column are

QuantityValue
threshold on λ/σ2\lambda/\sigma^21+2(10+1100)/100=1.8631 + 2(10 + \sqrt{1100})/100 = 1.863
threshold on λ\lambda1.863⋅0.977=1.821.863 \cdot 0.977 = 1.82
quadratic for λ3=4.45\lambda_3 = 4.45110 u2−327.8 u+9.545=0110\, u^2 - 327.8\, u + 9.545 = 0
larger root, ∥w3∥\lVert w_3 \rVertu=2.950u = 2.950, ∥w3∥=1.717\lVert w_3 \rVert = 1.717
maximum likelihood, λ3−σ2\sqrt{\lambda_3 - \sigma^2}1.861.86

The third eigenvalue, 4.454.45, is above the threshold and the fourth, 1.521.52, below it, so exactly three columns survive. The length of the third is the one EM finds. The other two kept columns have lengths 7.4507.450 and 3.1363.136, again the larger roots of their quadratics, and α=(0.180,1.017,3.391)\alpha = (0.180, 1.017, 3.391).

Figure

Bayesian PCA switches off the columns it does not need

Bayesian PCA switches off the columns it does not needLeft: nine pairs of bars; maximum likelihood has all nine norms positive, Bayesian PCA only three. Right: nine curves of column norms over the EM iterations; six fall to zero, three level off.column norms ‖wⱼ‖, sorted0246810123456789columnmaximum likelihood, k = 9Bayesian PCA, k = 9‖wⱼ‖ during EM (log scale)02468101101001000EM iteration3 columns kept6 columns switched offBayesian PCA switches off the columns it does not needLeft: nine pairs of bars; maximum likelihood has all nine norms positive, Bayesian PCA only three. Right: nine curves of column norms over the EM iterations; six fall to zero, three level off.column norms ‖wⱼ‖, sorted0246810123456789columnmaximum likelihood, k = 9Bayesian PCA, k = 9‖wⱼ‖ during EM (log scale)02468101101001000EM iteration3 columns kept6 columns switched off
100 points in d = 10 dimensions from a model with three latent dimensions and unit noise; both fits get k = 9 columns. Left: maximum likelihood (grey) uses all nine, Bayesian PCA (red) keeps three. Right: the column norms over the EM iterations; six fall to zero by iteration 331, and three level off at the roots of the fixed-point equation.

The figure repeats the experiment on a second sample drawn the same way, with new loadings and new points. Six columns are removed between iterations 22 and 331.

Where it breaks#

The figure also shows the first failure: EM for Bayesian PCA is cheap per iteration and slow to converge. Pruning is fast, but the three surviving columns then turn slowly towards the eigenvectors, and only after a few thousand iterations do their lengths settle at the roots of the quadratic. When several columns sit near the threshold, the result after a fixed number of iterations depends on when one stops, and the starting point can decide which columns survive.

The second is that the evidence is only approximated. The update αj=d/∥wj∥2\alpha_j = d/\lVert w_j \rVert^2 treats every entry of a column as well determined and uses a point estimate of WW, so the threshold above is a property of this scheme. A variational treatment of the same model, with a factorized posterior over WW, zz and α\alpha, maximizes a true lower bound on the evidence instead (Bishop, 1999b).

The third is the bias of variational EM, worked out in the hard EM example. Its fixed points maximize a bound whose gap depends on the parameters, so the estimates move towards parameters with easy posteriors, 2.7672.767 instead of 2.5402.540 there. Comparing models by their bounds is worse still, because each bound carries its own unknown gap. Finally, the model is linear and Gaussian, like probabilistic PCA: it sees only second moments, and curved data need mixtures of probabilistic PCA or nonlinear models such as the VAE.

What you should remember#

  • log⁡p(X∣θ)=L(q,θ)+DKL(q ∥ p(Z∣X,θ))\log p(X \mid \theta) = \mathcal L(q, \theta) + D_{\mathrm{KL}}(q \,\|\, p(Z \mid X, \theta)) for every qq; EM is coordinate ascent on L\mathcal L.
  • A prior adds log⁡p(θ)\log p(\theta) to the M-step (MAP-EM); partial steps are fine if they raise L\mathcal L.
  • Crowd labels (GLAD): the E-step is a vote weighted by skill, the M-step a logistic-regression gradient; priors fix sign and scale.
  • Variational EM restricts qq; it raises the bound, the likelihood can fall, and its fixed point is biased. Hard EM is the point-mass case.
  • Bayesian PCA: one precision per column, M-step W=G(R+σ2A)−1W = G(R + \sigma^2 A)^{-1}, then αj=d/∥wj∥2\alpha_j = d/\lVert w_j \rVert^2.
  • A direction survives only if λ/σ2≥1+2(d+d(n+d))/n\lambda/\sigma^2 \ge 1 + 2(d + \sqrt{d(n + d)})/n.

Code#

Exact and hard EM on the seven-point mixture, the decomposition log⁡p=L+DKL\log p = \mathcal L + D_{\mathrm{KL}} for an arbitrary qq, maximum likelihood probabilistic PCA for every kk and with a fixed noise variance, Bayesian PCA by EM with the fixed-point check of the text, and EM for probabilistic PCA with and without the posterior covariance of the codes. NumPy and SciPy only; seeds are fixed, and exact numbers can differ slightly across platforms and library versions. The script runs in about two seconds.

import numpy as np
from scipy.stats import norm
from scipy.linalg import subspace_angles

# the seven-point mixture 0.5 N(0, 1) + 0.5 N(theta, 1): exact EM and variational EM with point masses (hard EM)
x = np.array([-0.8, -0.2, 0.3, 0.9, 2.1, 2.8, 3.4])
loglik = lambda th: float(np.log(0.5 * norm.pdf(x) + 0.5 * norm.pdf(x - th)).sum())
def bound(th, q):                        # L(q, theta), q = probability of the second component for each point
    with np.errstate(divide='ignore', invalid='ignore'):
        a = np.where(q < 1, (1 - q) * np.log(0.5 * norm.pdf(x) / (1 - q)), 0.0)
        b = np.where(q > 0, q * np.log(0.5 * norm.pdf(x - th) / q), 0.0)
    return float((a + b).sum())
exact = lambda th: norm.pdf(x - th) / (norm.pdf(x) + norm.pdf(x - th))   # E-step: the posterior
hard = lambda th: (np.abs(x - th) < np.abs(x)).astype(float)             # E-step restricted to point masses
r0, h0 = exact(0.6), hard(0.6)
print(np.where(h0 == 1, r0, 1 - r0).round(3), round(loglik(0.6) - bound(0.6, h0), 2))
# [0.659 0.574 0.5   0.589 0.746 0.818 0.865] 2.83: the probability of the chosen component, and the gap
for name, estep in (('exact', exact), ('hard', hard)):
    th, out = 0.6, []
    for it in range(200):
        q = estep(th)
        if it < 2: out.append((round(float(th), 3), round(loglik(th), 2), round(bound(th, q), 2)))
        th = (q * x).sum() / q.sum()                                     # M-step: q-weighted mean
    q = estep(th)
    print(name, out, round(float(th), 3), round(loglik(th), 2), round(bound(th, q), 2))
# exact [(0.6, -16.35, -16.35), (1.662, -12.83, -12.83)] 2.54 -12.0 -12.0
# hard [(0.6, -16.35, -19.18), (2.3, -12.06, -12.82)] 2.767 -12.05 -12.5
print(round(bound(2.540, hard(2.540)), 2))                              # -12.57: the hard bound at the maximum likelihood estimate

# log p = L + KL holds for any q, not only for the posterior
rng = np.random.default_rng(1)
q = rng.uniform(size=7); r = exact(1.0)
kl = (q * np.log(q / r) + (1 - q) * np.log((1 - q) / (1 - r))).sum()
print(round(loglik(1.0), 6), round(bound(1.0, q) + kl, 6))           # -14.691242 -14.691242

# Bayesian PCA: 100 points in d = 10 dimensions from a model with three latent dimensions and unit noise
d, k, n = 10, 3, 100
W_true = rng.normal(size=(d, k)) * np.array([3.0, 2.0, 1.0])
X = rng.normal(size=(n, k)) @ W_true.T + rng.normal(size=(n, d))
X = X - X.mean(axis=0)
lam, V = np.linalg.eigh(X.T @ X / n); lam, V = lam[::-1], V[:, ::-1]
print(lam.round(2))
# [62.23 12.    4.45  1.52  1.35  1.18  0.89  0.84  0.63  0.39]

# maximum likelihood probabilistic PCA: the log-likelihood only grows with the number of columns
def ppca_loglik(q):
    s2 = lam[q:].mean(); c = np.concatenate([lam[:q], np.full(d - q, s2)])
    return -n / 2 * (d * np.log(2 * np.pi) + np.log(c).sum() + (lam / c).sum())
print([round(float(ppca_loglik(q)), 1) for q in range(1, 10)])
# [-2052.4, -1885.9, -1813.9, -1806.6, -1799.7, -1793.2, -1790.6, -1786.4, -1783.4]
s2 = lam[9:].mean(); print(round(float(s2), 3), np.sqrt(lam[:9] - s2).round(2))   # nine columns: every one is used
# 0.388 [7.86 3.41 2.02 1.07 0.98 0.89 0.71 0.67 0.49]
print(np.sqrt(np.maximum(lam[:9] - 1, 0)).round(2))                             # noise variance fixed at the true 1: lengths sqrt(max(lambda_j - 1, 0))
# [7.83 3.32 1.86 0.72 0.59 0.42 0.   0.   0.  ]

# EM for the MAP loadings with one ARD precision per column, alpha_j = d / ||w_j||^2; columns with alpha_j > 1e8 are removed
q = d - 1
W, s2, alpha = rng.normal(size=(d, q)), 1.0, np.ones(q)
active = np.arange(q); pruned = []
for it in range(1000):
    Wa = W[:, active]; m = len(active)
    Minv = np.linalg.inv(Wa.T @ Wa + s2 * np.eye(m))
    Ez = X @ Wa @ Minv                                   # E[z_i], n x m
    R = n * s2 * Minv + Ez.T @ Ez                        # sum_i E[z_i z_i^T]
    Wa = (X.T @ Ez) @ np.linalg.inv(R + s2 * np.diag(alpha[active]))   # W = G (R + s2 A)^-1
    s2 = (np.sum(X ** 2) - 2 * np.sum(Ez * (X @ Wa)) + np.trace(R @ Wa.T @ Wa)) / (n * d)
    W[:] = 0; W[:, active] = Wa
    alpha[active] = d / (Wa ** 2).sum(axis=0)
    for j in active[alpha[active] > 1e8]: pruned.append((j, it + 1))
    active = active[alpha[active] <= 1e8]
print(len(active), [it for _, it in pruned], round(float(s2), 3))
# 3 [55, 67, 76, 124, 217, 218] 0.977
print(np.sort(np.linalg.norm(W[:, active], axis=0))[::-1].round(3), np.sort(alpha[active]).round(3))
# [7.45  3.136 1.717] [0.18  1.017 3.391]
print(np.degrees(subspace_angles(W[:, active], V[:, :3])).max() < 0.01)   # True: the kept columns span the leading eigenvectors

# the fixed point of one column along an eigenvector with eigenvalue l: (n + d) u^2 - [n (l - s2) - 2 d s2] u + d s2^2 = 0, u = ||w||^2
B = n * (lam[:4] - s2) - 2 * d * s2; disc = B ** 2 - 4 * (n + d) * d * s2 ** 2
print(np.where(disc > 0, np.sqrt((B + np.sqrt(np.maximum(disc, 0))) / (2 * (n + d))), 0).round(3), round(float(1 + 2 * (d + np.sqrt(d * (n + d))) / n), 3))
# [7.45  3.136 1.717 0.   ] 1.863

# EM for probabilistic PCA (A = 0, k = 3) with R = sum_i E[z_i z_i^T], and with the outer products of the means alone
for full in (True, False):
    W, s2 = np.random.default_rng(0).normal(size=(d, 3)), 1.0
    for it in range(20000):
        Minv = np.linalg.inv(W.T @ W + s2 * np.eye(3)); Ez = X @ W @ Minv
        R = full * n * s2 * Minv + Ez.T @ Ez
        W = (X.T @ Ez) @ np.linalg.inv(R)
        s2 = (np.sum(X ** 2) - 2 * np.sum(Ez * (X @ W)) + np.trace(R @ W.T @ W)) / (n * d)
    print(full, round(float(s2), 3), np.sqrt(np.linalg.eigvalsh(W @ W.T)[::-1][:3]).round(1))
# True 0.971 [7.8 3.3 1.9]: the maximum likelihood solution, lengths sqrt(lambda_j - s2)
# False 0.679 [165.  164.9 164.9]: a different noise variance, and columns that keep growing
print(round(float(lam[3:].mean()), 3), round(float(lam[3:].sum() / d), 3))   # 0.971 0.679: the discarded eigenvalues averaged over d - k, and summed over d

EM for crowd labels: the simulation of the worked example, GLAD against the majority vote and against a model of skills alone, and the two symmetries of the likelihood. It runs in under a second.

import numpy as np
from scipy.optimize import minimize
from scipy.special import expit, log_expit

# EM for crowd labels (GLAD): annotator j labels item i correctly with probability sigmoid(a_j b_i)
rng = np.random.default_rng(0)
n, m = 1000, 7                                       # 1000 items, 7 annotators, 3 labels per item
a_true = np.array([3.0, 2.0, 1.5, 1.0, 0.5, 0.0, -1.0])   # skills: experts, average, a guesser, an adversary
b_true = np.exp(rng.normal(1, 1, n))                 # easiness b_i > 0; the difficulty is 1/b_i
z_true = rng.integers(0, 2, n)
item = np.repeat(np.arange(n), 3)
ann = np.concatenate([rng.choice(m, 3, replace=False) for _ in range(n)])
ok = rng.uniform(size=3 * n) < expit(a_true[ann] * b_true[item])
lab = np.where(ok, z_true[item], 1 - z_true[item])
vote = 2 * lab - 1                                   # +1 for class 1, -1 for class 0

def e_step(a, b):                                    # log-odds of z_i = 1 is the weighted vote sum_j a_j b_i (2 l_ij - 1)
    return expit(np.bincount(item, a[ann] * b[item] * vote, minlength=n))

def m_step(q, a, s, fit_b):
    """A few L-BFGS steps on Q(a, b) + log prior, a_j ~ N(1, 1), s_i = log b_i ~ N(1, 1)."""
    c = np.where(lab == 1, q[item], 1 - q[item])     # posterior probability that each label is correct
    def neg(p):
        aj, si = p[:m], (p[m:] if fit_b else s)
        b = np.exp(si); x = aj[ann] * b[item]
        f = (c * log_expit(x) + (1 - c) * log_expit(-x)).sum() - ((aj - 1) ** 2).sum() / 2
        r = c - expit(x)                             # observed minus predicted probability of being correct
        g = [np.bincount(ann, r * b[item], minlength=m) - (aj - 1)]
        if fit_b:
            f -= ((si - 1) ** 2).sum() / 2
            g.append(np.bincount(item, r * aj[ann], minlength=n) * b - (si - 1))
        return -f, -np.concatenate(g)
    p = minimize(neg, np.concatenate([a, s]) if fit_b else a, jac=True, method='L-BFGS-B', options=dict(maxiter=25)).x
    return p[:m], (p[m:] if fit_b else s)

def em(fit_b):
    a, s = np.ones(m), np.zeros(n)                   # equal skills: the first E-step is a majority vote
    q = e_step(a, np.exp(s))
    for it in range(1, 500):
        a, s = m_step(q, a, s, fit_b)
        q, q_old = e_step(a, np.exp(s)), q
        if np.abs(q - q_old).max() < 1e-5: return q, a, s, it

majority = np.bincount(item, vote, minlength=n) > 0
q, a, s, it = em(fit_b=True)
glad = q > 0.5
print((majority != z_true).sum(), (glad != z_true).sum(), it)       # 133 61 24: errors of majority vote and of GLAD
print(((majority != z_true) & (glad == z_true)).sum(), ((majority == z_true) & (glad != z_true)).sum())   # 91 19
print(a.round(2))                                    # [ 1.45  1.4   1.43  1.13  0.83  0.09 -1.03]
print((np.bincount(ann, lab == z_true[item]) / np.bincount(ann)).round(2))   # [0.98 0.94 0.94 0.87 0.79 0.53 0.11]: each annotator's true accuracy
print(round(np.corrcoef(s, np.log(b_true))[0, 1], 2))                # 0.43: easiness is only roughly recovered
q1, a1, *_ = em(fit_b=False)                        # skills only, every b_i = 1
print(((q1 > 0.5) != z_true).sum(), a1.round(2))    # 61 [ 3.14  3.06  3.08  2.2   1.52  0.11 -2.01]

# the likelihood cannot tell (a, z) from (-a, 1 - z), nor (a, b) from (2a, b/2): only the priors fix sign and scale
def loglik(a, b, z):
    x = a[ann] * b[item]
    return np.where(lab == z[item], log_expit(x), log_expit(-x)).sum()
print(np.isclose(loglik(a_true, b_true, z_true), loglik(-a_true, b_true, 1 - z_true)),
      np.isclose(loglik(a_true, b_true, z_true), loglik(2 * a_true, b_true / 2, z_true)))   # True True

Next#

Variational EM approximated the posterior over the latent variables and kept a point estimate of the parameters. The next note approximates the posterior over everything unknown at once, latent variables and parameters alike, with a factorized qq. It derives the general update of each factor, log⁡qj∗=E−j[log⁡p]+const\log q_j^* = \mathbb E_{-j}[\log p] + \text{const}, works it out for a Gaussian with unknown mean and precision, and shows what the factorization gets wrong.

References#