This page explains, in the order words → formulas → calculation procedure, what the “traveler’s footprints” and the “ways of tracing with a bell” seen in the simulator correspond to in the language of probability, and with what formulas they are computed. The procedure, the conditions of the calculation, and the questions for checking for the detailed view are also collected here.
▶ Open the simulator (simple view)▶ Open the detailed view
The Approximate Inference and MCMC Simulator compares two ways of handling a probability distribution that is hard to handle with formulas (for example, a posterior distribution): copying it by walking around with random numbers (Markov chain Monte Carlo, MCMC), and tracing it with a distribution of a simple shape (the Laplace approximation and variational inference). It covers Chapter 20 (approximate inference) and Chapter 21 (sampling methods).
The simulator has two views.
Scene A is computed with the same functions as ② of the detailed view, and Scene B with the same functions as ①. We recommend reading in this order: try the simple view, check what it really shows in Section 2, read the formulas in Section 3, and operate the detailed view with the procedure in Section 4.
The “shape of the hills” and the “shape with two humps” in the simple view are curves of the probability density of a probability distribution. The horizontal axis is the value x, the vertical axis is how likely that value is, and the area under the curve is 1. The higher the hill, the more likely that value is to appear. The scale of the vertical axis is omitted in the simple view.
The traveler’s way of walking is the Metropolis–Hastings algorithm (MH algorithm) itself. The target shape is the same double well as the default of ② in the detailed view, p̃(x) = exp[−2(x2 − 1)2] (barrier b = 2), with two hills of the same height at x = ±1 and a valley at x = 0. The sequence of footprints left by the traveler is the MCMC sample, and the fact that the pile of counted footprints (the histogram) gets close to the target shape is what it means that MCMC can copy a distribution.
| Words on the screen | Term | Symbol or formula |
|---|---|---|
| Top: target shape (the hills in the top picture), dotted = target shape | Target distribution (the unnormalized density and the normalized density) | p̃(x) = exp[−b(x2 − 1)2], b = 2. p(x) = p̃(x)/Z |
| Traveler (where the traveler is) | Current state of the chain | x(t) |
| Traveler’s step size: Small / Just right / Big | Proposal width (the standard deviation of the Gaussian random-walk proposal) | s = 0.03, 1, 10 |
| Candidate (the spot to try next) | Proposal | x′ = x + sε, ε ~ 𝒩(0, 1) |
| Candidate is ○ × as high | Acceptance ratio (capped at 1, it is the acceptance probability) | r = p̃(x′)/p̃(x), acceptance probability min(1, r) |
| Random draw | Uniform random number | u ∈ [0, 1) |
| Go / stay | Acceptance / rejection | If u < min(1, r), then x ← x′ |
| Footprint (a step that could not move also leaves one, in place) | Sample (on rejection, the current value is counted once more) | x(1), …, x(N) |
| Pile of footprints | Histogram of the samples (heights scaled to area 1; 48 bins) | — |
| Fraction that moved | Acceptance rate | number of acceptances / N |
| Fraction on the left hill (target 0.50) | Fraction of samples with x < 0, and its true probability | P(x < 0) = 0.50 |
The rule written in the picture, “go higher always; go lower with chance = height ratio (half as high: 1 time in 2),” puts the acceptance probability min(1, r) into words (the proposal x′ = x + sε is a symmetric proposal, equally likely to go and to come back, so the acceptance probability is decided by the height ratio alone). Because only the height ratio is used, multiplying the whole hill by any factor does not change the walk. Therefore the traveler can walk with the unnormalized density p̃(x) as it is, without knowing the number Z that scales the area to 1. Because the traveler also moves to a lower spot with probability r, the traveler does not stay at the top of a hill but sometimes goes down into the valley and crosses it to the other hill. Therefore, with enough steps, footprints are left in proportion to the height of the hills (Section 3.2). “Just 1 step (look closely)” shows the candidate, the two heights, and the value of the random draw in turn, and shows how this rule decides one step.
Numbers from “Try it” (all are values after walking 2000 steps from the starting point):
For reference, the effective sample size for the same 2000 steps (Seff of Section 3.4; no burn-in) is about 216 for the just-right step size and about 51 for the too-big step size. For the too-small step size, summing the autocorrelation up to half the series length still does not meet the truncation condition (“series too short”), so the effective sample size cannot be given reliably. The acceptance rate 0.45 is close to the one-dimensional rule of thumb 0.44 in Section 21.8 of the text, but this rule of thumb was reported for a unimodal Gaussian target and does not necessarily apply as it is to a target with two hills.
Where it fits: each step of the traveler computes the proposal, the acceptance ratio, the random draw, and acceptance/rejection with the same function as ② of the detailed view (mhStep). The starting point (x = −1.2327, the 5 % point of the target shape) and the sequence of random numbers are also the same as chain 1 of ② (seed 20261112, initial values “Spread”), so with the same step size the sequence of footprints is the same as chain 1 of ② in the detailed view. Leaving a footprint in place on a step that could not move corresponds to counting the same value once more in the sample when the MH algorithm rejects.
Where it does not fit: a real traveler looks at the destination and chooses it, but this traveler’s candidate is decided by random numbers, and whether to go is decided by a random draw after looking at the height of the candidate. The “height” of a hill is a probability density, not the height of terrain. In the language of physics, if we view p̃(x) = exp(−E/kBT), the high parts of the hills correspond to low-energy places (the bottoms of the wells). The walking motion of the traveler (the motion of jumping to the candidate) is for show in the picture and is not used in the calculation.
▶ Simulator (simple view) A: Can walking around copy the shape of the hills?
The shape to trace is the default “Bimodal” target of ① in the detailed view (w = 0.6, d = 6): a mixture of two Gaussians with standard deviation 1, with weight 0.6 at x = −3 and 0.4 at x = 3. The bell is a Gaussian q(x) = 𝒩(x | m, s2). The two ways of tracing correspond to the two directions of the KL divergence, which measures the mismatch between p and q.
| Words on the screen | Term | Symbol or formula |
|---|---|---|
| Green = shape to trace | Target distribution (Gaussian mixture) | p(x) = 0.6 𝒩(x | −3, 1) + 0.4 𝒩(x | 3, 1) |
| Bell (thick line) | Approximating distribution (the family of Gaussians) | q(x) = 𝒩(x | m, s2) |
| Middle of the bell, Width of the bell | Mean and standard deviation of q | m, s |
| Don’t spill over (no cover where there is none) | The q that minimizes KL(q‖p) (the q that maximizes the ELBO; variational inference) | Searched for numerically with the Nelder–Mead method |
| Don’t miss any (cover all that is there) | The q that minimizes KL(p‖q) | m = 𝔼p[x], s2 = Varp[x] |
| Where tracing starts: From the left / From the middle / From the right | Initial value for KL(q‖p) minimization | (m, s) = (−3, 2.5), (−0.6, 4), (3, 2.5) |
| / hatching (spill-over) | Where the bell is more than 3 times as high as the shape | q(x) > 3p(x) |
| \ hatching (missed) | Where the shape is more than 3 times as high as the bell | p(x) > 3q(x) |
| Estimated probability on the right (x > 0) (True shape: 0.40) | Probability under q, and the true probability under p | 1 − Φ(−m/s). True value 0.6Φ(−3) + 0.4Φ(3) = 0.40 |
| Size of the mismatch with the whole shape (“What we learned”) | KL(q‖p) (unit: nat) | — |
The results of tracing (the bell after pressing “▶ Trace with the bell”) are as follows.
| Way of tracing, starting place | Middle m | Width s | KL(q‖p) | Probability on the right |
|---|---|---|---|---|
| Don’t spill over, From the left | −2.99 | 1.02 | 0.51 | 0.00 |
| Don’t spill over, From the middle | −0.47 | 2.70 | 0.85 | 0.43 |
| Don’t spill over, From the right | 2.98 | 1.03 | 0.91 | 1.00 |
| Don’t miss any (independent of the starting place) | −0.60 | 3.10 | 0.94 | 0.42 |
With “Don’t spill over,” starting from the left the bell settles on the big left hump, starting from the right it settles on the right hump, and starting from the middle it stops as a wide bell straddling both. Each of these is a local minimum of KL(q‖p), and the smallest is when it settles on the left hump (0.51). “Don’t miss any” is the bell that matches the mean and variance, with KL(p‖q) = 0.46. In this case the middle of the bell is in the valley (x = −0.6), where the height of the bell is 0.13 but the height of the true shape is only 0.0137 (Example 20.8 of the text).
Where it fits: the traced bell is found with the same functions as ① of the detailed view (minKLqp, momentMatch). The starting bells have the same centers as the initial values of ① in the detailed view (near the left and right peaks, and wide from the center), and only their widths are changed (widened from 1 to 2.5 for “From the left” and “From the right,” and narrowed slightly from 4.66 to 4 for “From the middle,” so that motion can be seen when the button is pressed). The bell it ends up at is the same as when starting from the initial values of ① in the detailed view (the tests confirm a difference of 10−6 or less). “Don’t spill over” and “Don’t miss any” put into words the facts that the integrand of KL(q‖p), q ln(q/p), is large where q ≫ p, and that the integrand of KL(p‖q), p ln(p/q), is large where p ≫ q (Section 3.3).
Where it does not fit: even the “Don’t spill over” way of tracing does not make the spill-over zero. The factor 3 at the boundary of the hatching is a value chosen to make the picture easy to read and is not used in the calculation (the KL weights and adds up the mismatch everywhere). The smooth motion of the bell from the starting bell to the traced result is for show in the picture (the center m and ln s are moved at the same rate) and is not the path followed by the optimization (the Nelder–Mead method). The Laplace approximation and the ELBO bars in ① of the detailed view are not shown in the simple view.
▶ Simulator (simple view) B: What if you trace a two-humped shape with one bell?
For the posterior distribution of Bayesian estimation, p(θ | 𝒟) = p(𝒟, θ)/p(𝒟), even when the numerator p(𝒟, θ) can be written as a formula, the integral in the denominator (the marginal likelihood) p(𝒟) = ∫ p(𝒟, θ) dθ usually cannot be solved. In this simulator, what corresponds to the numerator is written as the unnormalized density p̃(x), and what corresponds to the denominator as Z. There are two ways to handle the distribution without knowing Z. One is to make samples from p and obtain means and probabilities as sample averages (MCMC; Chapter 21; Scene A). The other is to choose a distribution q of an easy-to-handle form and search for one close to p (the Laplace approximation and variational inference; Chapter 20; Scene B).
In the MH algorithm, a candidate x′ is made from the current point x, the ratio r = p̃(x′)/p̃(x) is computed, and the chain moves to the candidate with probability min(1, r) (Section 21.6 of the text). Because r is a ratio, the unknown Z cancels and is not needed. A candidate in the direction in which p̃ increases (r ≥ 1) is always accepted, and a candidate in the direction in which it decreases is accepted with probability r. By not only climbing the hill but sometimes going down, the chain visits even the tails of the distribution in the right proportions.
The one-step transition T(x′ | x) made in this way satisfies, if the proposal is symmetric (the probability of proposing x′ from x equals the probability of proposing x from x′), for x ≠ x′
(detailed balance; here q(x′ | x) is the probability density of the proposal and is different from the bell q of Scene B). This holds because the middle expression is symmetric in x and x′. When detailed balance holds, a traveler who starts from p is still distributed according to p after one step, so p is a distribution that does not change (the stationary distribution). Furthermore, if the chain can go from anywhere to anywhere in some number of steps (irreducibility) and has no rule that makes it return to the same place with a fixed period (aperiodicity), then wherever it starts, the fraction of footprints approaches p as the number of steps increases (Section 21.5 of the text). Counting the current value once more as a sample on rejection is to count the “stay in place” part of this transition T; if it is not counted, the distribution is distorted.
However, “approaches” refers to what happens when the number of steps is made large enough. With the too-small step size of Scene A, it takes a great many steps to reach the other side of the valley, and 2000 steps copy only one of the hills. It is not that the traveler cannot leave the hill: walking on with the same sequence of random numbers, this traveler crosses the valley for the first time at step 5,289 (even so, after 20000 steps the fraction on the left hill is 0.80, still far from the target 0.50). With a too-big step size, most candidates land beyond the foot of the hills and are rejected, and the traveler keeps staying at the same spot. In both cases, even though there are 2000 footprints, the number converted to independent samples (the effective sample size) is small (Section 21.8 of the text). The two steps in Example 21.6 of the text (candidate −1.6350 is rejected with r = 0.00634 and u = 0.7392; candidate −0.6667 is accepted with r = 0.926 and u = 0.7207) are the first two steps of chain 1 with the default of ② in the detailed view (s = 0.3), and they come from the same sequence of random numbers as the traveler of Scene A.
How far a distribution q is from p is measured with the KL divergence. The KL has different values and different properties depending on its direction (Section 20.7 of the text).
When a p with two peaks is approximated by a q with one peak, something goes wrong in either direction. With KL(q‖p), one of the peaks is missed (the probability on the right is estimated as 0.00 or 1.00); with KL(p‖q), the valley, which has almost no probability, is treated as the most likely value. Which is better depends on what the approximation is used for (Section 20.10 of the text).
The target is given by an unnormalized density p̃(x), and p(x) = p̃(x)/Z. This corresponds to the posterior distribution of Chapter 20, p(θ | 𝒟) = p(𝒟, θ)/p(𝒟) (x ↔ θ, p̃ ↔ p(𝒟, θ), Z ↔ p(𝒟)).
The Laplace approximation expands ln p̃ to second order around the chosen mode x*. The approximation of the marginal likelihood Z (p(𝒟) in Chapter 20) also follows from this expansion. The curvature is written Λ (the same letter as in Chapter 20; it is the precision of the Gaussian).
The KL divergence has different values and different properties depending on its direction (the unit is the nat).
The Gaussian that minimizes KL(p‖q), q = 𝒩(x | m, s2), has m = 𝔼p[x] and s2 = Varp[x] (matching the mean and variance). The q that minimizes KL(q‖p) (= the q that maximizes the ELBO) has no closed form, so it is searched for numerically over (m, ln s) with the Nelder–Mead method. If the objective function has several local minima, the destination depends on the initial value.
Metropolis–Hastings algorithm: from the current point x, make a proposal x′ = x + sε (ε ~ 𝒩(0, 1)); if a uniform random number u ∈ [0, 1) satisfies u < min(1, r), accept (x ← x′); otherwise reject (x stays, and the same value is counted once more in the sample). Because the proposal is symmetric, q(x | x′) = q(x′ | x) cancels, and Z cancels too, so it is not needed.
The autocorrelation function ρk is computed for the samples x1, …, xS of a chain (after burn-in) with the standard estimator whose denominator is divided by S (computed by FFT; the tests confirm that it agrees with the direct sum). The integrated autocorrelation time τint (the same symbol as in Chapter 21; a subscript is added because τ alone would be confused with the temperature in Chapters 26 and 27) and the effective sample size are
Truncation rule: the upper limit kc of the sum is determined by Sokal’s automatic window. Add terms for k = 1, 2, …; when k ≥ 5 τint(k) holds for the first time, that k is taken as kc (τint(k) is the partial sum up to that k). If the condition is not met even after summing up to half the series length, “series too short” is displayed, and τint and the effective sample size may be underestimated. The effective sample size over all chains is the sum over the chains. The Monte Carlo standard error (MCSE) of the mean is √(variance / effective sample size).
Definition of R̂: this is split-R̂ (the form in Gelman et al., Bayesian Data Analysis, 3rd ed., Section 11.4; no rank normalization). Split each chain after burn-in into a first half and a second half to get M = 2 × (number of chains) sequences, let n be their length, W the mean of the within-chain variances, and B the spread of the chain means. Then
R̂ is displayed only when there are two or more chains. It is close to 1 if the chains look at the same distribution and becomes large if each chain looks at a different region. As a rule of thumb, suspect non-convergence if it exceeds 1.01 (the older rule of thumb was 1.1). However, R̂ ≈ 1 is only a necessary condition for convergence.
In the three-state example, from the proposal Qij = q(j | i) (1/2 for each of the other two states), the transition matrix Tij = Qij min(1, p̃jQji / (p̃iQij)) (j ≠ i), Tii = 1 − Σj≠i Tij is built. Rows are the “current state,” columns are the “next state,” and each row sums to 1.
The calculations of the simple view call the same functions as the detailed view (makeTarget, mhInit, mhStep, minKLqp, momentMatch, klPQ, and qTerms in inference-mcmc.model.js). The only calculations added for the simple view are counting the footprints (acceptance rate, fraction on the left hill, number of valley crossings), deciding where to put the hatching, and the intermediate shapes of the moving bell in the picture (inference-mcmc.easy.js).
The detailed view has two tabs: ① (Comparing Approximate Distributions) and ② (Metropolis–Hastings Algorithm). In both, the figures and the “Putting the current numbers into the formula” box are on the left, and the controls and readouts are on the right.
▶ Simulator (detailed view) ①: Comparing Approximate Distributions▶ Simulator (detailed view) ②: Metropolis–Hastings Algorithm
With the keyboard, Tab moves to buttons and sliders, Enter (or Space) presses a button, and the arrow keys move a slider. The tabs can be switched with ← and →.
Questions 1 and 2 can be answered with the simple view alone. Questions 3–6 use the detailed view.
Because each step is small, the candidate appears right next to the current spot and has almost the same height. So the traveler can go almost every time, but the distance moved in one step is short, and in 2000 steps the traveler cannot reach the right hill on the other side of the valley. The footprints are left only on the left hill, and the fraction on the left hill becomes 1.00 (target 0.50). A high fraction that moved does not mean “moved a lot”; it is also the flip side of “moved only a little.” With a too-big step size, conversely, the fraction that moved is as low as 0.07, and footprints pile up at the same spots. The step size that copies the shape well is the just-right one in between.
With “Don’t spill over,” the bell settles on one of the humps, so the estimate is 0.00 when starting from the left and 1.00 when starting from the right, far from the true 0.40 (one hump is missed). With “Don’t miss any,” the bell covers both, so the estimate is 0.42, close to the truth, but the middle of the bell lands in the valley (x = −0.6), where there is almost none of the shape, and an unlikely value is treated as the most likely value.
The mode is x* = (a − 1)/(a + b − 2) = 2/10 = 0.2, and Λ = 2/0.22 + 8/0.82 = 50 + 12.5 = 62.5, so the mean is 0.2 and the variance is 1/62.5 = 0.016. The true mean is 3/12 = 0.25 and the variance is 27/1872 ≈ 0.01442. Because the Laplace approximation is centered at the mode, it misses the weight of the long right tail and underestimates the mean. It also puts probability 0.0569 on the left side x < 0. KL(p‖q) is 0.12884, which is larger than that of the Gaussian with matched mean and variance (0.048117).
KL(q‖p) is an expectation under q, so if q puts probability where p is almost 0, ln(q/p) becomes large and is penalized heavily. Therefore it moves toward one peak, and its variance is also smaller (by default, the left peak: m = −2.988, s = 1.019). KL(p‖q) is an expectation under p, so it is penalized where p has probability but q is close to 0, and it spreads to cover both peaks (m = −0.6, s2 = 9.64; its center lies in the low-probability valley).
The difference is KL(q‖p) ≥ 0 (ln Z = ELBO + KL(q‖p)). Since ln Z does not depend on q, maximizing the ELBO is the same as minimizing KL(q‖p). For Beta(3, 9), ln Z = ln B(3, 9) = −6.2046, and the ELBO of the (truncated) q that minimizes KL(q‖p) is −6.2437; the difference 0.039178 is KL(q‖p).
Every chain sees only the well it started in and does not know the probability (one half) of the other well. Within a well the chain mixes well, so τint is small (about 4) and does not change even when burn-in is discarded. R̂ compares the between-chain spread B with the within-chain variance W; because the chain means split into −0.98 and +0.98, it gives a large value of about 9.9. However, if all four chains start from the same well, R̂ ≈ 1 while the overall mean is −0.98, and even R̂ does not notice.
References (from the end of Chapters 20 and 21):
Back to the Approximate Inference and MCMC Simulator | Machine Learning — From Probability to GPT (Contents) | Equations are typeset with the browser’s built-in MathML (no external library).