This Probability concept is the current idea: keep the same invariant visible across Intuition, Math, Code, Interactive Demo.
Probability
MCMC: Metropolis-Hastings and Gibbs Sampling
MCMC turns an intractable target distribution into a Markov chain: Metropolis-Hastings accepts or rejects proposals by a target ratio, while Gibbs resamples coordinates from conditionals.
Concept Structure
MCMC: Metropolis-Hastings and Gibbs Sampling
Start with the picture, metaphor, or geometric mechanism.
Make the objects explicit and connect them with notation.
Mirror the equations with runnable implementation details.
Manipulate the mechanism and watch the idea respond.
Learner Contract
What this page should let you do.
6 prerequisites listed; refresh them before leaning on the math or code.
Explain the mechanism, trace the main notation, and test one prediction in the live demo.
Read the intuition before the notation; the math should name a mechanism you already felt.
Follow this edge after making one prediction here; the next page should reuse the result, not restart the route.
Claim/source review status
Substantive review recorded
1/1 claims have bounded review metadata; still check caveats and source scope.Metadata-derived; review may be AI-assisted. Not a human certification.01
Intuition
Build the mental picture first so the rest of the page has something to attach to.
Conjugate Bayesian updating gives a rare luxury: multiply likelihood by prior and read the posterior exactly.
Most useful Bayesian models do not stay that polite. A posterior can be known only up to a constant:
or, in a continuous model, an integral we cannot compute. The unnormalized score is easy enough to evaluate at one state, but the normalizer is the hard part.
Markov chain Monte Carlo changes the job. Instead of trying to draw independent samples from directly, we build a Markov chain:
whose long-run distribution is . The samples are correlated, so we do not get iid magic. But if the chain is designed well, run long enough, and checked carefully, averages over the chain can approximate posterior expectations.
Metropolis-Hastings is the proposal-and-correction version:
- stand at the current state ;
- propose a candidate from a proposal distribution ;
- accept the move with a probability that compares the proposed target score to the current target score.
The important surprise is that the global normalizer cancels. If the target score doubles, an uphill symmetric proposal is accepted. If the score drops to one quarter, the move is accepted only one quarter of the time. Rejections are not failure; they are how the chain keeps the right long-run distribution.
Gibbs sampling is the conditional-resampling version. Instead of proposing an arbitrary move, it chooses one coordinate and samples that coordinate from its exact conditional distribution while holding the other coordinates fixed:
That can be easier than sampling the full joint distribution. In a high-dimensional model, a single conditional can be tractable even when the full posterior is not.
The learner move is to separate four ideas:
- scores states but may not be normalized;
- the transition rule defines how the chain moves;
- stationarity means the target distribution is preserved by the transition rule;
- mixing and diagnostics decide whether a finite run deserves trust.
MCMC is not "run a loop and believe the histogram." It is a way to turn local probability comparisons into global posterior exploration, with correlation and convergence caveats attached.
02
Math
Translate the story into symbols, assumptions, and a derivation you can inspect.
Let be a finite state space and let be the target distribution. A Markov chain transition kernel gives the probability of moving from to in one step.
The target distribution is stationary for the chain when
This equation says that if the chain's current state is already distributed as , one transition leaves it distributed as .
A common sufficient condition is detailed balance:
Detailed balance says the target-weighted probability flow from to matches the reverse flow. Summing detailed balance over all gives stationarity.
Metropolis-Hastings
Metropolis-Hastings starts with a proposal distribution . For , define
where the acceptance probability is
If the proposal is rejected, the chain stays at . The self-transition probability is whatever mass is left:
When the target is known only up to a normalizing constant, . Substitute that into the ratio:
The same unknown appears upstairs and downstairs, so it cancels.
For a symmetric proposal, , the formula becomes
That is the finite-state rule in the demo. Moving from score to score is accepted with probability . Moving from score to score is accepted with probability .
Gibbs Sampling
Suppose the state is split into coordinates . A Gibbs update chooses one coordinate and samples
For two binary coordinates, if is fixed and the unnormalized scores are
then
The full target normalizer over all states is not needed. The conditional normalizer only sums over the coordinate being refreshed.
Finite-Run Caveat
Stationarity is an asymptotic design property. A useful MCMC run also needs the chain to be irreducible enough to reach the relevant states, aperiodic enough not to oscillate deterministically, and well-mixed enough that finite samples represent the target. Burn-in, autocorrelation, effective sample size, multiple chains, and posterior predictive checks are practical warnings, not decorative statistics.
03
Code
Keep the implementation aligned with the notation so the algorithm is legible.
import numpy as np
states = [(0, 0), (0, 1), (1, 0), (1, 1)]
score = {(0, 0): 1.0, (0, 1): 3.0, (1, 0): 2.0, (1, 1): 8.0}
target = {s: score[s] / sum(score.values()) for s in states}
def mh_step(current, proposal, u):
ratio = score[proposal] / score[current] # symmetric proposal
alpha = min(1.0, ratio)
accepted = u <= alpha
return proposal if accepted else current, alpha, accepted
def gibbs_refresh_x_when_y_is_1(u):
p_x1 = score[(1, 1)] / (score[(0, 1)] + score[(1, 1)])
return ((1, 1) if u <= p_x1 else (0, 1)), p_x1
chain = [(0, 0)]
proposals = [(0, 1), (1, 1), (1, 0), (0, 0), (1, 1), (0, 1)]
uniforms = [0.20, 0.91, 0.12, 0.70, 0.40, 0.60]
for proposal, u in zip(proposals, uniforms):
nxt, alpha, accepted = mh_step(chain[-1], proposal, u)
chain.append(nxt)
print(chain[-2], "->", proposal, "alpha", round(alpha, 3),
"u", u, "accepted", accepted, "next", nxt)
print("target", target)
print("Gibbs x|y=1", gibbs_refresh_x_when_y_is_1(0.62))
The code never uses the target normalizer inside mh_step. It only compares unnormalized scores. The normalizer appears when we print target, because that is a diagnostic view of the toy distribution, not a requirement for making one Metropolis-Hastings move.
04
Interactive Demo
Use direct manipulation to connect the explanation to a moving system.
The Transition Ledger Lab hides the acceptance or conditional ledger until you commit.
Switch among three situations:
- an uphill Metropolis-Hastings proposal from score to score ;
- a downhill Metropolis-Hastings proposal from score to score ;
- a Gibbs update that refreshes while holding fixed.
Before revealing, decide whether the next move should accept, reject, resample a coordinate from a conditional, or require the global normalizer. Then reveal the ratio, the uniform draw, the next state, and a small stationarity check for the finite chain.
Live Concept Demo
Explore MCMC: Metropolis-Hastings and Gibbs Sampling
The stage is code-native and interactive. Use it to test the explanation against the mechanism.
Manipulate one control and predict the visible change.
Commit to what MCMC: Metropolis-Hastings and Gibbs Sampling should make visible before reading the result.
After The First Pass
Turn the concept into an inspected object.
Once the invariant is visible in the intuition, math, code, and demo, use these panels to inspect the mechanism visually, check source support, practice the idea, and attach a grounded research question.
Mechanism Storyboard
See the idea move before the page explains it
MCMC turns an intractable target distribution into a Markov chain: Metropolis-Hastings accepts or rejects proposals by a target ratio, while Gibbs resamples coordinates from conditionals.
Start with the picture, metaphor, or geometric mechanism.
Before reading further, choose the kind of change MCMC: Metropolis-Hastings and Gibbs Sampling should make visible.
Visual Inquiry
Make the image answer a mathematical question
MCMC turns an intractable target distribution into a Markov chain: Metropolis-Hastings accepts or rejects proposals by a target ratio, while Gibbs resamples coordinates from conditionals.
Which visible object should carry the first intuition?
Pick the cue that should make MCMC: Metropolis-Hastings and Gibbs Sampling easier to reason about before the page gives the answer.
Source Grounding
Canonical references for the mechanism on this page.
Grounds Monte Carlo sampling, Markov-chain stationary distributions, detailed balance, Metropolis-Hastings acceptance ratios, Gibbs sampling, burn-in, and proposal/mixing cautions.
Open sourceSupports detailed-balance reasoning, unnormalized target densities, the Metropolis acceptance rule, Gibbs sampling, and the warning that correlated samples require care.
Open sourceSupports the Gibbs update as resampling one variable from its conditional distribution while holding the rest fixed, along with practical burn-in and mixing discussion.
Open sourceDeep-learning textbook anchor for MCMC as a sampling method and for the practical caveat that mixing can become slow in high-dimensional energy landscapes.
Open sourceHistorical source for the Metropolis sampling method.
Open sourceHistorical source for the generalized Metropolis-Hastings transition rule.
Open sourceClaim Review
MCMC turns an intractable target distribution into a Markov chain: Metropolis-Hastings accepts or rejects proposals by a target ratio, while Gibbs resamples coordinates from conditionals.
Claims without a substantive review badge still need exact source-support review.
cs228-sampling-notes, gatsby-mcmc-lecture, mit-sontag-gibbs, goodfellow-2016-deep-learning-monte-carlo, metropolis-1953, hastings-1970
Use equations, runnable code, and demos to check whether the source support is operational.
The sources support the page's finite-state MCMC witness, the stationarity/detailed-balance math, the symmetric-proposal Metropolis-Hastings acceptance rule, the Gibbs full-conditional update, and the caveat that correlated samples need burn-in, mixing, and diagnostic scrutiny.
Sources: CS228 Notes: Sampling Methods, Machine Learning and Neural Computation: Markov Chain Monte Carlo, MIT 6.438 Inference: Gibbs Sampling, Deep Learning, Chapter 17: Monte Carlo MethodsFinite discrete witness only; excludes continuous-state measure theory, Hamiltonian Monte Carlo, slice sampling, adaptive MCMC, exact convergence diagnostics, high-dimensional posterior geometry, and a GPT Pro publication pass.A bounded review summary is present; still check caveats and exact reference scope.Checked Stanford CS228 notes for Markov-chain stationarity, detailed balance, Metropolis-Hastings ratios, Gibbs sampling, burn-in, and mixing caveats; checked Gatsby/UCL MCMC notes for detailed balance and unnormalized target-density framing; checked MIT Sontag Gibbs slides for one-coordinate conditional updates; checked the Deep Learning Book for MCMC's role in machine learning and slow-mixing caveats; used Metropolis, Hastings, and Geman & Geman as historical anchors. GPT Pro publication critique remains pending.
Reviewer: codex-local-source-review; reviewed 2026-07-02Source support candidates
course-notes 2026CS228 Notes: Sampling MethodsGrounds Monte Carlo sampling, Markov-chain stationary distributions, detailed balance, Metropolis-Hastings acceptance ratios, Gibbs sampling, burn-in, and proposal/mixing cautions.
course-notes 2015Machine Learning and Neural Computation: Markov Chain Monte CarloSupports detailed-balance reasoning, unnormalized target densities, the Metropolis acceptance rule, Gibbs sampling, and the warning that correlated samples require care.
course-notes 2015MIT 6.438 Inference: Gibbs SamplingSupports the Gibbs update as resampling one variable from its conditional distribution while holding the rest fixed, along with practical burn-in and mixing discussion.
book 2016Deep Learning, Chapter 17: Monte Carlo MethodsDeep-learning textbook anchor for MCMC as a sampling method and for the practical caveat that mixing can become slow in high-dimensional energy landscapes.
Practice Loop
Try the idea before it explains itself
MCMC turns an intractable target distribution into a Markov chain: Metropolis-Hastings accepts or rejects proposals by a target ratio, while Gibbs resamples coordinates from conditionals.
Before touching the demo, predict one visible change that should happen in MCMC: Metropolis-Hastings and Gibbs Sampling.
Reveal when your model needs a nudge.
Reveal when your model needs a nudge.
Reveal when your model needs a nudge.
A concrete answer is on the canvas.
The answer names why the claim should hold.
It touches the page context or a neighboring idea.
Research Room
Attach the question to a claim, equation, code, or demo
Pick the concept, equation, source, runnable code, claim, misconception, or demo state before asking for help. The handoff keeps that page item in context.Open the draft below to save one note and next action in this browser.
MCMC: Metropolis-Hastings and Gibbs Sampling
What is the smallest example that makes MCMC: Metropolis-Hastings and Gibbs Sampling click without losing the math?
Local action draftNo local draft saved yetExpand only when ready to capture one local next action
This draft stays in this browser, attached to the selected learning item.
- References to inspect: attached references on this page.
- Definition, prerequisite, and contrast concept links
- The equation or runnable code that makes the concept operational
- One demo state that shows the invariant instead of a slogan
- The learner can state the mechanism in their own words
- The learner can name the prerequisite that would repair confusion
- The learner can predict how the mechanism changes under one perturbation
I am working in Continuous Function's research reading room. Object: concept - MCMC: Metropolis-Hastings and Gibbs Sampling Selected item key: recorded for copy. Context: Probability Page anchor: recorded for copy. Open question: What is the smallest example that makes MCMC: Metropolis-Hastings and Gibbs Sampling click without losing the math? Evidence to inspect: - References to inspect: attached references on this page. - Definition, prerequisite, and contrast concept links - The equation or runnable code that makes the concept operational - One demo state that shows the invariant instead of a slogan What would resolve this: - The learner can state the mechanism in their own words - The learner can name the prerequisite that would repair confusion - The learner can predict how the mechanism changes under one perturbation Answer as a careful research tutor: stay source-grounded, separate verified evidence from assumptions, name the relevant math objects, and end with one next action.
concept/concept-notebook/probability/mcmc-metropolis-hastings-gibbs
concept:probability/mcmc-metropolis-hastings-gibbs