Course contents 09 / 15

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 0.4100.410 for the mean. The exact value is 0.4490.449, and nothing in the method revealed the error. To measure such an error, or to avoid it, we need draws from the exact posterior p(Z∣X)p(Z \mid X).

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 0.4490.449 for μ\mu and 0.2700.270 for λ\lambda, and λ\lambda 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 p(X)p(X) cancels:

p(θ′∣X)p(θ∣X)=p(X∣θ′) p(θ′)/p(X)p(X∣θ) p(θ)/p(X)(Bayes)=p~(θ′)p~(θ),\begin{aligned} \frac{p(\theta' \mid X)}{p(\theta \mid X)} &= \frac{p(X \mid \theta')\, p(\theta') / p(X)}{p(X \mid \theta)\, p(\theta) / p(X)} \quad \text{(Bayes)} \\ &= \frac{\tilde p(\theta')}{\tilde p(\theta)} , \end{aligned}

where p~(θ)=p(X∣θ) p(θ)\tilde p(\theta) = p(X \mid \theta)\, p(\theta) is the unnormalized posterior. From the current θ\theta, the sampler proposes θ′∼q(θ′∣θ)\theta' \sim q(\theta' \mid \theta) and accepts it with probability

α(θ,θ′)=min⁡(1, p~(θ′) q(θ∣θ′)p~(θ) q(θ′∣θ)).\alpha(\theta, \theta') = \min\Big(1,\ \frac{\tilde p(\theta')\, q(\theta \mid \theta')}{\tilde p(\theta)\, q(\theta' \mid \theta)}\Big) .

If the proposal is rejected, the chain stays at θ\theta and records θ\theta again as its next draw. The repeat counts. It is how the chain spends more time where p~\tilde p 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 θ′=θ+sε\theta' = \theta + s\varepsilon with ε∼N(0,1)\varepsilon \sim \mathcal N(0, 1), the two values of qq cancel.

Worked example. Take the seven flips 1,0,1,1,0,1,11, 0, 1, 1, 0, 1, 1 of the conjugate priors note, five heads and two tails, with a prior that has no conjugate form: the log-odds of heads, ϕ=log⁡(f/(1−f))\phi = \log\big(f / (1 - f)\big), is N(0,1.52)\mathcal N(0, 1.5^2). Since f=σ(ϕ)f = \sigma(\phi) and 1−f=σ(−ϕ)1 - f = \sigma(-\phi), the likelihood f5(1−f)2f^5 (1 - f)^2 and the prior density give

log⁡p~(ϕ)=5log⁡σ(ϕ)+2log⁡σ(−ϕ)−ϕ24.5+const.\log \tilde p(\phi) = 5 \log \sigma(\phi) + 2 \log \sigma(-\phi) - \frac{\phi^2}{4.5} + \text{const} .

A random walk with step s=1.5s = 1.5 is symmetric, so α=min⁡(1,p~(ϕ′)/p~(ϕ))\alpha = \min\big(1, \tilde p(\phi') / \tilde p(\phi)\big). Two moves, with the change of each term of log⁡p~\log \tilde p:

Moveheads termtails termprior termlog ratioα\alpha
0→10 \to 1+1.899+1.899−1.240-1.240−0.222-0.222+0.437+0.43711
1→2.51 \to 2.5+1.172+1.172−2.531-2.531−1.167-1.167−2.526-2.5260.0800.080

The first move is uphill and always accepted. The second proposes f=σ(2.5)=0.924f = \sigma(2.5) = 0.924, more extreme than five heads in seven support, and is accepted only if a uniform draw falls below 0.0800.080. When it does not, the chain records ϕ=1\phi = 1 a second time, and the draws so far read 0,1,10, 1, 1.

Over 20,000 steps, after 1,000 of burn-in, the sampler accepts 49% of its proposals. Its draws give a posterior mean of ff of 0.6650.665 and a standard deviation of 0.1470.147, against 0.6650.665 and 0.1480.148 from numerical integration over ϕ\phi, which one dimension makes cheap. Dropping the repeated states raises the standard deviation to 0.1540.154: 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 α\alpha 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 Z=(Z1,…,Zm)Z = (Z_1, \dots, Z_m), and write z−jz_{-j} for all blocks except zjz_j; we write the target as p(z)p(z), leaving the data implicit. One sweep with a fixed order of blocks, from the current state z(t)z^{(t)}, is

z1(t+1)∼p(z1∣z2(t),z3(t),…,zm(t)),z2(t+1)∼p(z2∣z1(t+1),z3(t),…,zm(t)),    ⋮zm(t+1)∼p(zm∣z1(t+1),…,zm−1(t+1)).\begin{aligned} z_1^{(t+1)} &\sim p\big(z_1 \mid z_2^{(t)}, z_3^{(t)}, \dots, z_m^{(t)}\big), \\ z_2^{(t+1)} &\sim p\big(z_2 \mid z_1^{(t+1)}, z_3^{(t)}, \dots, z_m^{(t)}\big), \\ &\;\;\vdots \\ z_m^{(t+1)} &\sim p\big(z_m \mid z_1^{(t+1)}, \dots, z_{m-1}^{(t+1)}\big) . \end{aligned}

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 jj is found exactly as a mean-field factor was, by reading log⁡p(X,z)\log p(X, z) as a function of zjz_j alone,

log⁡p(zj∣z−j,X)=log⁡p(X,z)+const,\log p(z_j \mid z_{-j}, X) = \log p(X, z) + \text{const},

so it involves only the Markov blanket of zjz_j in the graphical model. Mean field sets a factor to the normalized exp⁡E−j[log⁡p(X,Z)]\exp \mathbb E_{-j}[\log p(X, Z)], averaging over the other blocks. Gibbs draws a value from the normalized p(X,z)p(X, z) at the current values of the others.

A discrete block can be drawn back to its old value. A label with KK values is redrawn from its conditional over all KK 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 0.90.9, the Code section finds a sample correlation of 0.8990.899 with the sequential update and −0.009-0.009 with the simultaneous one. The covariance shows why. The simultaneous update draws z1′=ρz2+e1z_1' = \rho z_2 + e_1 and z2′=ρz1+e2z_2' = \rho z_1 + e_2 with independent noises e1,e2e_1, e_2, so Cov⁡(z1′,z2′)=ρ2Cov⁡(z2,z1)\operatorname{Cov}(z_1', z_2') = \rho^2 \operatorname{Cov}(z_2, z_1), whose only fixed point is zero. The variances still settle at 1, from Var⁡(z1′)=ρ2Var⁡(z2)+1−ρ2\operatorname{Var}(z_1') = \rho^2 \operatorname{Var}(z_2) + 1 - \rho^2, 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 zz is distributed according to pp. Then z−jz_{-j} has the marginal p(z−j)p(z_{-j}), and the new zj′z_j' is drawn from p(zj∣z−j)p(z_j \mid z_{-j}), so the new state has density p(zj′∣z−j) p(z−j)=p(zj′,z−j)p(z_j' \mid z_{-j})\, p(z_{-j}) = p(z_j', z_{-j}), the target again. In terms of the transition density Kj(z→z′)K_j(z \to z') of the update of block jj, which leaves z−j′=z−jz_{-j}' = z_{-j},

∫Kj(z→z′) p(z) dz=∫p(zj′∣z−j′) p(zj,z−j′) dzj=p(zj′∣z−j′) p(z−j′)=p(z′).\begin{aligned} \int K_j(z \to z')\, p(z)\, dz &= \int p(z_j' \mid z_{-j}')\, p(z_j, z_{-j}')\, dz_j \\ &= p(z_j' \mid z_{-j}')\, p(z_{-j}') \\ &= p(z') . \end{aligned}

A sweep is a composition of such updates, and a composition of transitions that each preserve pp preserves pp.

Each update is also a Metropolis–Hastings step that is always accepted. With the proposal q(z′∣z)=p(zj′∣z−j)q(z' \mid z) = p(z_j' \mid z_{-j}) and z−j′=z−jz_{-j}' = z_{-j}, the acceptance ratio is

p(z′) q(z∣z′)p(z) q(z′∣z)=p(zj′∣z−j) p(z−j) p(zj∣z−j)p(zj∣z−j) p(z−j) p(zj′∣z−j)=1.\begin{aligned} \frac{p(z')\, q(z \mid z')}{p(z)\, q(z' \mid z)} &= \frac{p(z_j' \mid z_{-j})\, p(z_{-j})\, p(z_j \mid z_{-j})}{p(z_j \mid z_{-j})\, p(z_{-j})\, p(z_j' \mid z_{-j})} \\ &= 1 . \end{aligned}

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 K1K_1 then K2K_2 becomes K2K_2 then K1K_1, a different transition. The random-order version is reversible, because its transition is the average 1m∑jKj\frac1m \sum_j K_j and each KjK_j 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 R×(0,∞)\mathbb R \times (0, \infty), satisfies it; the last section shows a target that does not.

Why positivity suffices

Take two points zz and z′z' of the support. Every density along a sweep from zz to z′z', such as p(z1′∣z2,…,zm)p(z_1' \mid z_2, \dots, z_m), has a joint density in its numerator at a point whose blocks come from zz or z′z'. 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 N(μ,λ−1)\mathcal N(\mu, \lambda^{-1}), the prior μ∣λ∼N(μ0,(κ0λ)−1)\mu \mid \lambda \sim \mathcal N\big(\mu_0, (\kappa_0\lambda)^{-1}\big) with μ0=0\mu_0 = 0 and κ0=1\kappa_0 = 1, and λ∼Gamma(a0,b0)\lambda \sim \mathrm{Gamma}(a_0, b_0) with a0=b0=2a_0 = b_0 = 2. Read as a function of μ\mu alone, its log joint is a quadratic with leading coefficient −(κ0+n)λ2-\frac{(\kappa_0 + n)\lambda}{2} and maximum at μn\mu_n. Read as a function of λ\lambda alone, it is the logarithm of a gamma density. The complete conditionals are therefore

μ∣λ,X∼N(μn, 1(κ0+n)λ),λ∣μ,X∼Gamma(a0+n+12, b(μ)),\begin{aligned} \mu \mid \lambda, X &\sim \mathcal N\Big(\mu_n,\ \frac{1}{(\kappa_0 + n)\lambda}\Big), \\ \lambda \mid \mu, X &\sim \mathrm{Gamma}\Big(a_0 + \frac{n + 1}{2},\ b(\mu)\Big), \end{aligned}

where μn=(κ0μ0+nxˉ)/(κ0+n)=0.478\mu_n = (\kappa_0 \mu_0 + n\bar x)/(\kappa_0 + n) = 0.478 and

b(μ)=b0+12(∑i=1n(xi−μ)2+κ0(μ−μ0)2).b(\mu) = b_0 + \frac12 \Big(\sum_{i=1}^n (x_i - \mu)^2 + \kappa_0 (\mu - \mu_0)^2\Big) .

These are the mean-field factors of the previous note, with E[λ]\mathbb E[\lambda] replaced by the current λ\lambda and the average over μ\mu by the value at the current μ\mu.

Worked example. Start at (μ,λ)=(1.7,1.7)(\mu, \lambda) = (1.7, 1.7). The conditional of μ\mu is a normal with mean 0.4780.478 and precision 9⋅1.7=15.39 \cdot 1.7 = 15.3, standard deviation 0.2560.256; the draw is μ=0.87\mu = 0.87. At this μ\mu the conditional of λ\lambda is Gamma(6.5,9.78)\mathrm{Gamma}(6.5, 9.78), with mean 0.660.66; the draw is λ=0.91\lambda = 0.91. One sweep has moved the chain from the edge of the posterior into its bulk.

Figure

One Gibbs sweep: first μ, then λ

One Gibbs sweep: first μ, then λThe (μ, λ) plane with contours of the exact posterior. From a point at the upper right the chain moves horizontally towards the centre (above this segment, the bell of the conditional of μ), then vertically down (to its right, the gamma density of λ), and then wanders over the contours in steps.00.511.52−0.500.511.52μλ4123exact posterior p(μ, λ | X)Gibbs chainconditional distributionsOne Gibbs sweep: first μ, then λThe (μ, λ) plane with contours of the exact posterior. From a point at the upper right the chain moves horizontally towards the centre (above this segment, the bell of the conditional of μ), then vertically down (to its right, the gamma density of λ), and then wanders over the contours in steps.00.511.52−0.500.511.52μλ4123exact posterior p(μ, λ | X)Gibbs chainconditional distributions
The normal model of the variational-inference note; blue: contours of the exact posterior. Step 2: at λ = 1.7, μ is drawn from a normal with mean 0.478 and precision 15.3 (amber bell): μ = 0.87. Step 3: λ is drawn from Gamma(6.5, 9.78) (amber curve): λ = 0.91. Step 4: the first 30 sweeps, each move along an axis.

Now run four chains of 10,000 sweeps from the dispersed starts (−0.5,0.3)(-0.5, 0.3), (1.5,0.3)(1.5, 0.3), (−0.5,1.6)(-0.5, 1.6) and (1.5,1.6)(1.5, 1.6), and discard the first 1,000 sweeps of each:

Gibbs, 4×9,0004 \times 9{,}000 drawsexact
posterior mean of μ\mu0.4780.4780.4780.478
posterior standard deviation of μ\mu0.4520.4520.4490.449
posterior mean of λ\lambda0.6600.6600.6610.661

The Monte Carlo error of the standard deviation is about 0.0020.002. The difference of 0.0030.003 is noise of the expected size, and unlike the 0.0390.039 of mean field it shrinks as the chains get longer.

Where 0.002 comes from

For NN independent draws with variance σ2\sigma^2 and excess kurtosis κ\kappa, the sample variance has variance (2+κ)σ4/N(2 + \kappa)\sigma^4/N. The derivative of the square root at σ2\sigma^2 is 1/(2σ)1/(2\sigma), so the delta method gives the standard deviation an error of σ(2+κ)/(4N)\sigma\sqrt{(2 + \kappa)/(4N)}. The marginal of μ\mu is a Student tt with ν=12\nu = 12 degrees of freedom, κ=6/(ν−4)=0.75\kappa = 6/(\nu - 4) = 0.75, and the draws of μ\mu are nearly independent (next paragraph), so N=36,000N = 36{,}000 gives 0.449⋅0.0044=0.0020.449 \cdot 0.0044 = 0.002.

This sampler mixes unusually well. The conditional mean of μ\mu is μn\mu_n whatever λ\lambda is, so successive draws of μ\mu are uncorrelated: by the tower rule, E[μ(t+1)∣μ(t)]=E[E[μ(t+1)∣λ(t)]∣μ(t)]=μn\mathbb E[\mu^{(t+1)} \mid \mu^{(t)}] = \mathbb E\big[\mathbb E[\mu^{(t+1)} \mid \lambda^{(t)}] \mid \mu^{(t)}\big] = \mu_n, a constant, and a constant has zero covariance with μ(t)\mu^{(t)}. The lag-1 autocorrelation is −0.002-0.002, and each chain’s 9,000 draws of μ\mu are worth 9,000 independent ones. For λ\lambda the lag-1 autocorrelation is 0.050.05, 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 ρ=0.9\rho = 0.9, successive draws of one coordinate have correlation ρ2=0.81\rho^2 = 0.81 (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:

p(x∗∣X)=Ep(μ,λ∣X)[N(x∗∣μ,λ−1)]≈1S∑s=1SN(x∗∣μ(s),(λ(s))−1).\begin{aligned} p(x_* \mid X) &= \mathbb E_{p(\mu, \lambda \mid X)}\big[\mathcal N(x_* \mid \mu, \lambda^{-1})\big] \\ &\approx \frac1S \sum_{s=1}^S \mathcal N\big(x_* \mid \mu^{(s)}, (\lambda^{(s)})^{-1}\big) . \end{aligned}

We average the density at each draw instead of making a histogram of simulated values of x∗x_*. The density at a draw is the conditional probability of a small interval around x∗x_* 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 x∗=3x_* = 3 the 36,000 draws of the four chains give 0.05080.0508, against 0.05070.0507 for the exact Student-t predictive.

The evidence is an expectation too, over the prior: by the sum rule, p(X)=∫p(X∣θ) p(θ) dθ=Ep(θ)[p(X∣θ)]p(X) = \int p(X \mid \theta)\, p(\theta)\, d\theta = \mathbb E_{p(\theta)}\big[p(X \mid \theta)\big]. 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 ∫p(X∣θ) p(θ) dθ\int p(X \mid \theta)\, p(\theta)\, d\theta with the prior as the proposal qq: the weight of a draw, p(X∣θ) p(θ)/q(θ)p(X \mid \theta)\, p(\theta) / q(\theta), is then its likelihood. The effective sample size of the weights p(X∣θ(s))p(X \mid \theta^{(s)}) measures the waste. For the normal model, with 1000 prior draws repeated five times:

Dataexact log evidencefive estimateseffective sample sizes
the eight points−15.511-15.511−15.59-15.59 to −15.42-15.42244 to 283
eighty new points−124.051-124.051−124.28-124.28 to −123.85-123.8538 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 1/n1/\sqrt n, as in the coin example, so the fraction falls roughly like n−d/2n^{-d/2} for dd parameters. For d=2d = 2 that predicts a tenfold fall from eight to eighty points; the effective sample size fell sixfold, since the 1/n1/\sqrt n 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 1/p(X∣θ)1/p(X \mid \theta), largest in the tails where the posterior has few draws. Its mean is right, Ep(θ∣X)[1/p(X∣θ)]=∫p(θ) dθ/p(X)=1/p(X)\mathbb E_{p(\theta \mid X)}\big[1/p(X \mid \theta)\big] = \int p(\theta)\, d\theta / p(X) = 1/p(X), but its variance can be infinite (details below). Chib (1995) takes the logarithm of Bayes’ formula at one point θ∗\theta^*, log⁡p(X)=log⁡p(X∣θ∗)+log⁡p(θ∗)−log⁡p(θ∗∣X)\log p(X) = \log p(X \mid \theta^*) + \log p(\theta^*) - \log p(\theta^* \mid X). For the normal model, p(μ∗,λ∗∣X)=p(λ∗∣μ∗,X) p(μ∗∣X)p(\mu^*, \lambda^* \mid X) = p(\lambda^* \mid \mu^*, X)\, p(\mu^* \mid X) by the product rule. The first factor is a complete conditional, and the second is the average of the complete conditional p(μ∗∣λ,X)p(\mu^* \mid \lambda, X) over the Gibbs draws of λ\lambda, by the sum rule.

Why the harmonic mean can have infinite variance

Its second moment is ∫p(θ)/p(X∣θ) dθ\int p(\theta) / p(X \mid \theta)\, d\theta divided by p(X)p(X): the posterior density cancels one factor of the likelihood. With a Gaussian likelihood for nn points of known precision λ\lambda, 1/p(X∣μ)1/p(X \mid \mu) grows like enλ(μ−xˉ)2/2e^{n\lambda(\mu - \bar x)^2/2}. Against a normal prior of variance s02s_0^2 the integral is finite only if s02<1/(nλ)s_0^2 \lt 1/(n\lambda), 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 λ∼Gamma(an,bn)\lambda \sim \mathrm{Gamma}(a_n, b_n) and then μ∣λ\mu \mid \lambda: the Code section’s 9,000 draws give a standard deviation of 0.4480.448 and an effective sample size of 9,000. For a correlated Gaussian, drawing both coordinates together removes the ρ2\rho^2 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 p(z1,z2,z3)p(z_1, z_2, z_3) it samples p(z1,z2)=∫p(z1,z2,z3) dz3p(z_1, z_2) = \int p(z_1, z_2, z_3)\, dz_3 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 z2z_2 and z3z_3 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 KK Gaussians in one dimension with known variance σ2\sigma^2: weights π∼Dir(α,…,α)\pi \sim \mathrm{Dir}(\alpha, \dots, \alpha), means μk∼N(0,s02)\mu_k \sim \mathcal N(0, s_0^2), labels zi∣π∼Cat(π)z_i \mid \pi \sim \mathrm{Cat}(\pi) and xi∣zi,μ∼N(μzi,σ2)x_i \mid z_i, \mu \sim \mathcal N(\mu_{z_i}, \sigma^2). With nkn_k the number of points with label kk, the standard sampler cycles three conjugate conditionals:

π∣z∼Dir(α+n1,…,α+nK),μk∣z,x∼N(mk,vk),p(zi=k∣π,μ,xi)∝πk N(xi∣μk,σ2),\begin{aligned} \pi \mid z &\sim \mathrm{Dir}(\alpha + n_1, \dots, \alpha + n_K), \\ \mu_k \mid z, x &\sim \mathcal N(m_k, v_k), \\ p(z_i = k \mid \pi, \mu, x_i) &\propto \pi_k\, \mathcal N(x_i \mid \mu_k, \sigma^2), \end{aligned}

where vk=(1/s02+nk/σ2)−1v_k = (1/s_0^2 + n_k/\sigma^2)^{-1} and mk=vk∑i:zi=kxi/σ2m_k = v_k \sum_{i: z_i = k} x_i / \sigma^2, the normal–normal update. Given π\pi and μ\mu the labels are independent, so all of them are drawn at once.

The collapsed sampler integrates π\pi and μ\mu out and samples the labels alone, one at a time. By Bayes’ formula, p(zi=k∣z−i,x)∝p(zi=k∣z−i) p(xi∣zi=k,z−i,x−i)p(z_i = k \mid z_{-i}, x) \propto p(z_i = k \mid z_{-i})\, p(x_i \mid z_i = k, z_{-i}, x_{-i}). The first factor is the Dirichlet–categorical predictive probability, a count plus a pseudo-count. The second is the posterior predictive density of xix_i under component kk, given the other points with that label. Given them, μk∼N(mk−i,vk−i)\mu_k \sim \mathcal N(m_k^{-i}, v_k^{-i}) by the normal–normal update, and xi=μk+εx_i = \mu_k + \varepsilon with independent noise of variance σ2\sigma^2, so by the linear-Gaussian marginal xix_i is normal with mean mk−im_k^{-i} and variance σ2+vk−i\sigma^2 + v_k^{-i}. So

p(zi=k∣z−i,x)∝nk−i+αn−1+Kα×N(xi∣mk−i, σ2+vk−i),\begin{aligned} p(z_i = k \mid z_{-i}, x) \propto{}& \frac{n_k^{-i} + \alpha}{n - 1 + K\alpha} \\ &\times \mathcal N\big(x_i \mid m_k^{-i},\ \sigma^2 + v_k^{-i}\big), \end{aligned}

where nk−in_k^{-i}, mk−im_k^{-i} and vk−iv_k^{-i} are computed without point ii. 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 −2.5-2.5, 00 and 2.52.5, with K=3K = 3, α=1\alpha = 1, s02=25s_0^2 = 25 and σ2=1\sigma^2 = 1. 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:

standardcollapsed
effective sample size of 1,800 sweeps56213
average size of the cluster of the first point42.342.340.140.1

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 ii has a skill wiw_i with a Gaussian prior. In game gg, between players IgI_g and JgJ_g, the performance difference is tg∼N(wIg−wJg,1)t_g \sim \mathcal N(w_{I_g} - w_{J_g}, 1), 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 tgt_g added as unknowns, both conditionals are standard. Given the skills, each tgt_g 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-tt likelihood into a Gaussian one: a tt 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, ∫0∞λc−1e−dλ dλ=Γ(c)/dc\int_0^\infty \lambda^{c-1} e^{-d\lambda}\, d\lambda = \Gamma(c)/d^c, with c=(ν+1)/2c = (\nu + 1)/2:

∫0∞N(x∣μ,(τu)−1) Gamma(u∣ν2,ν2) du∝∫0∞uν+12−1e−u(ν2+τ(x−μ)22) du∝(1+τ(x−μ)2ν)−ν+12,\begin{aligned} &\int_0^\infty \mathcal N\big(x \mid \mu, (\tau u)^{-1}\big)\, \mathrm{Gamma}\big(u \mid \tfrac\nu2, \tfrac\nu2\big)\, du \\ &\quad\propto \int_0^\infty u^{\frac{\nu + 1}{2} - 1} e^{-u\big(\frac\nu2 + \frac{\tau (x - \mu)^2}{2}\big)}\, du \\ &\quad\propto \Big(1 + \frac{\tau (x - \mu)^2}{\nu}\Big)^{-\frac{\nu + 1}{2}} , \end{aligned}

the Student-tt density with ν\nu 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 R^\hat R, a version of the potential scale reduction factor of Gelman and Rubin (1992), cuts each of MM chains in half and compares the 2M2M halves of length hh. With WW the average variance within the halves and BB the variance of the half means times hh,

R^=h−1h W+1h BW,\hat R = \sqrt{\frac{\frac{h - 1}{h}\, W + \frac1h\, B}{W}} ,

which approaches 1 when the halves agree. Vehtari et al. (2021) recommend a rank-normalized version and treat R^≥1.01\hat R \ge 1.01, or a total effective sample size below 400, as a sign of trouble. The four chains of the normal model give R^=1.0000\hat R = 1.0000 for both μ\mu and λ\lambda.

Second, in mixtures and other models with symmetric labels, monitor what the labels cannot change. R^\hat R 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 kk-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 kk thinned averages that start at sweeps 1,…,k1, \dots, k. In a stationary chain they have equal variances vv, and by the Cauchy–Schwarz inequality every covariance between them is at most vv, so the variance of their mean is at most vv (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.

Figure

Bias against variance: Gibbs and mean field

Bias against variance: Gibbs and mean fieldFour jagged lines spread from 0.28 to 0.53 at small n that converge by n = 10,000 to the horizontal line at 0.449. Below it, the horizontal mean-field line at 0.410, which the chains do not approach.estimated sd of μ0.30.40.50.610100100010,000sweeps nexact: 0.449mean field: 0.410four Gibbs chainsBias against variance: Gibbs and mean fieldFour jagged lines spread from 0.28 to 0.53 at small n that converge by n = 10,000 to the horizontal line at 0.449. Below it, the horizontal mean-field line at 0.410, which the chains do not approach.estimated sd of μ0.30.40.50.610100100010,000sweeps nexactmean field
The posterior standard deviation of μ in the normal model. Thin lines: four Gibbs chains, each the sample standard deviation of its first n draws, from 0.28–0.53 after 10 sweeps to 0.443–0.449 after 10,000. Blue: the exact 0.449. Red: mean field, 0.410 at once, biased low by 0.039.

Mean field reports the posterior standard deviation of μ\mu as 0.4100.410 at once and with no randomness. Its error, 0.0390.039, 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 0.280.28 and 0.530.53 after 10 sweeps, between 0.4430.443 and 0.4490.449 after 10,000, shrinking roughly like one over the square root of the number of sweeps, σ/ESS\sigma/\sqrt{\mathrm{ESS}} 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 inferenceGibbs sampling
UsesE−j[log⁡p(X,Z)]\mathbb E_{-j}[\log p(X, Z)] for each blockdraws from p(zj∣z−j,X)p(z_j \mid z_{-j}, X) for each block
Resulta distribution qq in closed formcorrelated samples from the exact posterior, in the limit
Errorbias: too narrow, one mode, correlations lostvariance: about σ/ESS\sigma/\sqrt{\mathrm{ESS}}
More computationno improvement after convergencethe error keeps shrinking
Evidencea lower bound L(q)\mathcal L(q)needs a further method, for example Chib (1995)
Convergence checkthe bound stops increasingseveral chains, R^\hat R, ESS
Scales tolarge data, with the stochastic versionmoderate 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 pp be uniform on the union of the squares [0,1]2[0, 1]^2 and [−1,0]2[-1, 0]^2, which touch only at a corner. From a point in the first square, the conditional of z1z_1 given z2>0z_2 > 0 is uniform on [0,1][0, 1], and so is the conditional of z2z_2 given z1>0z_1 > 0. 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 pp, the equal mixture of the two. The positivity condition fails: the product of the marginals is positive on [0,1]×[−1,0][0, 1] \times [-1, 0], where pp 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 p(zj∣z−j)p(z_j \mid z_{-j}), always given the newest values of the others.
  • Metropolis–Hastings needs only p(X∣θ) p(θ)p(X \mid \theta)\, p(\theta), 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 R^<1.01\hat R \lt 1.01 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 R^\hat R 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#