A walkthrough of the second half of STAT 238 (Spring 2026, Guntuboyina) covering Markov chains, the Metropolis-Hastings family, Gibbs sampling and its applications, mixture-model fitting, MALA, Hamiltonian Monte Carlo, variational inference, and the EM algorithm. Each entry below summarizes one source file from _sources/STAT 238/ so the vault has a navigable index of what was covered, what was coded, and what was practiced in lab.
Lectures
Lecture 25 — Markov Chains, Stationarity, Detailed Balance, MH and Gibbs (1 April 2026)
Sets up the entire MCMC unit. Defines time-homogeneous Markov chains via transition kernels on discrete or continuous state spaces, defines stationary distributions as invariant measures of the kernel, and states the ergodic theorem (irreducibility plus stationarity gives almost-sure convergence of time averages to space averages). Introduces the detailed balance condition as a sufficient condition for stationarity, illustrated by a random walk on a graph with . Derives the Metropolis-Hastings algorithm: given an arbitrary proposal kernel , the acceptance probability produces a chain satisfying detailed balance with respect to . Closes with the bivariate Gibbs sampler — alternately resampling and from their full conditionals — and a direct verification that it satisfies detailed balance.
Lecture 26 — The Gibbs Sampler in General; Examples (3 April 2026)
Generalizes Gibbs to : at each step pick a coordinate uniformly and resample from . Three illustrative examples: (i) bivariate normal — used to expose the failure mode at where the chain freezes; (ii) Bayesian linear regression with the improper prior, deriving the conjugate full conditionals and ; (iii) probit regression with the uniform prior, where direct Gibbs on alone has no tractable conditional, motivating the data-augmentation trick using latent normals with .
Lecture 27 — Gibbs Sampler for Probit Regression (6 April 2026)
Develops the Albert-Chib data-augmentation Gibbs sampler for probit. Introduces latent with and ; shows that the joint posterior factors so that and are independent truncated normals. Derives the inverse-CDF formula for sampling truncated on , with chosen by the sign of . Closes with the full algorithmic specification of the Gibbs sampler.
Lecture 28 — Gibbs Sampler for Mixture Models (8 April 2026)
Introduces the augmentation Gibbs sampler for the two-component normal mixture with known. Reformulates the model with latent indicators and Gaussian to make the full conditionals tractable: is Bernoulli with success probability , and is normal with cluster-mean and cluster-size sufficient statistics (in the limit of an uninformative prior). Foreshadows the EM algorithm as a deterministic analog to be developed in the next lecture.
Lecture 29 — Gibbs for Mixtures with Unknown Weight and Variances (10 April 2026)
Specifies the algorithm in full for the two-component case with known weight and known unit variance, and writes out the iteration step-by-step. Then generalizes the model to with all five parameters unknown, placing , , and priors. Notes that this prior structure is conjugate so the full conditionals will all admit closed forms (formulae stated in Lecture 30), and warns that Gibbs convergence is sensitive to initialization because the log-likelihood is multimodal.
Lecture 30 — Gibbs Sampler for -Component Gaussian Mixtures and the EM Algorithm (13 April 2026)
States the full conditionals for the -component model with Dirichlet, normal, and inverse-gamma priors:
- with responsibilities .
- .
- Gaussian with conjugate posterior mean and variance.
- .
Then derives the EM algorithm as a deterministic variant that replaces each Gibbs draw with its expectation: integer counts become soft counts , the Dirichlet draw becomes the MAP weight , and the conjugate means and variances become weighted MLEs. The connection between Gibbs and EM is laid out explicitly.
Lecture 31 — RWM and the MALA Algorithm (15 April 2026)
Recaps Markov chain theory and Metropolis-Hastings, then introduces Random Walk Metropolis with proposal , . Motivates the Metropolis-Adjusted Langevin Algorithm by adding a drift term to the proposal and choosing to make the Metropolis-Hastings ratio nearly one for small steps. A first-order Taylor expansion of around forces , giving the MALA proposal . Includes a beautiful mechanical interpretation: RWM is a free particle (constant velocity); MALA is a particle with constant acceleration over the step interval ; HMC (foreshadowed) is a particle with position-dependent acceleration.
Lecture 32 — Dimension Scaling of RWM, MALA, and HMC (17 April 2026)
Quantitatively compares RWM, MALA, and HMC for the standard Gaussian target . For RWM, computes with and ; concludes that the acceptance probability is non-degenerate iff . Repeats the analysis for MALA, where the analogous quantity has expectation and standard deviation , giving the MALA scaling — much larger than RWM’s . Solves the HMC ODE exactly for the Gaussian: , and shows that the Metropolis-Hastings ratio equals one identically — so HMC accepts with probability one for any . This is the punchline justifying HMC’s use in high dimensions.
Lecture 33 — Continuity Equation and Stationarity for HMC (20 April 2026)
Develops the theoretical machinery for proving stationarity of HMC. Restates the HMC ODE in first-order form and reformulates it via the Hamiltonian as . Verifies that is conserved along trajectories. Then states and proves the continuity equation: if and , then the density of satisfies . Sets up the application to HMC for next lecture.
Lecture 34 — Hamiltonian Dynamics, Symplecticity, and Leapfrog (22 April 2026)
Generalizes the Hamiltonian to for any symmetric kinetic energy , with two examples: (preconditioned, Riemannian Manifold HMC) and (non-second-order dynamics). Establishes three properties of the time- flow :
- Reversibility: where flips momentum.
- Hamiltonian conservation: .
- Volume preservation: (proven by an infinitesimal Jacobian argument).
Introduces the leapfrog discretization with step :
Shows that leapfrog preserves reversibility and volume but not the Hamiltonian (motivating the Metropolis correction next lecture). Proves stationarity of under continuous Hamiltonian dynamics via the continuity equation: the divergence identically when .
Lecture 35 — HMC Algorithm and Detailed Balance Proof (24 April 2026)
Specifies the full HMC algorithm: sample , run leapfrog steps to produce , accept with probability . Reformulates the deterministic-transition kernel as an involution (). Proves the general detailed-balance condition for the joint chain on , exploiting the volume-preservation and involution properties of leapfrog. The proof shows why a velocity flip is necessary even though it does not affect the Hamiltonian, because it makes the deterministic update an involution.
Lecture 36 — Variational Inference (27 April 2026)
Introduces variational inference as an alternative to MCMC. Sets up the optimization , derives the equivalent objective in terms of the Evidence Lower Bound (ELBO) , and shows with equality at . Provides the alternative decomposition .
Develops the worked example of Bayesian logistic regression with a Gaussian variational family . Shows the ELBO becomes , with the entropy term coming from the Gaussian. Uses the reparameterization trick with and Monte Carlo estimation to make the objective amenable to gradient ascent.
Lecture 37 — VI Connection to EM and CAVI (29 April 2026)
Recaps the ELBO and proves the EM algorithm is a special case of variational inference. With model and a hyperparameter to be estimated by MLE, alternately maximizing over (giving ) and over (giving the M-step). The objective is exactly the EM auxiliary function.
Presents Coordinate Ascent Variational Inference (CAVI). With factorized variational family , the optimal satisfies . Two-step proof: first lemma minimizes over densities to give ; second lemma generalizes to two factors.
Code Notebooks
CodeLecture 26 — Gibbs Sampler Examples
Walks through three Gibbs sampler implementations side-by-side. Bivariate normal: generates 100,000 samples for with , plots the resulting scatter, trace plots, and marginal histograms; demonstrates the breakdown when (the chain barely moves). Linear regression on the Pearson father–son heights data (n = 1078): compares the Gibbs posterior for against statsmodels OLS, verifies posterior marginals match the theoretical , , and distributions. Probit regression: sets up the frogs dataset (binary presence/absence at 212 sites) and fits both probit and logit GLMs as a baseline for the next lecture’s data-augmentation Gibbs sampler.
CodeLecture 27 — Gibbs for Probit + Mixture Models Setup
Implements the Albert-Chib data-augmentation Gibbs sampler for probit regression on the frogs dataset (8 covariates, n = 212). Compares 100,000 Gibbs iterations against the Laplace posterior normal approximation produced by sm.GLM; shows the two agree closely. Repeats on a small simulated dataset (, ) where the discrepancy is larger and uses dense grid integration to confirm the Gibbs sampler is closer to the true posterior than the Laplace approximation. Then transitions to mixture models: simulates from a mixture, plots the bimodal log-likelihood surface (with one spurious mode), and shows that EM, Gibbs, and small-step RWM can all get trapped at the spurious mode; large-step RWM () reliably escapes.
CodeLecture 28 — Mixture EM and Gibbs (Sensitivity to Initialization)
Self-contained re-presentation of the mixture-model story from CodeLecture 27, repackaged for Lecture 28’s content: same simulated data, same comparison of EM, Gibbs, and RWM, same demonstration that initialization matters and that large-step RWM is the most robust.
CodeLecture 29 — Two-Component Mixture on the Exoplanet Dataset
Loads NASA’s exoplanet archive (~6,000 planets, with planet radius in Jupiter radii on the log scale). Fits the two-component normal mixture using both PyMC (slow, ~80 seconds for 2,000 draws on 600-point subsample) and a custom Gibbs sampler (fast, 40,000 draws). Demonstrates label switching between the two methods (PyMC reports , Gibbs reports — same fit, different labels). Shows the fitted bimodal density on the histogram. Concludes with a Gibbs run on the full ~6,000-point dataset, which PyMC cannot handle in reasonable time.
CodeLecture 30 — k-Component Gaussian Mixture, Gibbs and EM
Generalizes the previous lecture’s two-component sampler to arbitrary . Reproduces the result, then runs on the exoplanet data, finding that the third component improves the fit by capturing a tail not modeled by two components; does not visibly improve further. Uses the posterior modal assignments of to cluster the data into groups and visualize the per-component density contributions. Closes with the EM algorithm for -component mixtures, showing that EM and Gibbs converge to similar fits when both are well-initialized.
CodeLecture 31 — RWM in Low and High Dimensions
Implements RWM on the unnormalized 1D density . With , RWM produces excellent samples (good trace plot, fast-decaying autocorrelation). Then lifts the problem to by appending , and shows that no value of makes RWM work: too large an gives near-zero acceptance, too small an gives near-perfect autocorrelation. The dimension-scaling crisis demands MALA (next notebook).
CodeLecture 32 — MALA in High Dimensions and Geometry of Proposals
Returns to the high-dimensional setup from CodeLecture 31 and shows that MALA produces good samples for the first coordinate where RWM fails. Includes a geometric visualization of how the three proposals look for : RWM is a straight-line proposal from in direction ; MALA is parabolic; HMC is even more curved (an ellipse arc). The visualization makes concrete why curved proposals work better in higher dimensions — they follow the geometry of the target.
CodeLecture 35 — Leapfrog vs Euler; Bayesian Neural Network with HMC
Shows that leapfrog tracks the exact Hamiltonian flow accurately for over steps while Euler integration drifts away after a few steps. Then fits a Bayesian neural network with two hidden layers (20 units each, 661 parameters total) to the scikit-learn diabetes dataset using HMC. Tunes via the SGD baseline residual std and via the SGD weight-decay parameter. Runs leapfrog with step size and steps to produce 1,000 samples. Test RMSE matches SGD baseline ( on the original scale).
CodeLecture 36 — Variational Inference for Bayesian Logistic Regression
Compares three approximations to Bayesian logistic regression posteriors: full-covariance Gaussian VI (reparameterization trick + Adam), Laplace approximation, and long-run RWM as ground truth. The 1D warm-up demonstrates that VI and Laplace both essentially nail the truth when the posterior is bell-shaped. The frogs dataset (8D, n = 212) shows where the approximations diverge: VI is faithful to the global KL; Laplace is a local quadratic approximation at the MAP. Builds the design matrix with log-transforms on distance and NoOfPools and standardizes covariates. The VI implementation maximizes the ELBO using PyTorch with Cholesky parameterization to enforce positive-definiteness via gradient ascent on .
Labs
Lab 6 — Linear Regression Mechanics
Walks through the OLS quantities reported by statsmodels, computing each by hand on the FRED quarterly US GDP series (n = 314) fit with a cubic time trend. Computes the design matrix , the LSE , fitted values, residuals, residual sum of squares (RSS), residual standard error , and standard errors of as the square roots of the diagonal of . Verifies each quantity matches the corresponding statsmodels output. Closes by plotting posterior samples of the regression curve drawn from the multivariate- posterior to show the visual envelope of uncertainty.
Lab 7 — Linear Regression on MROZ + Poisson Regression Introduction
Reviews linear regression on the MROZ dataset (n = 753, 22 covariates on married women in 1975) with hours worked as response and 11 covariates. Drops the variables with high -values and refits with 6 covariates. Verifies that PyMC with pm.Flat priors on and gives essentially identical posterior means and standard deviations to the OLS output. Then motivates Poisson regression as the right model for the count-valued response: the linear model’s coefficient interpretations break down for (a -hour effect is meaningless for working women with hours or hours ), but a log-linear model gives the interpretable percentage interpretation. Fits the Poisson regression model via sm.GLM, derives the Newton-Raphson algorithm for the MLE explicitly (gradient , Hessian ), implements it in pure NumPy, and verifies convergence to the statsmodels answer. Compares the PyMC samples (with pm.Flat priors) against the frequentist output and shows that PyMC is unstable: random_seed = 0 works but random_seed = 4 fails to mix. Derives the Laplace posterior normal approximation from a second-order Taylor expansion of the log-likelihood at the MLE and shows that the resulting Bayesian standard errors coincide with the frequentist ones.
Lab 8 — Bayesian Regularization and Trend Filtering
Fits the smoothing model with — i.e., a first-order trend filtering basis with one knot per data point. The full model is over-parameterized ( knot coefficients plus an intercept and slope) and ridge regularization is necessary. Places a flat prior on and a prior on the knot coefficients. Derives the conditional posteriors of , , and in closed form and approximates the marginal posterior of on a log-spaced grid. Generates posterior samples via this grid-based scheme and visualizes uncertainty bands around the smoothed estimate. Demonstrates on two datasets: a smooth function with (the method recovers the truth and the uncertainty bands cover the truth), and a piecewise-linear function with (the method smooths over the kinks but recovers the overall shape).
Lab 9 — Gaussian Process Regression with the RBF Kernel
Switches from the Integrated Brownian Motion (IBM) kernel used in the lectures to the squared exponential / RBF kernel . Applies it to the wage dataset: regressed on years of experience, with subsampled from 25,437 records. Tunes the hyperparameters first by grid search over the marginal likelihood, then by L-BFGS-B optimization for speed, and finally with an additional intercept parameter . Compares the three RBF fits against the IBM-kernel result from Lecture 23 and finds they all give similar smooth fits. Demonstrates the qualitative effect of the length scale: smooths the function flat, shrinks the function to zero.
Lab 10 — Bayesian Approaches to Poisson Regression (MH Variants)
Returns to the MROZ Poisson regression from Lab 7. Compares four approaches:
- PyMC with random_seed = 0 — close to the frequentist answer.
- PyMC with random_seed = 4 — chain fails to mix.
- RWM with proposal covariance from the Laplace approximation — works (acceptance ~25%, posterior matches Laplace).
- RWM with proposal — fails because the variables are on different scales.
- RWM with proposal — works after burn-in.
- Independence sampler with proposal for — best mixing, ~80% acceptance, sensitive to initialization (must start at MLE).
The lab’s takeaway is that the Laplace covariance is essential for tuning the proposal in non-Gaussian posteriors: it tells you the right scales for each direction of the posterior, and ignoring it gives you either a chain that takes too-small steps (high acceptance, no exploration) or one that takes too-large steps (low acceptance, no exploration).
Lab 11 — Mixture of Regressions
Fits the mixture-of-regressions model where is drawn from a 3-atom discrete distribution with unknown atoms and weights. Simulates data points from three lines with coefficients , , at weights . The Gibbs sampler proceeds: introduce latent indicators , alternately resample from , weights from , and per-component coefficients from their conjugate normal posterior. Recovers the true coefficients (up to label-switching), visualizes the posterior over regression lines as a band plot, and uses the posterior-mode assignments of to color-code the data points by component.
Lab 12 — RWM, MALA, HMC Comparison on
Hands-on comparison of all three MCMC methods on the standard Gaussian using the dimension-scaling rules from Lecture 32. Implements all three samplers from scratch and computes diagnostics at each: (i) trace plot of the first coordinate; (ii) marginal histogram vs ; (iii) trace plot of (target value 1); (iv) sample autocorrelation function; (v) effective sample size (ESS); (vi) running mean. RWM at : acceptance but very poor mixing (ESS = 30 from 50,000 samples). MALA at : much better (ESS = 925), histogram matches the truth, stabilizes near 1. HMC with : acceptance is identically 1 (the exact-Gaussian solution can be evaluated in closed form), and ESS = 3,096 — best of the three by a factor of 3 over MALA. Confirms numerically the dimension-scaling theory of Lecture 32.
Lab 13 — Bayesian Neural Network on Diabetes Data
Extends CodeLecture 35’s BNN with HMC by adding a fully Bayesian treatment of and . First reproduces the fixed- result, then constructs the posterior predictive distribution properly: draws for each posterior sample of . Empirical 95% predictive coverage on the test set is 97.3% (well-calibrated), at the cost of intervals that are wide (average width 213, vs response std 77) — this is honest reporting of uncertainty given how few data points the BNN has. Then upgrades to the full hierarchical model with priors and . Implements Gibbs-within-HMC: HMC step on given , then closed-form inverse-gamma draws for and . The reasoning for this hybrid is that running HMC over the joint requires a non-trivial mass matrix because the parameters live on different scales; Gibbs sidesteps this. Result: posterior is well-pinned-down (matches the SGD value), but posterior is much broader than expected and the chain does not mix well — a known issue with hierarchical-model HMC, with references to Betancourt and Girolami (2013).
What These Sources Add to the Vault
The lectures, code, and labs together extend the existing Bayesian-statistics notes in three ways. First, they provide concrete dimension-scaling theory (, , ) for the three samplers and worked computations on — material that lives in 3.11.1 Metropolis-Hastings, 3.11.3 MALA, and 3.11.4 Hamiltonian Monte Carlo. Second, they give a complete derivation of HMC stationarity using the continuity equation, the involution structure, and the volume-preservation property of leapfrog — material that should be referenced from the HMC note. Third, they introduce variational inference and the connection to EM via the ELBO — material that is currently underdeveloped in the vault. A future note on variational inference (sitting alongside 3.11.5 EM Algorithm in the MCMC/inference subfolder, or as a peer to the MCMC subfolder) would close this gap.
The labs also cover practical tooling that is not in the lectures: PyMC behavior and failures, posterior-predictive coverage diagnostics (autocorrelation, ESS, running means), the Cholesky parameterization for covariance optimization, and Gibbs-within-HMC for hierarchical models. These are good candidates for a separate “MCMC diagnostics” note or for being incorporated as Properties in the existing MCMC notes.
See Also
- 3.11 MCMC — parent index for the MCMC subfolder.
- 3.11.1 Metropolis-Hastings, 3.11.2 Gibbs Sampling, 3.11.3 MALA, 3.11.4 Hamiltonian Monte Carlo, 3.11.5 EM Algorithm — concept notes that draw on this material.
- Proposed — the structural plan for the Bayesian Statistics folder, including notes on variational inference being deferred to
_backlog/.