Skip to content

Commit 5bf4394

Browse files
jstacclaude
andauthored
Add explanatory notes to bayes_nonconj: NUTS and variational inference (#918)
* Add a note explaining NUTS for first-time readers Most readers meeting NUTS will not know what it is. Add a {note} where it is introduced: NUTS is a form of Hamiltonian Monte Carlo, itself a Metropolis-Hastings method, whose proposals use gradient information about the log-posterior (and which auto-tunes trajectory length). Point to the advanced MCMC lecture for a Metropolis-Hastings introduction. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * Motivate variational inference: when and why to use it VI was introduced without saying why one would use it given NUTS. Add a "Why variational inference?" subsection: VI scales to large datasets and high-dimensional models (stochastic/mini-batch ELBO gradients, as in deep learning) where MCMC is too slow, and yields a cheap reusable approximation — at the cost of accuracy (best fit within the guide family). Includes a rule of thumb for choosing MCMC vs VI. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * Introduce ArviZ and MCMC diagnostics for first-time readers The diagnostics step assumed familiarity with convergence, ArviZ, R-hat, ESS, and trace plots. Expand it for a newcomer: why MCMC output must be checked (dependent chain must reach its stationary distribution; run multiple chains and check agreement), what ArviZ is, what r_hat and the effective sample sizes mean, and how to read a trace plot (both panels of plot_trace). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
1 parent 1f15346 commit 5bf4394

1 file changed

Lines changed: 52 additions & 4 deletions

File tree

‎lectures/bayes_nonconj.md‎

Lines changed: 52 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,16 @@ This lecture introduces two widely used ways to do that, both implemented in the
4444

4545
* **Variational inference (VI)** — replace sampling with optimization: search within a tractable family of distributions for the member closest to the posterior.
4646

47+
```{note}
48+
We treat NUTS as a black box in this lecture.
49+
50+
In brief, it is a form of **Hamiltonian Monte Carlo**, which is itself a version of the **Metropolis–Hastings** algorithm: it proposes candidate draws and accepts or rejects them so that the resulting Markov chain has the posterior as its stationary distribution.
51+
52+
What distinguishes it from a basic Metropolis–Hastings sampler is that its proposals are built from *gradient* (derivative) information about the log-posterior, which lets the chain move efficiently through the parameter space; NUTS additionally tunes the length of each proposed move automatically.
53+
54+
For a more advanced introduction to MCMC and the Metropolis–Hastings algorithm, see [this lecture](https://python-advanced.quantecon.org/mcmc.html).
55+
```
56+
4757
Our plan is:
4858

4959
1. Confirm that MCMC reproduces the *conjugate* beta posterior that we can compute analytically — this validates the machinery on a problem whose answer we already know.
@@ -183,25 +193,45 @@ We take $\alpha_0 = \beta_0 = 2$ and sample the posterior with NUTS.
183193
mcmc = run_nuts(binomial_model, dist.Beta(α0, β0), k, n)
184194
```
185195

186-
Before looking at the posterior we check that the sampler converged.
196+
Before looking at the posterior we should check that the sampler has done its job.
197+
198+
Unlike the independent draws we are used to, MCMC returns a *dependent* sequence — a Markov chain — whose early draws still remember where the chain started.
187199

188-
ArviZ reads NumPyro's output directly and reports standard diagnostics.
200+
We can trust the output only once the chain has "forgotten" its starting point and settled into its stationary distribution, which by construction is the posterior we want.
201+
202+
As a safeguard we ran **four** chains from different random starting points (`num_chains=4` in `run_nuts`) and now check that they agree with one another.
203+
204+
[ArviZ](https://www.arviz.org/) is a companion library for examining the output of Bayesian samplers.
205+
206+
The function `az.from_numpyro` repackages our NumPyro results into ArviZ's standard data structure, and `az.summary` prints a table of per-parameter summaries and convergence diagnostics.
189207

190208
```{code-cell} ipython3
191209
idata = az.from_numpyro(mcmc)
192210
az.summary(idata, var_names=["θ"])
193211
```
194212

195-
The potential scale reduction factor `r_hat` is essentially $1.0$ and the effective sample sizes are large, both signs that the chains have mixed well.
213+
Two columns of this table are convergence diagnostics worth understanding.
214+
215+
* **`r_hat`** (the Gelman–Rubin statistic) compares the spread of the draws *within* each chain to the spread *between* chains. If the chains have all converged to the same distribution these two match and `r_hat` is close to $1.0$; values above roughly $1.01$ warn that the chains disagree and the draws cannot yet be trusted.
216+
217+
* **`ess_bulk`** and **`ess_tail`** report the *effective sample size*. Because consecutive MCMC draws are correlated, a chain of length $N$ carries less information than $N$ independent draws would; the effective sample size estimates how many independent draws it is worth (in the bulk and in the tails of the distribution respectively). Larger is better.
218+
219+
Here `r_hat` is essentially $1.0$ and the effective sample sizes run into the thousands, so the chains have mixed well.
196220

197-
The trace plot tells the same story: the four chains overlap and look like stationary noise.
221+
A **trace plot** gives a visual check of the same thing.
222+
223+
ArviZ's `plot_trace` draws two panels for each parameter: on the right, the sampled value against the iteration number (one coloured line per chain); on the left, a density estimate of the draws from each chain.
224+
225+
Well-mixed chains look like stationary noise on the right — a fuzzy, flat band, with the chains overlapping rather than drifting or wandering — and their densities on the left lie almost on top of one another.
198226

199227
```{code-cell} ipython3
200228
az.plot_trace(idata, var_names=["θ"])
201229
plt.tight_layout()
202230
plt.show()
203231
```
204232

233+
Our chains pass both checks, so we can trust the draws and turn to the posterior itself.
234+
205235
Now we compare the MCMC posterior with the analytical beta posterior.
206236

207237
```{code-cell} ipython3
@@ -346,6 +376,24 @@ MCMC approximates the posterior by *sampling* from it.
346376

347377
We restrict attention to a tractable family of densities $q_\phi(\theta)$ — the **guide** — indexed by parameters $\phi$, and we search for the member of that family closest to the posterior.
348378

379+
### Why variational inference?
380+
381+
If NUTS already returns accurate posteriors, why introduce another method?
382+
383+
The answer is **scale**.
384+
385+
MCMC evaluates the likelihood over the entire dataset at every step, and the number of steps it needs tends to grow with the dimension of the parameter.
386+
387+
For large datasets or high-dimensional models — for instance the hierarchical models and neural networks common in machine learning — this can become too slow to be practical.
388+
389+
Variational inference scales much better, because the objective (the ELBO, introduced below) can be maximized with *stochastic* gradients computed on small random subsets of the data — the same machinery that trains deep learning models.
390+
391+
It also yields a compact parametric approximation that is cheap to store and to draw from afterwards.
392+
393+
The price is accuracy: VI returns only the best fit *within the guide family*, and it can understate uncertainty.
394+
395+
As a rule of thumb, prefer MCMC when you need an accurate posterior and the problem is small enough to afford it, and VI when the model is too large for MCMC or a fast, approximate answer is good enough.
396+
349397
### The evidence lower bound
350398

351399
Let the prior be $p(\theta)$ and the likelihood be $p(Y \mid \theta)$, where $Y$ denotes the observed data (here the head count $k$).

0 commit comments

Comments
 (0)