09 / 15 · Latent Variables and Approximate Inference
Gibbs sampling
Draw each block of unknowns from its conditional given the others, and the chain samples the exact posterior: noisy where variational inference is biased, and faster with blocking, collapsing or extra variables.
On this page 11
In the normal model with unknown mean and precision, mean-field variational inference reported a posterior standard deviation of for the mean. The exact value is , and nothing in the method revealed the error. To measure such an error, or to avoid it, we need draws from the exact posterior .
The general tool is Markov chain Monte Carlo: run a Markov chain whose stationary distribution is the posterior. Random-walk Metropolis–Hastings needs a step size that suits every direction at once. In the normal model the posterior standard deviations are for and for , and must stay positive. In a mixture with 100 discrete labels and a few continuous parameters, one joint random move of everything is almost always rejected. The direct samplers of the Monte Carlo note, rejection and importance sampling, fail sooner: they need a proposal close to the whole posterior, and in many dimensions there is none.
The models of this course are built from conjugate pieces. Given the other unknowns, each block has a standard distribution: the same complete conditional that gave the closed-form factors of mean field. Gibbs sampling (Geman and Geman, 1984; Gelfand and Smith, 1990) draws each block from it in turn. Each draw is a proposal that is never rejected.
Metropolis–Hastings on a posterior#
Gibbs sampling is a special case of a more general sampler, and in one dimension the general one is often all we need. Metropolis–Hastings uses the target only through ratios of its density. For a posterior these ratios are computable, because the evidence cancels:
where is the unnormalized posterior. From the current , the sampler proposes and accepts it with probability
If the proposal is rejected, the chain stays at and records again as its next draw. The repeat counts. It is how the chain spends more time where is high: from there most proposals lead downhill, and many are rejected. With this rule the posterior is a stationary distribution of the chain by detailed balance; the probability note also gives the conditions for convergence. For a symmetric proposal, such as the random walk with , the two values of cancel.
Worked example. Take the seven flips of the conjugate priors note, five heads and two tails, with a prior that has no conjugate form: the log-odds of heads, , is . Since and , the likelihood and the prior density give
A random walk with step is symmetric, so . Two moves, with the change of each term of :
| Move | heads term | tails term | prior term | log ratio | |
|---|---|---|---|---|---|
The first move is uphill and always accepted. The second proposes , more extreme than five heads in seven support, and is accepted only if a uniform draw falls below . When it does not, the chain records a second time, and the draws so far read .
Over 20,000 steps, after 1,000 of burn-in, the sampler accepts 49% of its proposals. Its draws give a posterior mean of of and a standard deviation of , against and from numerical integration over , which one dimension makes cheap. Dropping the repeated states raises the standard deviation to : the draws that remain over-represent the tails.
Gibbs sampling is Metropolis–Hastings whose proposal for one block is that block’s complete conditional. With this proposal the ratio inside equals 1, as the validity section shows, so every proposal is accepted and there is no step size to tune.
The Gibbs update#
Split the unknowns into blocks , and write for all blocks except ; we write the target as , leaving the data implicit. One sweep with a fixed order of blocks, from the current state , is
Each block is drawn given the newest values of the others. A random-order sampler instead picks one block at random at each step. The conditional of block is found exactly as a mean-field factor was, by reading as a function of alone,
so it involves only the Markov blanket of in the graphical model. Mean field sets a factor to the normalized , averaging over the other blocks. Gibbs draws a value from the normalized at the current values of the others.
A discrete block can be drawn back to its old value. A label with values is redrawn from its conditional over all of them, the current one included, and that one usually has positive probability. The state then repeats, as after a rejected Metropolis–Hastings proposal. Nothing was rejected, though: the repeat is a draw from the conditional and counts like any other.
Using the newest values is not a detail. Updating every block at once from the values of the previous sweep gives a different chain with a different stationary distribution. For a bivariate normal with correlation , the Code section finds a sample correlation of with the sequential update and with the simultaneous one. The covariance shows why. The simultaneous update draws and with independent noises , so , whose only fixed point is zero. The variances still settle at 1, from , and jointly Gaussian variables with zero covariance are independent: the chain samples the product of the marginals. Two repairs keep the speed of parallel updates. Blocks that are conditionally independent given the rest, such as the black and the white squares of a checkerboard grid, can be drawn together (Murphy, 2023, Section 12.3.3). Or the simultaneous draw can serve as the proposal of a Metropolis–Hastings step, which corrects its stationary distribution (Vetrov and Kropotov, lecture 8).
Why it is valid#
Each update leaves the target invariant. Suppose the current state is distributed according to . Then has the marginal , and the new is drawn from , so the new state has density , the target again. In terms of the transition density of the update of block , which leaves ,
A sweep is a composition of such updates, and a composition of transitions that each preserve preserves .
Each update is also a Metropolis–Hastings step that is always accepted. With the proposal and , the acceptance ratio is
Each single update therefore satisfies detailed balance. A systematic sweep, a fixed sequence of reversible steps, is in general not reversible itself: run backwards, the sweep then becomes then , a different transition. The random-order version is reversible, because its transition is the average and each satisfies detailed balance, which is linear in the transition. Neither matters for correctness, because invariance is what the chain needs.
Invariance alone does not make the chain converge. It must also be able to reach every region of the target from every start (irreducibility) and must not cycle (aperiodicity), and Gibbs, moving along one block at a time, can fail the first. A simple sufficient condition is the positivity condition: the joint density is positive wherever the product of its marginals is (Robert and Casella, 2004, Chapter 10). The normal model, with its density positive on , satisfies it; the last section shows a target that does not.
Why positivity suffices
Take two points and of the support. Every density along a sweep from to , such as , has a joint density in its numerator at a point whose blocks come from or . Every block’s marginal is positive there, so by positivity the joint is too. The transition density of a sweep is then positive between any two points of the support, the sufficient condition for an ergodic chain in lecture 4 of the course notes (Definition 13).
A Gibbs sampler for the normal model#
The model is the one of the variational inference note: eight observations from , the prior with and , and with . Read as a function of alone, its log joint is a quadratic with leading coefficient and maximum at . Read as a function of alone, it is the logarithm of a gamma density. The complete conditionals are therefore
where and
These are the mean-field factors of the previous note, with replaced by the current and the average over by the value at the current .
Worked example. Start at . The conditional of is a normal with mean and precision , standard deviation ; the draw is . At this the conditional of is , with mean ; the draw is . One sweep has moved the chain from the edge of the posterior into its bulk.
One Gibbs sweep: first μ, then λ
Now run four chains of 10,000 sweeps from the dispersed starts , , and , and discard the first 1,000 sweeps of each:
| Gibbs, draws | exact | |
|---|---|---|
| posterior mean of | ||
| posterior standard deviation of | ||
| posterior mean of |
The Monte Carlo error of the standard deviation is about . The difference of is noise of the expected size, and unlike the of mean field it shrinks as the chains get longer.
Where 0.002 comes from
For independent draws with variance and excess kurtosis , the sample variance has variance . The derivative of the square root at is , so the delta method gives the standard deviation an error of . The marginal of is a Student with degrees of freedom, , and the draws of are nearly independent (next paragraph), so gives .
This sampler mixes unusually well. The conditional mean of is whatever is, so successive draws of are uncorrelated: by the tower rule, , a constant, and a constant has zero covariance with . The lag-1 autocorrelation is , and each chain’s 9,000 draws of are worth 9,000 independent ones. For the lag-1 autocorrelation is , and the effective sample sizes are between 7,737 and 9,000. When the posterior couples the blocks strongly, Gibbs is slow. On a correlated Gaussian with , successive draws of one coordinate have correlation (MCMC note), the same factor by which each mean-field sweep shrinks the distance of the means to the optimum (variational inference note).
Using the draws: predictive and evidence#
Posterior draws turn the integrals of the first note into averages. By the law of total probability, the predictive density at a new point is an expectation over the posterior, and the average over the chain converges to it by the ergodic theorem, the law of large numbers for Markov chains:
We average the density at each draw instead of making a histogram of simulated values of . The density at a draw is the conditional probability of a small interval around given the draw, and by the law of total variance the variance of a conditional expectation is at most the variance of the indicator it averages. This is the Rao–Blackwellization of the next section. For the 36,000 draws of the four chains give , against for the exact Student-t predictive.
The evidence is an expectation too, over the prior: by the sum rule, . The average of the likelihood over independent prior draws has this expectation, so it is unbiased; it is also wasteful, because the likelihood is large only where the posterior is, a small part of the prior’s range. The estimate is importance sampling of the integral with the prior as the proposal : the weight of a draw, , is then its likelihood. The effective sample size of the weights measures the waste. For the normal model, with 1000 prior draws repeated five times:
| Data | exact log evidence | five estimates | effective sample sizes |
|---|---|---|---|
| the eight points | to | 244 to 283 | |
| eighty new points | to | 38 to 48 |
The fraction of useful draws is the Occam factor: the posterior’s volume over the prior’s. The posterior width of each parameter shrinks like , as in the coin example, so the fraction falls roughly like for parameters. For that predicts a tenfold fall from eight to eighty points; the effective sample size fell sixfold, since the scaling holds only once the data dominate the prior. Posterior draws alone do not fix this. Their harmonic mean of the likelihood weights each draw by , largest in the tails where the posterior has few draws. Its mean is right, , but its variance can be infinite (details below). Chib (1995) takes the logarithm of Bayes’ formula at one point , . For the normal model, by the product rule. The first factor is a complete conditional, and the second is the average of the complete conditional over the Gibbs draws of , by the sum rule.
Why the harmonic mean can have infinite variance
Its second moment is divided by : the posterior density cancels one factor of the likelihood. With a Gaussian likelihood for points of known precision , grows like . Against a normal prior of variance the integral is finite only if , only if the prior is narrower than the likelihood, which is almost never the case.
Blocked and collapsed Gibbs#
Two changes of what counts as a block make a Gibbs sampler mix faster.
Blocking draws several coupled blocks jointly from their joint conditional. In the limit of one block the sampler draws from the posterior directly, and successive samples are independent. For the normal model the joint posterior is a normal–gamma, so the blocked sampler draws and then : the Code section’s 9,000 draws give a standard deviation of and an effective sample size of 9,000. For a correlated Gaussian, drawing both coordinates together removes the autocorrelation entirely. In a hidden Markov model the whole state sequence can be drawn as one block given the parameters, by forward filtering and backward sampling (Murphy, 2023, Section 12.3.7). Blocking pays when the joint conditional of a group is still easy to sample and the group is strongly coupled inside.
Collapsing integrates some variables out analytically and runs Gibbs on the rest. From it samples by its conditionals. Liu (1994), extending Liu, Wong and Kong (1994), compares the three schemes by the norms of their forward operators, which measure how strongly successive states are correlated. Collapsing is no worse than grouping and into one block, which is no worse than updating all three one at a time. The intuition: dependence between successive states travels through the variables that each update conditions on, and every step from the third scheme to the first conditions on less. The variables integrated out are not lost. Given the sampled ones they can be drawn from their conditional, and expectations of functions of them can be estimated by averaging their conditional expectations, which has smaller variance than averaging draws by the law of total variance (Rao–Blackwellization).
A collapsed sampler for a Bayesian mixture#
Optional depth: the derivation of the collapsed conditional. The rest of the note does not depend on it.
Take a mixture of Gaussians in one dimension with known variance : weights , means , labels and . With the number of points with label , the standard sampler cycles three conjugate conditionals:
where and , the normal–normal update. Given and the labels are independent, so all of them are drawn at once.
The collapsed sampler integrates and out and samples the labels alone, one at a time. By Bayes’ formula, . The first factor is the Dirichlet–categorical predictive probability, a count plus a pseudo-count. The second is the posterior predictive density of under component , given the other points with that label. Given them, by the normal–normal update, and with independent noise of variance , so by the linear-Gaussian marginal is normal with mean and variance . So
where , and are computed without point . The labels are no longer conditionally independent, which is why they are updated in turn; the counts make each update cheap. The first factor makes large clusters attract new points, a rich-get-richer effect (Cambridge 4F13, Gibbs sampling for the Bayesian mixture).
Worked example. In the Code section, 120 points come from three unit-variance clusters centred at , and , with , , and . Both samplers start with every point in one cluster and run 2,000 sweeps. Component labels can permute during the run, so the monitored quantity must not depend on them: we take the size of the cluster that contains the first point. After 200 sweeps of burn-in:
| standard | collapsed | |
|---|---|---|
| effective sample size of 1,800 sweeps | 56 | 213 |
| average size of the cluster of the first point |
The averages carry the large noise of so few effective samples. The comparison is per sweep, and a collapsed sweep visits the points one at a time. The same collapsed sampler, with the Dirichlet weights replaced by a Dirichlet process, fits the infinite mixtures of the Dirichlet processes note. For topic models it is the standard way to fit latent Dirichlet allocation (Griffiths and Steyvers, 2004).
Adding variables to make the conditionals easy#
Collapsing removes variables; sometimes adding them helps more. A posterior with no standard conditionals can become one with easy conditionals once suitable latent variables are introduced, an idea known as data augmentation.
The TrueSkill model of player skills is the example of the Cambridge 4F13 course. Each player has a skill with a Gaussian prior. In game , between players and , the performance difference is , and only its sign, who won, is observed. The posterior of the skills alone is a Gaussian prior times a product of probit factors and has no standard form. With the added as unknowns, both conditionals are standard. Given the skills, each is a Gaussian truncated to the side that matches the observed outcome. Given the performance differences, the skills are a linear-Gaussian regression, so they are jointly Gaussian and can be drawn as one block.
The same move turns a Student- likelihood into a Gaussian one: a density is a Gaussian whose precision is scaled by a gamma-distributed variable, and given one such variable per point every conditional is conjugate again.
Derivation
The scale mixture is a gamma integral, , with :
the Student- density with degrees of freedom.
The price is more variables to sample. Adding variables and changing nothing else tends to slow a chain down (Liu, 1994): it is collapsing run backwards, so the three-schemes comparison above ranks it lower. Augmentation pays when it turns intractable conditionals into standard ones.
Checking convergence#
The MCMC note introduces the tools; four habits make them work for Gibbs samplers.
First, run several chains from dispersed starts, discard a burn-in, and compare the chains. The split , a version of the potential scale reduction factor of Gelman and Rubin (1992), cuts each of chains in half and compares the halves of length . With the average variance within the halves and the variance of the half means times ,
which approaches 1 when the halves agree. Vehtari et al. (2021) recommend a rank-normalized version and treat , or a total effective sample size below 400, as a sign of trouble. The four chains of the normal model give for both and .
Second, in mixtures and other models with symmetric labels, monitor what the labels cannot change. of a component mean measures label switching, not convergence; cluster sizes, the co-assignment of two points or the log-likelihood do not have this problem.
Third, report effective sample sizes, not sweeps: 1,800 sweeps of the standard mixture sampler above were worth 56 independent samples. Thinning, keeping every -th sweep, makes the kept draws less correlated but does not make their average more accurate. The average of all draws is the mean of the thinned averages that start at sweeps . In a stationary chain they have equal variances , and by the Cauchy–Schwarz inequality every covariance between them is at most , so the variance of their mean is at most (MacEachern and Berliner, 1994). Thinning only saves memory. Fourth, remember what no diagnostic sees. A region the chains never reach leaves no trace in their output, and starting chains in different modes, or knowing that the posterior has symmetries, is the only defence.
Gibbs or variational inference: bias against variance#
The mean squared error of an estimate splits into a squared bias and a variance. The two methods of this part of the course sit at the two ends of that split.
Bias against variance: Gibbs and mean field
Mean field reports the posterior standard deviation of as at once and with no randomness. Its error, , is a bias, and it stays the same however long the algorithm runs. The Gibbs estimates have no bias in the limit. Their error is random: between and after 10 sweeps, between and after 10,000, shrinking roughly like one over the square root of the number of sweeps, by the central limit theorem for the chain (MCMC note). For a short budget the deterministic answer can be closer; for any precision beyond its bias, sampling wins by running longer.
| Mean-field variational inference | Gibbs sampling | |
|---|---|---|
| Uses | for each block | draws from for each block |
| Result | a distribution in closed form | correlated samples from the exact posterior, in the limit |
| Error | bias: too narrow, one mode, correlations lost | variance: about |
| More computation | no improvement after convergence | the error keeps shrinking |
| Evidence | a lower bound | needs a further method, for example Chib (1995) |
| Convergence check | the bound stops increasing | several chains, , ESS |
| Scales to | large data, with the stochastic version | moderate data; each sweep visits every latent variable |
In practice the two are used together: variational inference to fit large models quickly, and a long Gibbs or Hamiltonian Monte Carlo run on a smaller problem to measure how far its uncertainty is off.
Where it breaks#
A target whose support is disconnected along the axes defeats Gibbs completely. Let be uniform on the union of the squares and , which touch only at a corner. From a point in the first square, the conditional of given is uniform on , and so is the conditional of given . The chain never enters the second square; in the Code section it spends 0 of 10,000 sweeps there. The uniform distribution on either square is stationary on its own, so a chain started in one square never approaches , the equal mixture of the two. The positivity condition fails: the product of the marginals is positive on , where is zero. And the output looks perfectly converged.
Real posteriors fail more softly in the same ways. Strongly coupled blocks make the chain crawl, as in the correlated Gaussian; blocking or reparametrizing helps only when the joint conditional of the group stays easy. Separated modes, such as the relabellings of a mixture, can hold a chain for its whole run. Without conjugacy the conditionals need samplers of their own: adaptive rejection sampling when a one-dimensional conditional is log-concave (Gilks and Wild, 1992), Metropolis steps inside Gibbs or slice sampling otherwise, and the simplicity is gone (Murphy, 2023, Section 12.3.6). And every sweep visits every latent variable, so the cost grows with the data, where stochastic variational methods scale better.
What you should remember#
- Gibbs draws each block from , always given the newest values of the others.
- Metropolis–Hastings needs only , and a rejected proposal repeats the state; each Gibbs update is a Metropolis–Hastings step with acceptance 1.
- Convergence also needs irreducibility; the positivity condition (a joint density positive wherever the product of its marginals is) guarantees it.
- Blocking draws coupled blocks jointly; collapsing integrates variables out; augmenting adds variables that make conditionals easy.
- Check with several chains, split and effective sample sizes, on label-free quantities.
- Mean field: fixed bias, no noise. Gibbs: no bias in the limit, noise that shrinks with sweeps.
Code#
Gibbs for the normal model with four chains, split and effective sample sizes, the predictive and the evidence by averaging, the blocked sampler, a reducible target, the bug of simultaneous updates, and the standard and collapsed samplers for a Bayesian mixture. NumPy and SciPy only; seeds are fixed, and exact numbers can differ across platforms and library versions. The script runs in about 12 seconds, almost all of it in the collapsed sampler, whose inner loop visits the points one at a time.
import numpy as np
from scipy import stats
from scipy.special import logsumexp, gammaln
def ess(a): # effective sample size, autocorrelations summed until they drop below 0.05
a = a - a.mean(); n = len(a)
r = np.correlate(a, a, 'full')[n - 1:] / (a.var() * n)
cut = np.argmax(r[1:] < 0.05) + 1
return n / (1 + 2 * r[1:cut].sum())
def split_rhat(chains): # chains: m x n; each chain split in two halves
h = chains.shape[1] // 2
c = np.vstack([chains[:, :h], chains[:, h:2 * h]])
B, W = h * c.mean(axis=1).var(ddof=1), c.var(axis=1, ddof=1).mean()
return np.sqrt(((h - 1) / h * W + B / h) / W)
# the normal model of the variational-inference note
x = np.array([3.0, -1.6, 1.4, 0.4, 0.5, 0.8, -1.0, 0.8])
N, mu0, l0, a0, b0 = len(x), 0.0, 1.0, 2.0, 2.0
mN = (l0 * mu0 + x.sum()) / (l0 + N)
aE, bE = a0 + N / 2, b0 + 0.5 * ((x - x.mean()) ** 2).sum() + l0 * N * (x.mean() - mu0) ** 2 / (2 * (l0 + N))
def gibbs(start, sweeps, rng):
mu, tau = start
out = np.empty((sweeps, 2))
for s in range(sweeps):
mu = rng.normal(mN, 1 / np.sqrt((l0 + N) * tau)) # mu | tau, x
b = b0 + 0.5 * (((x - mu) ** 2).sum() + l0 * (mu - mu0) ** 2)
tau = rng.gamma(a0 + (N + 1) / 2, 1 / b) # tau | mu, x
out[s] = mu, tau
return out
rng = np.random.default_rng(0)
starts = [(-0.5, 0.3), (1.5, 0.3), (-0.5, 1.6), (1.5, 1.6)]
ch = np.stack([gibbs(s, 10000, rng) for s in starts]) # 4 x 10000 x 2
keep = ch[:, 1000:] # discard 1000 sweeps of burn-in
print(keep[..., 0].mean().round(3), keep[..., 0].std().round(3), keep[..., 1].mean().round(3)) # 0.478 0.452 0.66
print(round(mN, 3), round(np.sqrt(bE / ((aE - 1) * (l0 + N))), 3), round(aE / bE, 3)) # 0.478 0.449 0.661: exact
print([f"{split_rhat(keep[..., j]):.4f}" for j in (0, 1)], [int(ess(c[:, 0])) for c in keep], [int(ess(c[:, 1])) for c in keep])
# ['1.0000', '1.0000'] [9000, 9000, 9000, 9000] [9000, 7937, 7737, 7917]
print([round(float(np.corrcoef(keep[0, :-1, j], keep[0, 1:, j])[0, 1]), 3) for j in (0, 1)]) # [-0.002, 0.05]: lag-1 autocorrelations
# the predictive density at x* = 3: N(3 | mu, 1/tau) averaged over the Gibbs draws, against the exact Student-t
d = keep.reshape(-1, 2)
pred = stats.t(2 * aE, loc=mN, scale=np.sqrt(bE * (l0 + N + 1) / (aE * (l0 + N))))
print(round(stats.norm.pdf(3.0, d[:, 0], 1 / np.sqrt(d[:, 1])).mean(), 4), round(pred.pdf(3.0), 4)) # 0.0508 0.0507
# the evidence by averaging the likelihood over prior draws, against the exact normal-gamma evidence
def prior_mc(data, S, g): # the log of the average likelihood over S prior draws, and the ESS of the weights
t = g.gamma(a0, 1 / b0, S); m = g.normal(mu0, 1 / np.sqrt(l0 * t))
ll = stats.norm.logpdf(data[:, None], m, 1 / np.sqrt(t)).sum(axis=0)
w = np.exp(ll - ll.max())
return logsumexp(ll) - np.log(S), w.sum() ** 2 / (w ** 2).sum()
def log_ev(data): # a ratio of normalizing constants of the normal-gamma prior and posterior
n = len(data); kn, an = l0 + n, a0 + n / 2
bn = b0 + 0.5 * ((data - data.mean()) ** 2).sum() + l0 * n * (data.mean() - mu0) ** 2 / (2 * kn)
return gammaln(an) - gammaln(a0) + a0 * np.log(b0) - an * np.log(bn) + 0.5 * np.log(l0 / kn) - n / 2 * np.log(2 * np.pi)
for data in (x, np.random.default_rng(5).normal(0.5, 1.2, 80)):
r = [prior_mc(data, 1000, np.random.default_rng(s)) for s in range(5)]
print(round(log_ev(data), 3), [round(float(v), 2) for v, _ in r], [int(e) for _, e in r])
# -15.511 [-15.59, -15.42, -15.51, -15.52, -15.43] [244, 283, 274, 255, 261]
# -124.051 [-124.21, -123.85, -124.28, -124.13, -123.92] [41, 48, 41, 38, 47]
# blocking mu and tau: the joint conditional is the whole normal-gamma posterior, so the draws are independent
tau = rng.gamma(aE, 1 / bE, size=9000); mu = rng.normal(mN, 1 / np.sqrt((l0 + N) * tau))
print(mu.std().round(3), int(ess(mu))) # 0.448 9000
# a reducible target: uniform on two squares that touch only at a corner; Gibbs never leaves the first
z = np.array([0.5, 0.5]); visits = 0
for s in range(10000):
z[0] = rng.uniform(0, 1) if z[1] > 0 else rng.uniform(-1, 0)
z[1] = rng.uniform(0, 1) if z[0] > 0 else rng.uniform(-1, 0)
visits += z[0] < 0
print(visits) # 0
# a common bug: updating both coordinates of a bivariate normal (rho = 0.9) from the old values, not the newest
rho, z1, z2, seq, par = 0.9, 0.0, 0.0, [], []
for s in range(20000):
z1 = rng.normal(rho * z2, np.sqrt(1 - rho ** 2)); z2 = rng.normal(rho * z1, np.sqrt(1 - rho ** 2)); seq.append((z1, z2))
y1, y2 = 0.0, 0.0
for s in range(20000):
y1, y2 = rng.normal(rho * y2, np.sqrt(1 - rho ** 2)), rng.normal(rho * y1, np.sqrt(1 - rho ** 2)); par.append((y1, y2))
print([round(float(np.corrcoef(np.array(c).T)[0, 1]), 3) for c in (seq, par)]) # [0.899, -0.009]
# a mixture of three unit-variance Gaussians in 1-D: pi ~ Dir(1, 1, 1), mu_k ~ N(0, 25)
K, s2, t2, alpha = 3, 1.0, 25.0, 1.0
xm = np.concatenate([rng.normal(-2.5, 1, 40), rng.normal(0, 1, 40), rng.normal(2.5, 1, 40)]); n = len(xm)
stat = lambda z: (z == z[0]).sum() # size of the cluster of the first point: does not depend on the labels
def standard(T, g): # pi, mu and z in turn
z, mu, out = np.zeros(n, int), np.zeros(K), []
for t in range(T):
nk = np.bincount(z, minlength=K)
pi = g.dirichlet(alpha + nk)
for k in range(K):
v = 1 / (1 / t2 + nk[k] / s2); mu[k] = g.normal(v * xm[z == k].sum() / s2, np.sqrt(v))
lw = np.log(pi) - 0.5 * (xm[:, None] - mu) ** 2 / s2
p = np.exp(lw - logsumexp(lw, axis=1, keepdims=True))
z = (p.cumsum(axis=1) < g.random(n)[:, None]).sum(axis=1)
out.append(stat(z))
return np.array(out)
def collapsed(T, g): # pi and mu integrated out: z_i | z_-i, one point at a time
z = np.zeros(n, int); nk = np.bincount(z, minlength=K).astype(float); sk = np.array([xm[z == k].sum() for k in range(K)]); out = []
for t in range(T):
for i in range(n):
nk[z[i]] -= 1; sk[z[i]] -= xm[i]
v = 1 / (1 / t2 + nk / s2); m = v * sk / s2 # posterior of mu_k from the other points
lw = np.log(nk + alpha) + (-0.5 * np.log(s2 + v) - 0.5 * (xm[i] - m) ** 2 / (s2 + v))
z[i] = g.choice(K, p=np.exp(lw - logsumexp(lw)))
nk[z[i]] += 1; sk[z[i]] += xm[i]
out.append(stat(z))
return np.array(out)
for f in (standard, collapsed):
a = f(2000, np.random.default_rng(1))
print(f.__name__, a[:6], a[200:].mean().round(1), int(ess(a[200:])))
# standard [20 33 40 51 51 55] 42.3 56
# collapsed [91 51 54 53 59 53] 40.1 213
Random-walk Metropolis–Hastings on the coin with a normal prior on the log-odds: the two moves of the worked example, the exact posterior moments by numerical integration, and the chain with and without its repeated states. It runs in about a second.
import numpy as np
from scipy import stats, integrate
from scipy.special import log_expit, expit
# the flips 1, 0, 1, 1, 0, 1, 1 with a N(0, 1.5^2) prior on the log-odds phi: the log of the unnormalized posterior
logp = lambda phi: 5 * log_expit(phi) + 2 * log_expit(-phi) + stats.norm.logpdf(phi, 0, 1.5)
print(round(float(logp(1.0) - logp(0.0)), 3), round(float(np.exp(logp(2.5) - logp(1.0))), 3)) # 0.437 0.08: the two moves
# exact posterior mean and standard deviation of f = sigmoid(phi), by numerical integration over phi
Z = integrate.quad(lambda p: np.exp(logp(p)), -20, 20)[0]
m1, m2 = (integrate.quad(lambda p: expit(p) ** j * np.exp(logp(p)), -20, 20)[0] / Z for j in (1, 2))
print(round(m1, 3), round(np.sqrt(m2 - m1 ** 2), 3)) # 0.665 0.148
# random-walk Metropolis with step 1.5: a rejected proposal records the current state again
rng = np.random.default_rng(0)
phi, lp, out, acc = 0.0, logp(0.0), [], 0
for s in range(20000):
y = phi + 1.5 * rng.normal(); ly = logp(y)
if np.log(rng.uniform()) < ly - lp: phi, lp, acc = y, ly, acc + 1
out.append(phi)
f = expit(np.array(out[1000:])) # 1000 steps of burn-in
moved = np.r_[True, np.diff(f) != 0] # the draws left if repeats are dropped
print(round(acc / 20000, 3), round(f.mean(), 3), round(f.std(), 3), round(f[moved].std(), 3))
# 0.489 0.665 0.147 0.154: acceptance rate, mean and standard deviation of f, and the standard deviation without the repeats
Next#
This part of the course approximated posteriors that have no formula, by EM, by variational inference and by sampling. The next part changes the models. In a Gaussian process the unknown is a whole function, and the number of parameters grows with the data. For regression with Gaussian noise its posterior is again exact and Gaussian; the approximations of this part return when the likelihood is not Gaussian, as in classification.
References#
- S. Geman, D. Geman. Stochastic Relaxation, Gibbs Distributions, and the Bayesian Restoration of Images. IEEE Transactions on Pattern Analysis and Machine Intelligence, 6(6), 721–741, 1984.
- A. E. Gelfand, A. F. M. Smith. Sampling-Based Approaches to Calculating Marginal Densities. Journal of the American Statistical Association, 85(410), 398–409, 1990.
- J. S. Liu, W. H. Wong, A. Kong. Covariance Structure of the Gibbs Sampler with Applications to the Comparisons of Estimators and Augmentation Schemes. Biometrika, 81(1), 27–40, 1994.
- J. S. Liu. The Collapsed Gibbs Sampler in Bayesian Computations with Applications to a Gene Regulation Problem. Journal of the American Statistical Association, 89(427), 958–966, 1994. Theorem 1 (the three-schemes theorem).
- A. Gelman, D. B. Rubin. Inference from Iterative Simulation Using Multiple Sequences. Statistical Science, 7(4), 457–472, 1992.
- A. Vehtari, A. Gelman, D. Simpson, B. Carpenter, P.-C. Bürkner. Rank-Normalization, Folding, and Localization: An Improved R̂ for Assessing Convergence of MCMC. Bayesian Analysis, 16(2), 667–718, 2021.
- S. Chib. Marginal Likelihood from the Gibbs Output. Journal of the American Statistical Association, 90(432), 1313–1321, 1995.
- T. L. Griffiths, M. Steyvers. Finding Scientific Topics. Proceedings of the National Academy of Sciences, 101(suppl. 1), 5228–5235, 2004.
- W. R. Gilks, P. Wild. Adaptive Rejection Sampling for Gibbs Sampling. Applied Statistics, 41(2), 337–348, 1992.
- S. N. MacEachern, L. M. Berliner. Subsampling the Gibbs Sampler. The American Statistician, 48(3), 188–190, 1994.
- C. P. Robert, G. Casella. Monte Carlo Statistical Methods, 2nd edition. Springer, 2004. Chapters 9 and 10 (the two-stage and multi-stage Gibbs samplers).
- C. M. Bishop. Pattern Recognition and Machine Learning. Springer, 2006. Section 11.3 (Gibbs sampling).
- K. P. Murphy. Probabilistic Machine Learning: Advanced Topics. MIT Press, 2023. Section 12.3 (Gibbs sampling: Ising models, mixtures, Metropolis within Gibbs, blocked and collapsed samplers).
- Cambridge University Engineering Department, 4F13 Probabilistic Machine Learning, 2025/26. Course page; lectures on Gibbs sampling, Gibbs sampling in TrueSkill, and Gibbs sampling for the Bayesian mixture.
- D. P. Vetrov, D. A. Kropotov. Байесовские методы машинного обучения, lecture course, Moscow State University, 2015. Course page; lecture 8, Markov chain Monte Carlo methods (notes).
- Конспект курса «Байесовские методы в анализе данных», 2026, github.com/bmml-team/bmml_ftda, лекция 4.