You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Commit 5bf4394
Browse filesBrowse the repository at this point in the historyBrowse files
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]>
Copy file name to clipboardExpand all lines: lectures/bayes_nonconj.md
+52-4Lines changed: 52 additions & 4 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -44,6 +44,16 @@ This lecture introduces two widely used ways to do that, both implemented in the
44
44
45
45
***Variational inference (VI)** — replace sampling with optimization: search within a tractable family of distributions for the member closest to the posterior.
46
46
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
+
47
57
Our plan is:
48
58
49
59
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.
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.
187
199
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.
189
207
190
208
```{code-cell} ipython3
191
209
idata = az.from_numpyro(mcmc)
192
210
az.summary(idata, var_names=["θ"])
193
211
```
194
212
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.
196
220
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.
198
226
199
227
```{code-cell} ipython3
200
228
az.plot_trace(idata, var_names=["θ"])
201
229
plt.tight_layout()
202
230
plt.show()
203
231
```
204
232
233
+
Our chains pass both checks, so we can trust the draws and turn to the posterior itself.
234
+
205
235
Now we compare the MCMC posterior with the analytical beta posterior.
206
236
207
237
```{code-cell} ipython3
@@ -346,6 +376,24 @@ MCMC approximates the posterior by *sampling* from it.
346
376
347
377
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.
348
378
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
+
349
397
### The evidence lower bound
350
398
351
399
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