Understanding Metropolis-Hastings and Gibbs Sampling from First Principles
Learning Objectives
By the end of this lesson, you will:
- Understand why MCMC was invented.
- Understand what a Markov Chain is.
- Understand why sampling solves Bayesian inference.
- Understand the logic behind the Metropolis-Hastings acceptance ratio.
- Learn Gibbs Sampling from first principles.
- Implement both algorithms in Python.
- Apply them to healthcare, epidemiology, and supply chain problems.
Why Do We Need MCMC?
Recall Bayes’ theorem:
The challenge is usually the denominator:
For most realistic Bayesian models, this integral cannot be evaluated analytically.
Examples include:
Healthcare:
Epidemiology:
Supply Chain:
Instead of solving the integral directly, MCMC asks a different question:
Can we generate samples from the posterior distribution?
If we can generate:
from
then almost every Bayesian quantity can be estimated using simple averages.
The Big Idea Behind MCMC
Suppose we want the posterior mean.
Mathematically:
If we have posterior samples:
then:
Similarly:
Posterior variance:
Posterior probability:
The entire Bayesian problem becomes:
Generate samples from the posterior distribution.
What Is a Markov Chain?
A Markov Chain is a sequence:
satisfying:
The future depends only on the present.
It does not depend on the entire history.
Healthcare example:
Suppose a patient can be:
- Healthy
- Sick
The patient’s health tomorrow depends mostly on today’s condition.
This is a Markov process.
The Goal of MCMC
Instead of sampling directly from
which is difficult,
we construct a Markov chain whose long-run distribution is
Then after running the chain long enough:
This is the central idea behind MCMC.
Metropolis-Hastings Algorithm
Metropolis-Hastings is the most widely used MCMC algorithm.
The algorithm repeatedly:
- Proposes a move.
- Decides whether to accept it.
- Repeats.
Over time the chain spends the correct proportion of time in each region of the posterior.
Step 1: Start Somewhere
Suppose our current value is:
For example:
The starting point is usually arbitrary.
Step 2: Generate a Proposal
We generate a candidate value:
A common choice is:
This means we randomly explore nearby values.
Suppose:
Step 3: Decide Whether To Move
This is where the brilliance of Metropolis-Hastings appears.
We compute:
for symmetric proposal distributions.
Accept with probability:
Why Do We Use This Ratio?
This is one of the most important questions in Bayesian computation.
Suppose:
Current location:
Proposed location:
Then:
Since:
we automatically accept.
Why?
Because the proposal lies in a region that is five times more probable under the posterior.
The chain should spend more time there.
Why Not Always Reject Worse Points?
Suppose:
Current location: 0.50
Proposed location: 0.25
Then:
Accept with probability: 50%
At first this seems strange.
Why move to a less likely location?
Because if we only accepted better moves, the chain could become trapped.
Imagine a posterior with two peaks.
If the chain reaches one peak, it may never leave.
Allowing occasional downhill moves enables exploration of the entire posterior distribution.
The Real Metropolis-Hastings Ratio
For asymmetric proposal distributions:
The extra terms compensate for proposal bias.
For symmetric proposals:
and they cancel.
Why Is MCMC So Powerful?
Notice:
Substituting into the acceptance ratio:
The difficult term: cancels completely.
This is the key reason MCMC became so successful.
The hardest integral in Bayesian statistics never needs to be computed.
Example 1: Healthcare — Drug Effectiveness
Suppose:
Posterior:
Goal:
Generate 50,000 Metropolis-Hastings samples.
Estimate:
This gives the probability that the treatment truly improves patient outcomes.
Example 2: Epidemiology
Suppose:
Posterior:
Goal:
Values above one indicate an expanding epidemic.
Metropolis-Hastings samples provide the answer immediately.
Example 3: Supply Chain Forecasting
Suppose:
Posterior:
Generate posterior samples:
Then estimate:
using simulation.
Python Example: Metropolis-Hastings
import numpy as np
def target(x):
return np.exp(-x**2/2)
n = 10000
theta = 0
samples = []
for i in range(n):
proposal = np.random.normal(
theta,
1
)
r = target(proposal) / target(theta)
if np.random.rand() < min(1, r):
theta = proposal
samples.append(theta)
samples = np.array(samples)Understanding Gibbs Sampling
Metropolis-Hastings is very general.
Gibbs Sampling is a special case that becomes extremely efficient when conditional distributions are available.
The Core Idea
Suppose we have two parameters and
The joint posterior:
may be difficult.
However, suppose we know:
and
These conditional distributions may be easy to sample from.
Gibbs Sampling Algorithm
Start with:
Update:
Then:
Repeat indefinitely.
Why Does Gibbs Sampling Work?
Imagine moving around a mountain.
Metropolis-Hastings jumps randomly.
Gibbs moves one coordinate at a time.
Update
Then update:
Then update:
again.
Eventually the chain explores the entire posterior.
Why Is There No Acceptance Ratio?
Because every draw already comes from the correct conditional distribution.
Every proposed value is automatically valid.
Mathematically:
for every iteration.
Nothing is rejected.
Example 1: Blood Pressure Model
Parameters:
Posterior:
Update:
then
Example 2: Hospital Readmission Model
Parameters:
and
Posterior:
Update:
then
Example 3: Supply Chain Forecasting
Parameters:
Posterior:
Update each parameter conditionally.
Generate future demand forecasts using posterior samples.
Python Example: Gibbs Sampling
import numpy as np
n = 10000
x = 0
y = 0
samples = []
for i in range(n):
x = np.random.normal(
y,
1
)
y = np.random.normal(
x,
1
)
samples.append([x, y])
samples = np.array(samples)
Metropolis-Hastings vs Gibbs Sampling
| Feature | Metropolis-Hastings | Gibbs Sampling |
|---|---|---|
| Requires conditional distributions | No | Yes |
| Acceptance ratio | Yes | No |
| Every proposal accepted | No | Yes |
| General-purpose | Yes | No |
| Easier to apply | Yes | Sometimes |
| More efficient when conditionals known | No | Yes |
Key Takeaways
MCMC solves Bayesian inference by generating samples from the posterior distribution.
Metropolis-Hastings uses the acceptance ratio:
to ensure the chain visits regions according to their posterior probability.
The normalizing constant:
cancels from the acceptance ratio, making Bayesian inference feasible.
Gibbs Sampling is a special case of MCMC where we sample directly from conditional distributions.
Because each sample already comes from the correct conditional distribution:
and every proposal is accepted.
Together, Metropolis-Hastings and Gibbs Sampling form the foundation of modern Bayesian computation and lead directly to advanced methods such as Hamiltonian Monte Carlo, NUTS, Sequential Monte Carlo, Bayesian Nonparametrics, and Bayesian Machine Learning.
References
- Gelman, Carlin, Stern, Dunson, Vehtari, and Rubin. Bayesian Data Analysis.
- Robert and Casella. Monte Carlo Statistical Methods.
- Brooks, Gelman, Jones, and Meng. Handbook of Markov Chain Monte Carlo.
- Murphy. Machine Learning: A Probabilistic Perspective.

Leave a Reply