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
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:

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 couples the coefficients and their precision. Mean-field VI replaces it with a factorised approximation:
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 . 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:
For Bayesian linear regression with a Gaussian likelihood and a Gamma prior on , those updates are tractable in closed form. The precision factor stays in the Gamma family with shape and rate :
The coefficient factor stays Gaussian with the familiar Bayesian-regression mean and covariance, but with replaced by its variational expectation :
The CAVI loop alternates these two updates. Each step provably increases the lower bound . Convergence on this problem takes three iterations:

Predictive distribution
Once is fitted, the predictive distribution at a new input integrates the Gaussian likelihood against the variational posterior. The result is:
Two terms, two sources of uncertainty. The constant 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 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 :
where the lower bound and the KL term are
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 is equivalent to minimising because is constant in .
The ELBO is also a tight lower bound on the log marginal likelihood, so its value at convergence approximates for a given model . Sweep 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:

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 . The right panel runs No-U-Turn-Sampler NUTS and shows the predictive band built from the first posterior samples. The CAVI band tightens within a single iteration. The NUTS band wobbles for hundreds of samples before settling.

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:

Why VI is biased toward narrow posteriors comes down to the asymmetry of the KL divergence. Minimising penalises for placing mass where has none. The optimum therefore prefers to underspend on the tails. Minimising 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 on controls how strongly the model regularises before seeing data: setting recovers the noninformative limit and matches the evidence-framework derivation. The noise precision 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 to the ninth power on produces a feature matrix with condition number around , which is fine for closed-form CAVI but breaks NUTS without rescaling. The implementation in the notebook scales to 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 :
The same EM update appears in the Bayesian neural networks post under the Laplace evidence framework. The variational posterior over 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 , 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 decouples coefficients from precision. The full posterior couples them. The marginal over 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 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 . So on this problem, the variational posterior over is the same Gaussian you would have got from the Laplace approximation around the type-II maximum likelihood . The novelty is the posterior over itself, not over .
- 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 shifts and sharpens as and change. The intuition for what 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.
Related Posts
For gradient-based posterior sampling, the Hamiltonian Monte Carlo tutorial compares trajectories, step sizes and sampling behaviour.
From MLE to Bayesian Inference: the foundation post on why posterior distributions are worth computing in the first place.
Bayesian Model Comparison: The Evidence Framework: the deterministic alternative to ELBO sweeping for picking model complexity.
EM Algorithm: Coin Toss Intuitive Guide: the same decomposition, used for point estimation rather than full Bayes.
MCMC Metropolis-Hastings: Island Hopping Guide: the door this post does not walk through, in detail.
Linear Regression from Scratch: Five Solvers, One Answer: the non-Bayesian end of the same modelling problem, including OLS, ridge, and Bayesian linear regression with fixed .
From Thermodynamics to ML: Entropy, KL and Mutual Info: variational Bayes works by minimising the KL divergence to the true posterior, the quantity defined here.







