Monte Carlo and Markov chains
Instead of a formula for the posterior, samples from it: the Monte Carlo estimate and its error, the inverse CDF method, rejection sampling, importance sampling, and then Markov chains: stationarity, irreducibility, aperiodicity, detailed balance, burn-in and the effective sample size.
An integral as an average over samples
The topic Variational inference replaced the posterior with the best member of a family . That answer is fast but biased: whatever the family cannot represent is simply missing, and nothing in the output says how much. This topic takes the other road. Instead of approximating the posterior by a formula, we draw samples from it and average.
Almost everything we want from a posterior is an expectation. The posterior mean, the probability of a set , the posterior predictive:
All three have the form . If are independent draws from , the Monte Carlo estimate is the sample average:
It is unbiased, , and the law of large numbers gives when . If also , then
So the typical error is . The normal shape is a large- statement, not an exact one for every .
The running example is the coin from the topic The Bayesian approach: a uniform prior and three heads give the posterior with density on . Its mean is , the probability that the next toss is heads, and its standard deviation is . With posterior draws, the average of the lands within about of .
Two remarks. The rate contains no dimension: averaging works the same way for a 1000-dimensional . But , the cost of one draw and, later, how fast a chain mixes can all depend heavily on dimension. And the whole method rests on one assumption we have not earned yet: that we can draw from at all. The next three blocks do that in one dimension.
The inverse CDF method
A computer gives us uniform numbers . Simple transforms already go far: is uniform on , and is when (see the topic What generative modeling is in Generative Models). An old trick, , has mean and variance but is only approximately normal: it never leaves .
The general recipe is the inverse CDF method. Let be the cumulative distribution function. Then
has exactly the distribution . For a continuous, strictly increasing the proof is one line:
Exponential. . Solve for :
The coin posterior. For the CDF is , so . A draw gives ; a draw gives . Small are rare because grows slowly near zero.
Discrete distributions. When has jumps, use the generalized inverse . In practice: cut into consecutive pieces of lengths and return the index of the piece that falls into. A Bernoulli draw is .
The limit of the method is itself. For the normal distribution it has no elementary formula, and for a posterior known only up to a constant we cannot even write . The next method needs neither.
Rejection sampling
Rejection sampling draws from a density using a simpler proposal that we can sample. (Here is a proposal, not the variational family of the previous topic.) We need a finite constant with an envelope above the target:
One accepted draw is produced as follows. Draw a candidate and an independent . Accept if
otherwise throw away and draw again.
Why it works. A candidate at is accepted with probability , so
Accepted draws follow exactly. The constant controls speed, not accuracy: on average we spend candidates per accepted draw. Accepted draws from independent rounds are independent.
For the coin posterior with a uniform proposal, the ratio peaks at , so and a quarter of candidates survive.
Unnormalized targets. A posterior is usually known only as with unknown , the evidence. Rejection sampling still works with an envelope and acceptance test . The accepted draws again follow , and the acceptance probability is . We never need to run the algorithm.
Two catches. The proposal must cover the support of the target, and its tails must be at least as heavy: a normal proposal cannot envelope a Cauchy target, since the ratio grows without bound. And in many dimensions the best tends to grow exponentially, so almost every candidate is rejected.
Importance sampling
Rejection sampling throws candidates away. Importance sampling keeps all of them and corrects each one with a weight. It does not produce draws from ; it estimates an expectation under using draws from .
If wherever , multiply and divide by :
With and the importance weights :
This estimate is unbiased. For the coin posterior with a uniform proposal, : a draw near counts four times, a draw near almost not at all.
Unknown normalizer. With only , use and normalize the weights so they sum to one:
This self-normalized estimate is a ratio of two random averages. It is consistent, but for finite it is generally biased. The unbiasedness of plain importance sampling does not carry over.
Weights can hurt. Unbiased does not mean accurate. For the coin, the uniform proposal gives a per-draw standard deviation of about for the estimate of , against for direct draws: roughly times more samples for the same error. If rarely visits the region that matters, one point grabs almost all the weight, and many draws carry the information of a few. A common diagnostic is the effective sample size of the weights, . A good depends on both and ; using weights does not by itself reduce variance.
Markov chains and stationarity
All three methods need a proposal that resembles the whole target. In one dimension that is easy. For a posterior over hundreds of parameters, a global proposal close enough to the posterior rarely exists: rejection stalls and importance weights degenerate.
Markov chain Monte Carlo (MCMC) changes the plan. Instead of independent draws, it builds a sequence where each state is a small random step from the previous one, designed so that in the long run the states are distributed as the target. Then we average along the path.
The sequence is a Markov chain if the next state depends on the past only through the present:
For a homogeneous chain the rule is a fixed transition kernel . With finitely many states it is a transition matrix with rows that sum to one, . Writing the distribution of as a row vector :
A distribution is stationary (invariant) if one step does not change it:
Example: three states in a row. From an end state, stay or move to the middle with probability each; from the middle, stay with and move to each end with :
Check the first entry: . Starting from the chain gives , , and by it is within of .
Stationarity is a statement about marginals: if then . It does not make neighbouring states independent. In this chain, equals half the time.
Irreducibility, aperiodicity and burn-in
A stationary distribution alone does not make a chain useful. The chain (transition matrix ) keeps every distribution, so it never forgets where it started. We want more: whatever is, the distribution of should approach .
For a chain with finitely many states two conditions are enough.
- Irreducibility. From every state one can reach every other state in some finite number of steps with positive probability. The identity chain fails: it never leaves its state.
- Aperiodicity. The period of state is ; we need period . Remove the "stay" moves from the three-state example, and the chain jumps between the middle and the ends: from the left end it returns only in an even number of steps. Its distribution oscillates, , , , …, though is still stationary.
If a finite chain is irreducible and aperiodic, its stationary distribution is unique and from any start. For an irreducible chain, one state with a positive probability of staying put already makes it aperiodic. Positive transitions between all pairs in one step are more than needed. For infinite and continuous state spaces the conditions are stated with sets of positive probability (Harris recurrence); the idea is the same.
What we actually use is the ergodic theorem, a law of large numbers along the path:
It does not need independent states. Note the difference between two statements. For a finite chain, irreducibility alone is enough for the time average to converge; aperiodicity is needed for the distribution of a single to converge.
In practice the first part of the path is discarded as burn-in, so the arbitrary start weighs less. There is no universal step after which the states are exactly -distributed. Started from an arbitrary point, an MCMC average is usually biased for finite ; started from itself it is unbiased, dependence notwithstanding.
Detailed balance
Checking means summing over all states. A simpler condition is local. A chain satisfies detailed balance with respect to if for every pair of states
In the stationary regime, the probability flow from to equals the flow back. Integrating over shows that detailed balance implies stationarity:
Chains with this property are called reversible. Two cautions. Detailed balance is sufficient but not necessary: there are correct non-reversible chains. And it gives invariance only; convergence from an arbitrary start still needs irreducibility and aperiodicity.
Back to the coin, now with restricted to a grid and a uniform prior on it. After three heads the posterior is proportional to , that is to , so . Here is a chain on the grid:
Check the flows. Between the first two states: and . Between the last two: and . Detailed balance holds, so is stationary. Every state can reach every other and the diagonal is positive, so the chain converges to the posterior from any start. Notice how the matrix was built: moves towards higher posterior are always taken, moves away from it are often refused. Where these numbers come from is the subject of the next topic.
Autocorrelation and effective sample size
MCMC states are dependent, and that changes the error. For a stationary chain, let and the autocorrelation at lag . Then
When correlations die out fast enough, the bracket tends to the integrated autocorrelation time, and the chain behaves like a smaller independent sample:
is the effective sample size (ESS) and MCSE is the Monte Carlo standard error. Example: a chain for the coin parameter runs steps, and its autocorrelations add up to . Then , and the posterior mean is known to about , not to the that independent draws would give.
Three points that are easy to get wrong:
- ESS belongs to a function , not to the chain: and have different autocorrelations.
- With negative correlations, and the ESS can exceed .
- Thinning, keeping every -th state, does not make states independent and, for the same number of steps, usually loses information. It saves memory.
Mixing is the informal name for how fast the chain forgets its past; slow mixing means large . Everything now hinges on one design problem. Monte Carlo needs draws from the posterior; one-dimensional samplers do not scale; a Markov chain can wander through a complex space with local steps if its stationary distribution is the posterior. The grid chain above shows it is possible. How do we build such a chain for an arbitrary posterior known only up to the evidence ? That is the topic Gibbs sampling and Metropolis–Hastings.
Check your understanding
The same questions as in Pulse. Answers are shared between modes.
Answers are saved on the server and tied to this browser until you sign in.