Approximate Inference: From MCMC to Variational Bayes

Derive variational Bayesian linear regression in NumPy, compare it to PyMC NUTS on the same dataset, and watch the lower bound pick the true polynomial degree.

Cover Image for Approximate Inference: From MCMC to Variational Bayes

You fit a curve to a small set of noisy observations, and several different curves look plausible. A single fitted line cannot show how uncertain its coefficients are or how much confidence to place in predictions beyond the observed range. Bayesian modelling expresses those possibilities as a posterior distribution. Approximate inference gives us ways to work with that distribution when its integrals cannot be evaluated directly.

We test a simpler way to approximate those plausible curves. CAVI takes three iterations and 0.4 milliseconds; NUTS takes 34 seconds. The lower bound also selects the true polynomial degree without a validation set. Comparing predictive bands checks what the speed gains cost in uncertainty.

Quick Win: Bayesian Regression in Forty Lines

Open In Colab

The variational treatment of Bayesian linear regression gives every update equation in closed form. The whole inference loop fits in forty lines of NumPy.

import numpy as np
from scipy.special import digamma, gammaln

def cavi(Phi, t, beta, a0=0.0, b0=0.0, max_iter=60, tol=1e-7):
    """Coordinate-ascent VI for Bayesian linear regression with Gamma prior on alpha."""
    N, M = Phi.shape
    PhiTPhi, PhiTt, tTt = Phi.T @ Phi, Phi.T @ t, float(t @ t)

    E_alpha, prev_elbo = 1.0, -np.inf
    for it in range(max_iter):
        # q(w) = N(m_N, S_N)
        S_N = np.linalg.inv(E_alpha * np.eye(M) + beta * PhiTPhi)
        m_N = beta * S_N @ PhiTt
        E_wTw = m_N @ m_N + np.trace(S_N)
        # q(alpha) = Gamma(a_N, b_N)
        a_N, b_N = a0 + M / 2, b0 + 0.5 * E_wTw
        E_alpha = a_N / b_N

        # Lower bound  L(q)
        psi_a, ln_b = digamma(a_N), np.log(b_N)
        elbo = (
            0.5 * N * np.log(beta / (2 * np.pi)) - 0.5 * beta * tTt
            + beta * (m_N @ PhiTt)
            - 0.5 * beta * np.trace(PhiTPhi @ (np.outer(m_N, m_N) + S_N))
            - 0.5 * M * np.log(2 * np.pi) + 0.5 * M * (psi_a - ln_b)
            - 0.5 * (a_N / b_N) * E_wTw
            - (psi_a - ln_b) - gammaln(a_N)
            + 0.5 * np.linalg.slogdet(S_N)[1] + 0.5 * M * (1 + np.log(2 * np.pi))
            + gammaln(a_N) - (a_N - 1) * psi_a - ln_b + a_N
        )
        if abs(elbo - prev_elbo) < tol:
            break
        prev_elbo = elbo
    return m_N, S_N, E_alpha, elbo

Generate thirty noisy points from a degree-three polynomial, fit a degree-nine model with this loop, and the predictive band hugs the truth and widens cleanly outside the training range:

Variational predictive distribution from a degree-9 polynomial fit to 30 noisy points: the gold band tracks the dark navy true curve through the green data and widens beyond x = 5.

A single CAVI fit takes 0.4 milliseconds. The same model under PyMC NUTS takes thirty-four seconds and 8000 samples to produce a posterior that looks almost identical on this problem. The two-method comparison below shows where the gap matters and where it does not.

What Just Happened: One CAVI Iteration

The function above hides three independent ideas. Pulling them apart is the whole game.

Mean-field factorisation

The true posterior p(w,α∣t)p(\mathbf{w}, \alpha \mid \mathbf{t}) couples the coefficients and their precision. Mean-field VI replaces it with a factorised approximation:

q(w,α)=q(w) q(α)q(\mathbf{w}, \alpha) = q(\mathbf{w}) \, q(\alpha)

The mean-field assumption does all the heavy lifting and creates the most-cited bias of VI: anything correlated under the true posterior is decoupled under qq. The marginals plot below shows what that costs.

Coordinate-ascent updates

Under the mean-field assumption, the optimal update for one factor takes a closed form:

ln⁡qj⋆(Zj)  =  Ei≠j ⁣[ln⁡p(X,Z)]  +  const\ln q^\star_j(\mathbf{Z}_j) \;=\; \mathbb{E}_{i \neq j}\!\left[\ln p(\mathbf{X}, \mathbf{Z})\right] \;+\; \text{const}

For Bayesian linear regression with a Gaussian likelihood and a Gamma prior on α\alpha, those updates are tractable in closed form. The precision factor stays in the Gamma family with shape aNa_N and rate bNb_N:

aN=a0+M2,bN=b0+12 E[w⊤w]a_N = a_0 + \tfrac{M}{2}, \qquad b_N = b_0 + \tfrac{1}{2}\,\mathbb{E}[\mathbf{w}^{\top}\mathbf{w}]

The coefficient factor stays Gaussian with the familiar Bayesian-regression mean and covariance, but with α\alpha replaced by its variational expectation E[α]=aN/bN\mathbb{E}[\alpha] = a_N / b_N:

mN=β SN Φ⊤t,SN=(E[α] I+β Φ⊤Φ)−1\mathbf{m}_N = \beta \, \mathbf{S}_N \, \boldsymbol{\Phi}^{\top} \mathbf{t}, \qquad \mathbf{S}_N = \left(\mathbb{E}[\alpha]\,\mathbf{I} + \beta\,\boldsymbol{\Phi}^{\top}\boldsymbol{\Phi}\right)^{-1}

The CAVI loop alternates these two updates. Each step provably increases the lower bound L(q)\mathcal{L}(q). Convergence on this problem takes three iterations:

ELBO trace: lower bound jumps from -49 at iteration 1 to -29 by iteration 3, then plateaus through iteration 11.

Predictive distribution

Once q(w)=N(mN,SN)q(\mathbf{w}) = \mathcal{N}(\mathbf{m}_N, \mathbf{S}_N) is fitted, the predictive distribution at a new input x\mathbf{x} integrates the Gaussian likelihood against the variational posterior. The result is:

σ2(x)=1β+ϕ(x)⊤SN ϕ(x)\sigma^2(\mathbf{x}) = \frac{1}{\beta} + \boldsymbol{\phi}(\mathbf{x})^{\top} \mathbf{S}_N \, \boldsymbol{\phi}(\mathbf{x})

Two terms, two sources of uncertainty. The constant 1/β1/\beta is observation noise. The quadratic form is parameter uncertainty: it shrinks where you have data and grows where you do not. The widening band at ∣x∣>5|x| > 5 in the predictive plot is that second term doing its job.

Going Deeper: The ELBO and the Two Doors

CAVI is a loop of closed-form updates. The deeper question is what the loop optimises and why an alternative loop based on stochastic sampling exists at all.

The evidence lower bound

The log marginal likelihood admits a decomposition that holds for any choice of qq:

ln⁡p(X)  =  L(q)+KL(q ∥ p)\ln p(\mathbf{X}) \;=\; \mathcal{L}(q) + \mathrm{KL}(q \,\Vert\, p)

where the lower bound L(q)\mathcal{L}(q) and the KL term are

L(q)=∫q(Z) ln⁡p(X,Z)q(Z) dZ,KL(q∥p)=− ⁣∫q(Z) ln⁡p(Z∣X)q(Z) dZ\mathcal{L}(q) = \int q(\mathbf{Z}) \, \ln \frac{p(\mathbf{X}, \mathbf{Z})}{q(\mathbf{Z})} \, \mathrm{d}\mathbf{Z}, \qquad \mathrm{KL}(q \Vert p) = -\!\int q(\mathbf{Z}) \, \ln \frac{p(\mathbf{Z} \mid \mathbf{X})}{q(\mathbf{Z})} \, \mathrm{d}\mathbf{Z}

The same identity powers the EM algorithm. EM uses it to drive a point estimate of parameters while integrating out latent variables. VI uses it to drive a distributional approximation. Maximising L(q)\mathcal{L}(q) is equivalent to minimising KL(q ∥ p(Z∣X))\mathrm{KL}(q \,\Vert\, p(\mathbf{Z} \mid \mathbf{X})) because ln⁡p(X)\ln p(\mathbf{X}) is constant in qq.

The ELBO is also a tight lower bound on the log marginal likelihood, so its value at convergence approximates ln⁡p(t∣M)\ln p(\mathbf{t} \mid M) for a given model MM. Sweep MM and you get an approximation to the model-evidence sweep that the Bayesian model comparison post computes via Laplace. Plotted against polynomial degree, the lower bound peaks at the true generating degree:

ELBO versus polynomial degree: a sharp climb from M=1 (-2436) to M=3 (-18), peak circled at M=3 matching the true generating degree, then a slow decline through M=9.

A held-out validation set never had to make this decision. That is the model-selection argument for going Bayesian.

Stochastic and deterministic approximations

When the integrals do not collapse to closed form, you have two families of approximation. Stochastic techniques such as Markov chain Monte Carlo can, given infinite computational resource, generate exact results, with the approximation arising from the use of a finite amount of processor time. Deterministic approximation schemes instead build analytical approximations to the posterior distribution, for example by assuming that it factorises in a particular way, and some of these scale well to large applications.

VI is the second class. Where MCMC trades wall-clock for asymptotic exactness, VI trades exactness for wall-clock and a fixed parametric form. The cover image of this post is the same idea: an intractable target on the left, two distinct routes to a usable answer on the right.

CAVI versus NUTS, side by side

Animating both methods on the same dataset makes the trade-off concrete. The left panel runs CAVI and shows the predictive band at iteration tt. The right panel runs No-U-Turn-Sampler NUTS and shows the predictive band built from the first NtN_t posterior samples. The CAVI band tightens within a single iteration. The NUTS band wobbles for hundreds of samples before settling.

Two-panel animation: left shows the CAVI predictive band over iterations 1 to 11, already tight at iteration 1; right shows NUTS samples accumulating from 20 to 8000, with the band gradually filling in and converging to the same shape as CAVI.

Wall-clock on this problem: 0.4 milliseconds for CAVI, 34 seconds for NUTS at default settings. The five-orders-of-magnitude gap is what makes VI the default in modern variational autoencoders, GraphRAG embedding inference, and any setting where you need a posterior at every gradient step of a larger optimisation.

Where mean-field bites

Run the marginals through both methods and the picture is more nuanced. On this problem the means agree, but the VI Gaussian visibly underestimates the tails of the cubic coefficient:

Side-by-side marginals: VI Gaussian (gold curve) and NUTS samples (purple histogram) for the linear and cubic coefficients on the rescaled basis. Means agree. NUTS shows slightly heavier tails on the cubic coefficient.

Why VI is biased toward narrow posteriors comes down to the asymmetry of the KL divergence. Minimising KL(q ∥ p)\mathrm{KL}(q \,\Vert\, p) penalises qq for placing mass where pp has none. The optimum therefore prefers to underspend on the tails. Minimising KL(p ∥ q)\mathrm{KL}(p \,\Vert\, q) would do the opposite: cover everything, blur the modes. The convention in VI is the first form, so VI posteriors are mode-seeking and narrow. This is why VI estimates of credible intervals on safety-critical quantities deserve a sanity check against a short MCMC run.

Hyperparameters worth knowing

The choices that matter on Bayesian linear regression are short. The Gamma prior (a0,b0)(a_0, b_0) on α\alpha controls how strongly the model regularises before seeing data: setting a0=b0=0a_0 = b_0 = 0 recovers the noninformative limit and matches the evidence-framework derivation. The noise precision β\beta is fixed in this post; treating it as variational and giving it its own Gamma prior is a one-paragraph extension. The basis matters too: raising xx to the ninth power on [−5,5][-5, 5] produces a feature matrix with condition number around 59≈2×1065^9 \approx 2 \times 10^6, which is fine for closed-form CAVI but breaks NUTS without rescaling. The implementation in the notebook scales xx to [−1,1][-1, 1] before forming polynomial features; the predictive distribution is invariant, the geometry is much better.

Foundations: Variational Bayes

Variational methods predate machine learning by two centuries. Euler and Lagrange formalised the calculus of variations to find functions that extremise integrals. Feynman, Hibbs, and others used the same machinery in twentieth-century physics. The translation to probabilistic inference is recent.

The seminal modern reference is Jordan, Ghahramani, Jaakkola, and Saul's 1999 review, An Introduction to Variational Methods for Graphical Models. It established mean-field VI as a coherent framework for graphical models with intractable posteriors.

The most influential recent paper on bringing VI to mainstream statistical practice is Blei, Kucukelbir, and McAuliffe's 2017 Variational Inference: A Review for Statisticians. It introduces the modern stochastic, automatic-differentiation flavours (BBVI, ADVI, reparameterisation-trick VAEs) and remains one of the cleanest introductions.

For the specific case of Bayesian linear regression, the variational solution recovers the classical evidence framework of MacKay (1992) in the limit a0=b0=0a_0 = b_0 = 0:

E[α]  =  aNbN  =  MmN⊤mN+Tr(SN)\mathbb{E}[\alpha] \;=\; \frac{a_N}{b_N} \;=\; \frac{M}{\mathbf{m}_N^{\top}\mathbf{m}_N + \mathrm{Tr}(\mathbf{S}_N)}

The same EM update appears in the Bayesian neural networks post under the Laplace evidence framework. The variational posterior over α\alpha adds a width to that point estimate but does not move the centre.

Limitations and Pitfalls

VI is not free. The trade-offs to keep in mind:

  • Variance underestimation. Mean-field VI minimises KL(q ∥ p)\mathrm{KL}(q \,\Vert\, p), which is mode-seeking. Posterior intervals from VI are routinely too narrow. Rule of thumb: when posterior calibration matters more than wall-clock, validate against a short HMC run.
  • No correlations across factors. The factorisation q(w)q(α)q(\mathbf{w})q(\alpha) decouples coefficients from precision. The full posterior couples them. The marginal over w\mathbf{w} integrates this out and the disagreement is small here, but in non-conjugate models (Bayesian logistic regression, mixture models) the coupling matters more.
  • Local optima. ELBO is non-convex in qq for general models. Different initialisations converge to different fixed points. CAVI on Bayesian linear regression is a special case where the ELBO is concave and the optimum is unique.
  • Equivalence to evidence framework. The post recovers the evidence-framework solution exactly when a0=b0=0a_0 = b_0 = 0. So on this problem, the variational posterior over w\mathbf{w} is the same Gaussian you would have got from the Laplace approximation around the type-II maximum likelihood α^\hat\alpha. The novelty is the posterior over α\alpha itself, not over w\mathbf{w}.
  • Modern alternatives. Auto-differentiation VI (ADVI in Stan and PyMC, normalising flows in Pyro) lift the closed-form requirement and let VI run on any differentiable model. Reparameterisation-trick VI is what makes variational autoencoders and amortised inference networks tractable.

Interactive Tools

  • Distribution Explorer (Gamma): see how the Gamma prior on α\alpha shifts and sharpens as aa and bb change. The intuition for what (a0,b0)→(0,0)(a_0, b_0) \to (0, 0) means visually.
  • Bayes' Theorem Calculator: the prior-times-likelihood logic that variational inference is approximating, in a two-event toy form.
  • Regression Playground: fit polynomial features interactively and see how predictive variance grows with model complexity, the same overfitting effect the ELBO penalises.

Stay in the loop

Get notified when new tutorials and deep-dives are published. No spam, unsubscribe anytime.

Related Posts

Frequently Asked Questions