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.
The relevance vector machine · The Laplace approximation and Bayesian classification · Mixtures and the EM algorithm · Dimensionality reduction
On this page 7
Here are 100 points in ten dimensions. The eigenvalues of their sample covariance are , and , then , and a slow decline to . 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 , centred so that the data have mean zero, by a -dimensional code :
where is the loading matrix with columns and the noise variance.
Centring costs nothing. With a mean, the marginal is with , and enters the log-likelihood only through . The gradient of this quadratic form, with symmetric, gives
The log-likelihood is concave in , because is positive definite, so this stationary point is the maximum. It does not depend on or , so we set once, centre the data and fit and to the centred points.
The maximum likelihood solution is known in closed form. Let be the eigenvalues of the sample covariance . The columns of span the leading eigenvectors of , the directions of PCA. In the solution with orthogonal columns, column has length , and is the average of the discarded eigenvalues.
Why
The log-likelihood depends on the data only through : with , it is plus a constant. Suppose has the eigenvectors of , with eigenvalues . The determinant is the product of the and the trace is , so the log-likelihood splits into one term per direction, , and its derivative in , , vanishes at . A rank- sets of them freely above , , which gives the lengths ; the other equal . Setting the derivative of in to zero gives their average. That the optimal has the eigenvectors of , and keeps the largest eigenvalues, is proved in Tipping and Bishop (1999), Appendices A.1–A.2.
One case has no maximum. If all discarded eigenvalues are zero, the data lie in a -dimensional subspace, as they always do when , because centred points span at most dimensions. Each discarded direction then contributes to the log-likelihood, which grows without bound as : there is no maximizer with .
If the noise variance is fixed instead of fitted, each column is decided on its own. Column sets , which cannot go below . Its term has the derivative , positive below and negative above. So when , and otherwise stays at the boundary , a zero column:
where holds the leading eigenvectors, is the diagonal matrix of their eigenvalues, the maximum is taken entry by entry, and is any orthogonal matrix, since leaves the likelihood unchanged. The leading eigenvectors are the right ones: moving from to raises the log-likelihood by with , which increases with for .
A fixed can therefore leave fewer than active columns. On the data of the opening, with the true and , the columns along , and vanish. Six survive, with lengths down to , because sampling noise has lifted , and above 1.
What maximum likelihood cannot do is choose . The models are nested: a model with columns can set one of them to zero, so the maximized log-likelihood never decreases with . The data of the opening come from a model with three latent dimensions and unit noise:
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | |
|---|---|---|---|---|---|---|---|---|---|
| log-likelihood |
The gains are and up to , then , and less, but the likelihood keeps growing. With every column is used. The lengths are , and for the signal and down to for six directions that carry only noise. The noise variance comes out as , well below the true value 1, because the extra columns have absorbed most of the noise. Choosing by BIC or by held-out likelihood means fitting every separately.
EM as coordinate ascent on the evidence lower bound#
Let be the observations, the latent variables and the parameters. For any distribution that is positive wherever the posterior is,
The EM note derives the identity: write , add and subtract , and average over . The KL divergence is non-negative, so , the evidence lower bound (ELBO), is a lower bound on the log evidence, tight exactly when is the posterior. The Code section checks the identity for a randomly drawn : both sides equal .
EM is coordinate ascent on . The E-step maximizes over with fixed. Since does not depend on , this minimizes the KL divergence: becomes the posterior and the gap closes. The M-step maximizes over with fixed. The entropy of does not depend on , so the M-step maximizes the expected complete-data log-likelihood .
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 components alone turns one maximum into . 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 is in the exponential family. Then 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 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 . 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 , in an annotator’s skill and an item’s easiness . With , and the chain rule,
and by symmetry. At they equal , and , so the Hessian has the eigenvalues : 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 . Substituting the average of gives another function: in general . The two agree when is linear in . For a mixture with one-hot labels it is, , which is why plugging in the responsibilities works there. In the PCA model below it is quadratic in , and the average needs , which contains the posterior covariance of .
A prior on the parameters gives MAP-EM. The log posterior of the parameters is , and the last term does not depend on . Adding to both sides of the decomposition,
The E-step is unchanged. The M-step maximizes , 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 , which the RVM note compares with MacKay’s fixed point.
Neither step has to be solved exactly. A generalized EM only increases 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 has an unknown true label and an easiness ; its difficulty is . Annotator has a skill . The label that annotator gives item is correct with probability
The paper writes and ; 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 is a coin flip for everyone. The labels are independent given the true label, and an annotator need not label every item: write for those who labelled item .
The E-step is a weighted vote. By Bayes’ formula with the prior , the posterior log-odds of the true label is the sum of the log-likelihood ratios of its labels, since they are independent given . A label is correct under and wrong under , so it contributes ; a label contributes the negative. Finally :
Each label votes or 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, , adds one factor to Bayes’ formula: the posterior odds are the prior odds times the likelihood ratio, so
The prior casts a vote of fixed weight for the more common class, the same for every item, and vanishes at .
For the M-step, let be the posterior probability that label is correct, . The complete-data log-likelihood is a sum over labels of for a correct label and for a wrong one. Its expectation under replaces the indicator of a correct label by :
Since , its derivative is , and that of is . With , each term has the derivative with respect to , and the chain rule gives
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 and , which keeps 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 : experts, average annotators, a guesser and an adversary. The easiness is , as in the paper’s simulations. EM starts from equal skills, so its first E-step is the majority vote:
| majority vote | GLAD, 24 EM iterations | |
|---|---|---|
| wrong labels of 1000 | 133 | 61 |
| skills | equal |
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 and swap places, so each factor stays the same. Doubling the skills while halving the easiness leaves every product , and so the likelihood, unchanged. Only the prior mean of 1 on says that annotators are mostly helpful and fixes the scale.
A model with skills alone, every , 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 weights item by , so hard items count less. Here the two fits find nearly proportional skills, 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 . 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 of distributions it can handle:
The two forms of the E-step are the same problem, because does not depend on . Each step still increases , so the bound never decreases. What is lost is the tightness after the E-step: the gap is the smallest KL divergence within , which is positive unless contains the posterior. Write . The monotonicity chain of exact EM is
and with a restricted its last link becomes . 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 , so its maximizer is pulled towards parameters at which the posterior is easy to approximate by a member of , a bias that can be large (Turner and Sahani, 2011).
Worked example: hard EM is variational EM. Take to be the point masses, . The entropy of a point mass is zero, so , maximized by giving each point its most probable component. The gap for one point is
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 on seven points, and start at . The first three points go to the first component and the last four to the second:
| gap |
The gaps add up to . The M-step moves to the mean of the four points, , where the log-likelihood is and the next E-step leaves a gap of . Hard EM converges to with and a gap of . Exact EM converges to the maximum likelihood estimate with and no gap. Hard EM even climbs faster at first, against after one M-step, and still stops at the wrong place. It maximizes its own bound, which at is , higher than its value at the maximum likelihood estimate.
An exact and a restricted E-step: ℓ = L + KL
Point masses are the crudest family. The next note uses factorized distributions, , for which the E-step has a closed-form coordinate update. It also lets 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 per column:
This is automatic relevance determination applied to latent dimensions instead of input features. A large forces column towards zero, and a zero column removes latent dimension from the model, since no longer depends on . is as many columns as can be useful: with all of them kept, can already represent any covariance matrix. Take equal to its smallest eigenvalue , and as columns the other eigenvectors scaled to (Bishop, 2006, Section 12.2.3).
The ideal would be to choose and by maximizing the evidence . But enters the covariance of 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:
- with fixed, find the MAP estimate of and by MAP-EM, with the codes as latent variables;
- with fixed, set .
The second update is the evidence fixed point of the relevance vector machine, , applied to a whole column of entries, each of them counted as well determined by the data, so that . It is also the value of that maximizes at the current .
The E-step is exact, because and are jointly Gaussian. Keep the terms of that contain and complete the square:
The precision is , the mean is the precision’s inverse times the linear term, and is the covariance plus the outer product of the mean:
The M-step maximizes . The terms with are . Write and collect the two sums of E-step statistics,
Expand . By the trace rules, the gradient in of is and that of , for a symmetric , is ; the prior term gives . Summed over the points, the gradient and its zero are
With this is the EM algorithm for probabilistic PCA (Tipping and Bishop, 1999); the prior adds , a ridge penalty of its own size for every column. The prior does not involve the noise variance. Setting the derivative of to zero, with the new , gives
Both updates use , the sum of . 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 and , EM converges to and the maximum likelihood lengths . The variant settles at , and its columns grow without bound, to lengths of about 165 after 20,000 iterations.
Why the columns grow
Follow one eigenvector of with eigenvalue and a column of length along it. With the coordinates of the points along it, , and the mean codes are . The variant’s M-step regresses the on these means:
So , and grows by more than in every iteration: by more than over iterations with , a length of about 165. With the posterior variance of each code, the denominator gains , and the fixed point becomes , that is .
The update divides by , while the closed form of the first section averages eigenvalues. At the maximum likelihood solution () they agree, because there each kept direction contributes to the expected residual and each discarded one :
EM averages over all coordinates, and the posterior uncertainty of the codes puts of residual into each kept direction; the closed form has already eliminated and keeps only the directions that carry nothing but noise. The Code section’s EM with reaches , the average of the seven discarded eigenvalues.
Why a kept direction contributes nσ²
With , the expansion of above becomes . Take the solution with orthogonal columns along the eigenvectors ; a rotation changes neither term. Then is diagonal with entries and diagonal with entries . Along the fitted mean has the coordinate , where and . Summed over the points,
A discarded direction has no component of , so its whole energy stays in the residual.
One iteration costs and never forms the covariance, which makes EM cheaper than an eigendecomposition when is large and 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 . 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 . Then has the eigenvectors of . Along the eigenvector of column , with eigenvalue of and , has the eigenvalue , and as in the maximum likelihood solution above the log-likelihood splits into one term per direction. The MAP objective for and its stationary point are
Substituting the precision update and , then expanding both sides and collecting powers of :
The product of the roots, , is positive, so both roots have the same sign, that of their sum, the bracket divided by . 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 , that is , or
Below the threshold the only fixed point is with : the column is switched off. Maximum likelihood keeps a direction whenever . The prior asks for extra evidence that shrinks as grows, about in relative terms when . Above the threshold the larger root is the squared length that EM reaches here. It is smaller than the maximum likelihood value , because it is below the sum of the roots, .
Worked example. Return to the data of the opening, with and . Bayesian PCA with columns removes six of them, at EM iterations , , , , and (a column is removed when exceeds ), and ends with , close to the true noise variance. The threshold and the third column are
| Quantity | Value |
|---|---|
| threshold on | |
| threshold on | |
| quadratic for | |
| larger root, | , |
| maximum likelihood, |
The third eigenvalue, , is above the threshold and the fourth, , below it, so exactly three columns survive. The length of the third is the one EM finds. The other two kept columns have lengths and , again the larger roots of their quadratics, and .
Bayesian PCA switches off the columns it does not need
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 treats every entry of a column as well determined and uses a point estimate of , so the threshold above is a property of this scheme. A variational treatment of the same model, with a factorized posterior over , and , 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, instead of 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#
- for every ; EM is coordinate ascent on .
- A prior adds to the M-step (MAP-EM); partial steps are fine if they raise .
- 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 ; 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 , then .
- A direction survives only if .
Code#
Exact and hard EM on the seven-point mixture, the decomposition for an arbitrary , maximum likelihood probabilistic PCA for every 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 . It derives the general update of each factor, , works it out for a Gaussian with unknown mean and precision, and shows what the factorization gets wrong.
References#
- A. P. Dempster, N. M. Laird, D. B. Rubin. Maximum Likelihood from Incomplete Data via the EM Algorithm. Journal of the Royal Statistical Society B, 39(1), 1–38, 1977.
- J. Whitehill, P. Ruvolo, T. Wu, J. Bergsma, J. Movellan. Whose Vote Should Count More: Optimal Integration of Labels from Labelers of Unknown Expertise. Advances in Neural Information Processing Systems 22, 2035–2043, 2009. Sections 2–4 (the model, EM with priors on the parameters, simulations).
- R. M. Neal, G. E. Hinton. A View of the EM Algorithm that Justifies Incremental, Sparse, and other Variants. In Learning in Graphical Models, 355–368, 1998.
- M. E. Tipping, C. M. Bishop. Probabilistic Principal Component Analysis. Journal of the Royal Statistical Society B, 61(3), 611–622, 1999.
- C. M. Bishop (1999a). Bayesian PCA. Advances in Neural Information Processing Systems 11, 382–388, 1999.
- C. M. Bishop (1999b). Variational Principal Components. Proceedings of the Ninth International Conference on Artificial Neural Networks (ICANN), 509–514, 1999.
- M. J. Beal. Variational Algorithms for Approximate Bayesian Inference. PhD thesis, University College London, 2003. Chapter 2 (variational Bayesian EM).
- R. E. Turner, M. Sahani. Two problems with variational expectation maximisation for time-series models. In Bayesian Time Series Models, Cambridge University Press, 104–124, 2011.
- C. M. Bishop. Pattern Recognition and Machine Learning. Springer, 2006. Section 9.4 (EM in general, generalized and incremental EM), Section 12.2.2 (EM for PCA, missing data) and Section 12.2.3 (Bayesian PCA).
- D. P. Vetrov, D. A. Kropotov. Байесовские методы машинного обучения, lecture course, Moscow State University, 2015. Course page; lecture 6, EM and Bayesian PCA (notes), and lecture 7, variational inference and variational EM (notes).
- Конспект курса «Байесовские методы в анализе данных», 2026, github.com/bmml-team/bmml_ftda, лекция 3.