Tutorials › Econometrics (Graduate) › Hamiltonian Monte Carlo For Bayesian Regression

Bayesian Econometrics · Tutorial 882 of 952

Hamiltonian Monte Carlo For Bayesian Regression

Derive and work through Hamiltonian Monte Carlo updates for continuous regression parameters, including practical choices for integration step size and trajectory length.

Advanced 10 min read

What You'll Learn

  • Define the regression posterior as the target density for Hamiltonian Monte Carlo.
  • Derive the log-posterior gradient for Gaussian regression with a Gaussian prior.
  • Follow a leapfrog update and calculate its Metropolis acceptance probability.
  • Explain how momentum, mass matrix, step size, and trajectory length affect proposals.
  • Tune integration settings without confusing acceptance with evidence of convergence.

Why Use Hamiltonian Monte Carlo?

A Bayesian regression posterior can be difficult to explore when its coefficients are correlated or when the posterior mass lies in a narrow region of a continuous parameter space. A random-walk Metropolis proposal moves locally and may spend many iterations taking small steps. Hamiltonian Monte Carlo (HMC) uses the gradient of the log posterior to construct longer, directed proposals. It can make substantial moves while accounting for the shape of the posterior.

HMC is a simulation method, not a different posterior target. Its proposals are generated using a numerical approximation to a dynamical system, then a Metropolis step corrects for integration error. The method requires a differentiable log posterior with gradients that can be evaluated at proposed parameter values. The examples below use Gaussian regression with known error variance, but the same construction applies to other differentiable regression posteriors.

The Posterior Target and Its Gradient

Let \(y\) be the vector of outcomes, \(X\) the design matrix, and \(\beta\) the vector of regression coefficients. For a Gaussian linear regression with known error variance, suppose \(y\mid\beta,\sigma^2 \sim N(X\beta,\sigma^2 I)\), where \(\sigma^2\) is fixed. A prior density \(p(\beta)\) gives the posterior target \(\pi(\beta\mid y)\propto p(y\mid\beta)p(\beta)\). Constants that do not depend on \(\beta\) can be omitted when calculating the gradient or Metropolis ratio.

Definition: HMC augments a continuous parameter vector \(q\) with an auxiliary momentum vector \(p\). It defines a potential energy \(U(q)=-\log\pi(q\mid y)\) and a kinetic energy \(K(p)=\tfrac12 p^\mathsf{T}M^{-1}p\), where \(M\) is a positive-definite mass matrix. The joint density is proportional to \(\exp[-H(q,p)]\), where \(H(q,p)=U(q)+K(p)\) is the Hamiltonian. The gradient of the log posterior supplies the force that guides movement through parameter space.

For the Gaussian regression model, the log posterior, up to an additive constant, is \(\ell(\beta)= -\tfrac{1}{2\sigma^2}(y-X\beta)^\mathsf{T}(y-X\beta)+\log p(\beta)\). Differentiating with respect to \(\beta\) gives \(\nabla_\beta\ell(\beta)=X^\mathsf{T}(y-X\beta)/\sigma^2+\nabla_\beta\log p(\beta)\). The gradient points locally toward increasing log posterior density; the potential-energy gradient has the opposite sign, \(\nabla U(\beta)=-\nabla_\beta\ell(\beta)\). For a Gaussian prior \(\beta\sim N(m,V)\), the prior contribution is \(-V^{-1}(\beta-m)\).

Worked Example: Computing the Regression Gradient

Suppose the hypothetical data have predictor values \(x=(0,1,2)\) and outcomes \(y=(1,2,2)^\mathsf{T}\). Fit a regression with an intercept and slope, so the parameter order is \(q=\beta=(\beta_0,\beta_1)^\mathsf{T}\) and the design matrix has rows \((1,x_i)\). Take \(\sigma^2=1\) and the prior \(\beta\sim N(0,10I)\). Find the log-posterior gradient at \(\beta=(0,0)^\mathsf{T}\).

Here \(X=\begin{pmatrix}1&0\\1&1\\1&2\end{pmatrix}\), so \(X^\mathsf{T}y=(1+2+2,\;0(1)+1(2)+2(2))^\mathsf{T}=(5,6)^\mathsf{T}\). At \(\beta=0\), the residual vector is \(y-X\beta=y\). The prior has precision \(V^{-1}=0.1I\), and its gradient at zero is also zero. Therefore \(\nabla_\beta\ell(0)=X^\mathsf{T}y-0.1(0,0)^\mathsf{T}=(5,6)^\mathsf{T}\).

The first component, \(5\), is the intercept component; the second, \(6\), is the slope component. Locally, increasing either coefficient from this point increases the log posterior in that coordinate's positive direction, holding the other coordinate fixed. The potential-energy gradient is \(\nabla U(0)=(-5,-6)^\mathsf{T}\), which points toward decreasing log posterior.

Hamiltonian Dynamics and Leapfrog Integration

In ideal Hamiltonian dynamics, the position \(q\) and momentum \(p\) evolve according to \(\frac{dq}{dt}=M^{-1}p\) and \(\frac{dp}{dt}=-\nabla U(q)\). The momentum is refreshed from \(N(0,M)\) to start a trajectory. If these differential equations could be followed exactly, the Hamiltonian would stay constant, so movement could travel through a posterior region without systematically favoring high- or low-density states. In practice, the equations are integrated numerically.

HMC commonly uses the leapfrog integrator. For step size \(\epsilon>0\), one step consists of a half momentum update, a full position update, and a second half momentum update. Repeating this operation \(L\) times gives a proposed endpoint. The approximate trajectory length is \(\tau=L\epsilon\).

$$ \begin{aligned} p_{k+\frac12} &= p_k-\frac{\epsilon}{2}\nabla U(q_k),\\ q_{k+1} &= q_k+\epsilon M^{-1}p_{k+\frac12},\\ p_{k+1} &= p_{k+\frac12}-\frac{\epsilon}{2}\nabla U(q_{k+1}). \end{aligned} $$

Leapfrog is useful because it is reversible (with momentum reversal) and preserves volume in the joint position-momentum space. Each momentum update is a shear in \(p\), and each position update is a shear in \(q\); each has Jacobian determinant one. The symmetric half-step, full-step, half-step sequence reverses when run backward with momentum negated. These properties make it possible to apply a Metropolis correction to the numerical proposal rather than treating the numerical path as exact.

After \(L\) steps, let the endpoint be \((q^\ast,p^\ast)\). The proposal is accepted with probability \(\min\{1,\exp[-H(q^\ast,p^\ast)+H(q_0,p_0)]\}\). Equivalently, if \(\Delta H=H(q^\ast,p^\ast)-H(q_0,p_0)\), the probability is \(\min(1,\exp(-\Delta H))\). If rejected, the position remains \(q_0\). A momentum sign reversal is often included in the proposal description to make reversibility explicit; because kinetic energy depends quadratically on momentum, the sign does not change the acceptance calculation.

Worked Example: One Leapfrog Step and Its Acceptance Probability

Continue with the hypothetical regression and prior above. Use mass matrix \(M=I\), start at \(q_0=(0,0)^\mathsf{T}\) with momentum \(p_0=(1,0)^\mathsf{T}\), and take one leapfrog step with \(\epsilon=0.1\). For these data, \(X^\mathsf{T}X=\begin{pmatrix}3&3\\3&5\end{pmatrix}\), so the log-posterior gradient is \(X^\mathsf{T}y-(X^\mathsf{T}X+0.1I)\beta\).

At \(q_0\), the log-posterior gradient is \((5,6)^\mathsf{T}\), so \(\nabla U(q_0)=(-5,-6)^\mathsf{T}\). The half momentum update is \(p_{1/2}=p_0-0.05(-5,-6)^\mathsf{T}=(1.25,0.30)^\mathsf{T}\). Since \(M=I\), the position update gives \(q_1=q_0+0.1p_{1/2}=(0.125,0.030)^\mathsf{T}\).

At this new position, \((X^\mathsf{T}X+0.1I)q_1=(0.4775,0.528)^\mathsf{T}\), so \(\nabla_\beta\ell(q_1)=(4.5225,5.472)^\mathsf{T}\) and \(\nabla U(q_1)=(-4.5225,-5.472)^\mathsf{T}\). The final momentum is therefore \(p_1=(1.25,0.30)^\mathsf{T}-0.05(-4.5225,-5.472)^\mathsf{T}=(1.476125,0.5736)^\mathsf{T}\).

Ignoring constants, the potential energy is \(U(\beta)=\tfrac12\{(y-X\beta)^\mathsf{T}(y-X\beta)+0.1\beta^\mathsf{T}\beta\}\). At the starting point, \(U(q_0)=\tfrac12(1^2+2^2+2^2)=4.5\), and \(K(p_0)=\tfrac12\). Thus \(H_0=5\). At \(q_1\), the fitted values are \((0.125,0.155,0.185)^\mathsf{T}\), giving residual sum of squares \(0.875^2+1.845^2+1.815^2=7.463875\). The prior penalty is \(0.1(0.125^2+0.030^2)=0.0016525\), hence \(U(q_1)=3.73276375\). Also, \(K(p_1)=\tfrac12(1.476125^2+0.5736^2)=1.253980988\), so \(H_1\approx4.986745\).

The energy error is \(\Delta H\approx-0.01326\), and the acceptance probability is \(\min(1,\exp(0.01326))=1\). This proposal is accepted. A negative energy error does not mean the numerical method is exact; the Metropolis rule simply accepts any proposal whose computed Hamiltonian is no larger than the starting value.

Choosing Step Size and Trajectory Length

The step size \(\epsilon\) controls the numerical resolution of the path. If it is too large, the integrator may make substantial energy errors, causing frequent rejections or unstable trajectories. A smaller step size generally improves numerical accuracy but requires more gradient evaluations for the same trajectory length. The mass matrix \(M\) also matters: it sets the scale of momentum and can help accommodate different scales and correlations among parameters. For example, a well-chosen mass matrix can reduce inefficient movement when coefficients have very different posterior scales.

The number of steps \(L\), together with \(\epsilon\), determines how far the trajectory runs. If \(L\) is too small, proposals may not travel far from their starting values. If it is too large, a trajectory can spend extra computation retracing or circling through regions already visited. The product \(\tau=L\epsilon\) is a useful description of integration length, but the best length depends on the posterior geometry and is not determined by a universal formula.

Worked Example: Comparing Two Tuning Choices

Suppose a hypothetical pilot run compares two settings for the same continuous regression posterior. Setting A uses \(\epsilon=0.05\) and \(L=20\); setting B uses \(\epsilon=0.20\) and \(L=5\). Each uses 100 proposals. Suppose A accepts 92 proposals and B accepts 58. Compare their integration lengths, approximate gradient costs, and acceptance fractions.

For A, \(\tau=L\epsilon=20(0.05)=1.0\), with approximately 20 leapfrog steps, and its observed acceptance fraction is \(92/100=0.92\). For B, \(\tau=5(0.20)=1.0\) as well, with approximately 5 steps, and its observed acceptance fraction is \(58/100=0.58\). Both settings have the same nominal trajectory length, but B takes larger numerical steps and has lower acceptance in this hypothetical pilot. That pattern is consistent with greater integration error for B; it does not prove that step size alone caused the difference in every run.

A practical response would be to try a smaller step size than B's, while checking whether the resulting proposals still travel usefully through the parameter space. A high acceptance fraction by itself is not sufficient: extremely short trajectories can be accepted almost always while moving little. Conversely, lowering acceptance through a larger step size may waste computation on rejected proposals. Tuning therefore considers numerical stability, acceptance, computational cost, and the size of proposed moves together. The figures from this pilot are descriptive tuning information, not a conclusion that the chain has converged.

Applying HMC to Regression Parameters

For a regression with several continuous coefficients, the position vector \(q\) can simply be \(\beta\). If an unknown variance or another continuous parameter is also sampled, it may be included in \(q\) after expressing it on an unconstrained scale. For example, a positive variance can be represented by its logarithm; the target density on the transformed scale must include the appropriate change-of-variables Jacobian. The complete target must be differentiable in the coordinates used for HMC.

In an econometric model, the gradient is valuable because it combines information from all observations into a direction of local posterior increase. That direction can make HMC substantially more efficient than proposals that ignore local posterior geometry, particularly when coefficients are strongly related. But gradients do not remove the need to specify the likelihood and prior correctly, and the acceptance step cannot repair a misspecified model. HMC samples from the posterior density supplied to it, subject to the accuracy of implementation and simulation.

Common Mistakes and Practical Checks

  • Reversing the gradient sign. The log-posterior gradient points uphill in log posterior; the potential-energy gradient is its negative. In the leapfrog momentum update, use \(-\nabla U(q)\), equivalently the log-posterior gradient.
  • Mixing up parameter order. If \(q=(\beta_0,\beta_1)^\mathsf{T}\), the first gradient entry is for the intercept and the second is for the slope. Keep this order consistent in the design matrix, vectors, and interpretation.
  • Assuming leapfrog conserves energy exactly. It approximates the Hamiltonian dynamics. The Metropolis acceptance probability corrects for the resulting energy error.
  • Changing step size without considering trajectory length. Since \(\tau=L\epsilon\), changing \(\epsilon\) while holding \(L\) fixed changes both numerical resolution and total path length.
  • Treating a high acceptance fraction as proof of good sampling. Acceptance is only one tuning indicator. Short, frequently accepted proposals may still move little; convergence and mixing require separate assessment.
Key takeaway: HMC uses the log-posterior gradient to guide a momentum-augmented trajectory, leapfrog integration to approximate that trajectory, and a Metropolis correction to preserve the intended posterior target. Step size controls numerical accuracy; trajectory length controls how far each proposal travels.

Check Your Understanding

Work through these questions using the definitions and calculations above.

  1. For a Gaussian regression with prior \(\beta\sim N(m,V)\), write the prior contribution to the log-posterior gradient.
  2. In the worked gradient example, why is \(5\) the intercept component and \(6\) the slope component?
  3. What changes in the leapfrog update if the mass matrix is not the identity?
  4. If a proposed endpoint has \(\Delta H=0.4\), what is its Metropolis acceptance probability, approximately?
  5. Explain why reducing the leapfrog step size while holding \(L\) fixed also changes the trajectory length.
Clinical Biostats