Markov Chains & the Metropolis Sampler
This lesson is about chains: a transition matrix, the long-run distribution a chain settles into, PageRank, and the Metropolis sampler that turns a chain into a tool for drawing random samples. It needs only probability and one idea from the eigenvalues lesson. The next lesson, Markov Decision Processes, adds decisions to the same chain, and it is optional if you are not heading toward reinforcement learning.
After this lesson, you will be able to:
- Understand the Markov property — the future depends only on the present, not the path you took to get there — and recognise where it shows up in modern AI
- Compute transition matrices, k-step transitions, and stationary distributions, and see why solving for the stationary distribution is just an eigenvector problem from a previous lesson
- Read how fast a chain forgets its starting state from the second-largest eigenvalue, and recognise absorbing, transient and recurrent states
- Compute PageRank on a tiny web (including a page with no outgoing links) and explain why the matrix is flipped to column form in the code
- Run a Metropolis sampler by hand on four states and in code on a two-bump target, and state the acceptance rule min(1, p(x') / p(x))
- Explain why MCMC is a Markov chain built to have your target as its stationary distribution, and why successive draws from it are correlated
Before you start
#The Present Screens Off the Past
This is the equation that runs reinforcement learning. The Markov property looks deceptively simple, but stacking it on top of itself produces some of the deepest equations in modern AI: the Bellman equation, the diffusion forward process, the autoregressive decoding loop in every LLM. Get this lesson and you can read RL, diffusion, and decoding papers without flinching.
X_0, X_1, X_2, … where each X_{t+1} depends only on X_t, not on the full history. Formally:Try it! Open the Python REPL (bottom-right of the screen: click Quick Actions, then Python) and type these lines yourself.
A chess engine is deciding its next move from the current board position. Does the engine need to know the full move history to play optimally, or is the position alone enough?
#A Worked Example: The Weather Chain
Suppose tomorrow's weather depends only on today's, with these transition probabilities:
- If today is sunny, tomorrow is sunny with probability 0.8 and rainy with probability 0.2
- If today is rainy, tomorrow is sunny with probability 0.4 and rainy with probability 0.6
P, where P_ij = "probability of going from state i to state j":π_0 = [1, 0] (definitely sunny), tomorrow's distribution is:Note on convention. This lesson uses row vectors (π_{t+1} = π_t P) because that is what most RL textbooks use. Some linear-algebra textbooks (and PyTorch code that prefers column vectors) write the same thing asπ_{t+1}^T = P^T π_t^T. They are mathematically identical — just different sides of the same product.
P, watch the state distribution π_t evolve one step at a time, and see how the particles redistribute. Try the "Sticky", "Mixing" and "Absorbing" presets to feel how the dynamics change.#Two Steps, Three Steps, k Steps
- Sunny → Sunny → Sunny: 0.8 × 0.8 = 0.64
- Sunny → Rainy → Sunny: 0.2 × 0.4 = 0.08
- Total: 0.72
P^2. The two-step transition matrix is P raised to the second power.P^2 = [[0.72, 0.28], [0.56, 0.44]]. So sunny → sunny in two steps has probability 0.72, matching our hand calculation. As k grows, something interesting happens to P^k: the rows start to look identical. Try it for k = 50:P50 = np.linalg.matrix_power(P, 50)
# [[0.667 0.333]
# [0.667 0.333]][0.667, 0.333]. The starting state has been forgotten. That repeated row is the stationary distribution.Why is the k-step table the matrix power? Open the derivation if you want to see where P^k comes from.
If P is a valid 3x3 transition matrix and you compute P^100, what structural property would you expect to see (assuming the chain is ergodic)?
#Stationary Distribution: The Long-Run Truth
π is a state distribution that is invariant under one step of the chain:π = π P says that π is a left eigenvector of P with eigenvalue 1. Solving for the stationary distribution is the same eigenvector problem you saw in the Eigenvalues & SVD lesson — there is no new linear algebra here, only a new application.P sums to 1, so a column of ones is an eigenvector with eigenvalue 1. The derivation below turns that into a left eigenvector that can be rescaled into probabilities.For the weather chain, working it out:
π = π Pgivesπ_S = 0.8 π_S + 0.4 π_Randπ_R = 0.2 π_S + 0.6 π_R- Both reduce to
π_S = 2 π_R - Combined with the normalisation
π_S + π_R = 1, we getπ_S = 2/3,π_R = 1/3
Over the long run, two-thirds of days are sunny, one-third rainy — regardless of where the chain started. That is the stationary distribution at work.
π_t oscillates instead of settling — the cyclic structure prevents convergence even though every state is visited equally often on average. Now try the "Random walk" preset and watch the same machinery quickly produce a uniform stationary distribution.P^t for several t and watches the rows align, then solves for the stationary distribution directly via eigendecomposition — the two answers must agree.#When Does π Exist? When Is It Unique?
π_t → π from any starting state:- Irreducibility: every state can reach every other state in finite time. There are no isolated islands.
- Aperiodicity: there is no fixed cycle length you are forced into. (Formally: the GCD of return times to any state is 1.)
π_t from any starting distribution. You do not need to memorise these conditions in detail — the takeaway is that "well-behaved" chains have a single long-run answer.π_t oscillates instead of converging, even though averages converge.P[s, s] is 1. A state is transient if the chain might leave it and never come back, and recurrent if the chain is certain to come back. In a chain with one absorbing state that every other state can reach, all the other states are transient, because the chain eventually falls into the absorbing state and stays.A 3-state chain has P[3, 3] = 1, so state 3 is absorbing. States 1 and 2 are not absorbing, and each of them can eventually reach state 3. What happens in the long run?
#Mixing Time (Briefly)
π_t converge to π? The answer is governed by the second-largest eigenvalue of P (in absolute value), often written |λ_2|. The gap 1 − |λ_2| is called the spectral gap, and convergence is exponentially fast at rate |λ_2|^t. A chain with a small spectral gap mixes slowly; a chain with a near-zero λ_2 snaps almost instantly to its stationary distribution. For the weather chain the eigenvalues of P are exactly 1 and 0.4, so |λ_2| = 0.4 and the gap is 0.6. The error should shrink like 0.4^t, and it does: after two steps the sunny-to-sunny entry is 0.72 against the limit 0.667, an error of 0.0533, which equals (1/3) × 0.4². After five steps the error is 0.0034.P = [[0.99, 0.01], [0.02, 0.98]]. Its stationary distribution is the same [2/3, 1/3], but its eigenvalues are 1 and 0.97. The error is (1/3) × 0.97^t: 0.286 after 5 steps and still 0.073 after 50, where the weather chain is down to about 1e-21. To shrink the error to 1% of its start, the weather chain needs about 5 steps and the sticky chain about 151.A second eigenvalue near 1 means the chain barely forgets where it began. That is why an MCMC sampler that takes tiny steps gives samples that are nearly copies of each other, and you need many more of them.
The two-state derivation above is a special case. The next derivation is optional on a first read: it proves the rate for any finite chain whose transition matrix can be diagonalized with real eigenvalues, which includes every reversible chain (one that satisfies detailed balance, defined in the first step). It also gives a bound on the total-variation distance, half the sum of the absolute differences between two distributions, which is the largest gap in probability that the two distributions can put on any set of states.
This single number controls how many MCMC samples you need, how quickly PageRank iterations converge, and how diffusion-model schedules trade off forward-process steps for sample quality.
#PageRank: The Web as a Markov Chain
Take four pages, A, B, C and D. A links to B and C. B links to C. C links to A and D. D links to nothing. The transition matrix, row by row (a row is "where do I go from this page"), starts like this:
| from \ to | A | B | C | D |
|---|---|---|---|---|
| A | 0 | 1/2 | 1/2 | 0 |
| B | 0 | 0 | 1 | 0 |
| C | 1/2 | 0 | 0 | 1/2 |
| D | ? | ? | ? | ? |
[1/4, 1/4, 1/4, 1/4].d = 0.85 the surfer follows a link, and with probability 1 − d = 0.15 the surfer teleports to a uniformly random page. Teleporting makes every page reachable from every other page, and it breaks any fixed cycle, so the chain is irreducible and aperiodic. That is exactly the ergodic condition from the last section, so the stationary distribution exists and is unique.i of P is where you go from state i, and the distribution updates as π P. PageRank code usually stores the transpose, M[j, i] = probability of going from page i to page j. Now each column of M sums to 1 (a column-stochastic matrix), and the update is π ← G π with the matrix on the left. It is the same chain written sideways: M is Pᵀ. Nothing changes except which way the table is read, but code that does it without saying so confuses everyone.The Google matrix below is just the two repairs written as one transition rule. The derivation shows that it is a true Markov chain.
M for these four pages, shows what goes wrong without the dangling-node repair, and then applies it.Run it and read it. Without the repair, the total probability collapses to about 2e-10, which means the "distribution" has drained away. With the repair, every column sums to 1 and the PageRank values are 0.234 for A, 0.187 for B, 0.345 for C and 0.234 for D, summing to 1, and the eigenvector gives the same four numbers. C ranks first because both A and B link to it. D ties with A: each of them receives half of C's clicks and a quarter of the jumps out of D. B ranks last: it receives only half of A's clicks and its quarter of the jumps out of D.
As a second run, here is PageRank from scratch on a bigger 5-page web with no dead ends. It is the same stationary-distribution computation, in about thirty lines, with the same column-stochastic convention.
#The Metropolis Sampler: A Chain Built to Hit a Target
p(x) that you can evaluate but cannot sample from directly, for example a Bayesian posterior known only up to a constant. The trick is to build a Markov chain whose stationary distribution is p. Run the chain for a long time, and the fraction of time it spends near each x is p(x). The visited states are your samples. The Bayesian Inference in Practice lesson pointed ahead to this tool, and this is where it gets built.P is the transition matrix, π the long-run row vector, and p the target density you want samples from. K is the kernel the sampler builds, q the proposal, and α the acceptance probability. The MDP lesson reuses P with an action, P(s' | s, a), and uses π for a policy.p as its stationary distribution? A sufficient condition is detailed balance. Write K(x → y) for the probability that the chain moves from x to y in one step. Detailed balance says that in equilibrium the flow each way is equal:K with this property using only ratios of p. From the current state x, propose a candidate x' from a symmetric proposal, meaning proposing x' from x is just as likely as proposing x from x'. Then accept the move with probabilityx to y is q times the smaller of p(x) and p(y), and that is the same number in both directions. The derivation gives every step.Move the four target sliders, switch between Metropolis and always-accept, and press Run chain. Under Metropolis the two flows on each link stay equal whatever target you set, and the chain's visit frequency follows p; with always-accept the flows go out of balance and the chain settles on the uniform distribution instead.
1, 2, 4, 3. They add to 10, so p = [0.1, 0.2, 0.4, 0.3]. The proposal picks one of the other three states uniformly, which is symmetric. Start at state 2. Instead of random numbers, use these fixed proposals and fixed uniform draws u between 0 and 1. The rule is: accept when u is below the acceptance probability.| step | current x | proposed x' | ratio p(x')/p(x) | accept prob | u | decision | next state |
|---|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4/2 = 2 | 1 | 0.30 | accept | 3 |
| 2 | 3 | 1 | 1/4 = 0.25 | 0.25 | 0.80 | reject | 3 |
| 3 | 3 | 4 | 3/4 = 0.75 | 0.75 | 0.45 | accept | 4 |
| 4 | 4 | 2 | 2/3 = 0.667 | 0.667 | 0.10 | accept | 2 |
| 5 | 2 | 4 | 3/2 = 1.5 | 1 | 0.50 | accept | 4 |
| 6 | 4 | 1 | 1/3 = 0.333 | 0.333 | 0.60 | reject | 4 |
u is. Step 2 proposes a state four times less probable, so it is accepted only if u is below 0.25, and 0.80 is not. A rejection is not wasted: the chain stays where it is, and that stay counts as a visit. Over thousands of steps, state 3 (the heaviest) is visited about 40% of the time.p as its stationary distribution. Its transition matrix K has, for each row, K(x → y) = (1/3) · min(1, p(y)/p(x)) off the diagonal, with the leftover probability on the diagonal:K = [[0.0, 0.3333, 0.3333, 0.3333],
[0.1667, 0.1667, 0.3333, 0.3333],
[0.0833, 0.1667, 0.5, 0.25 ],
[0.1111, 0.2222, 0.3333, 0.3333]]
# p @ K = [0.1, 0.2, 0.4, 0.3] = p
# detailed balance for states 1 and 2:
# p(1) K(1 -> 2) = 0.1 * 1/3 = 0.0333
# p(2) K(2 -> 1) = 0.2 * 1/6 = 0.0333The same recipe works in one dimension with a continuous target. The cell below samples a two-bump distribution: 60% of the mass is a bump centred at -2 with spread 0.7, and 40% is a bump centred at +2 with spread 1.0. The proposal adds Gaussian noise, which is symmetric. The code compares the draws with the exact answer.
Read the output. About 48.4% of proposals were accepted. The sampled mean is -0.383 against an exact -0.400, and the sampled variance is 4.609 against an exact 4.534. The histogram sits within about 0.011 of the exact probability in every bin, including the narrow gap between the bumps: the chain does cross it, because a downhill step is sometimes accepted.
step to see how the acceptance rate and the effective sample size move together.#Hidden Markov Models, Briefly
X_t (the "true" state) and observations Y_t that are generated from X_t via an emission distribution. You see the Y_ts but not the X_ts; algorithms like Viterbi and Baum-Welch reconstruct the most likely hidden sequence or fit the parameters by EM. HMMs were the dominant speech-recognition technology before deep learning, and they remain useful in bioinformatics.#Try It Yourself
You have met the stationary distribution three ways in prose: as the long-run share of time, as a left eigenvector, and as the limit of P^t. Here you check that they really agree on a fresh 3-state weather chain. Work through the TODOs in order; the solution is there when you want to compare.
Tests: Verify the three stationary estimates agree to about 3 decimals: simulated [0.456, 0.282, 0.262], eigenvector and P^100 both [0.457, 0.283, 0.261].
s in the simulation and run it again: the frequencies stay within the same noise of the same three numbers, because the chain forgets where it started.#Key Takeaways
- The Markov property says the present screens off the past. When a process looks non-Markovian, enrich the state instead of abandoning the framework
- A transition matrix has rows that are probability distributions over destinations, and its powers give multi-step probabilities. For the weather chain P^2 is [[0.72, 0.28], [0.56, 0.44]], and by P^50 both rows are [0.667, 0.333]
- The stationary distribution solves π = π P, a left eigenvector with eigenvalue 1. For the weather chain it is two-thirds sunny and one-third rainy, and ergodic chains (irreducible and aperiodic) have exactly one
- The second-largest eigenvalue sets the mixing speed: 0.4 for the weather chain, so the error shrinks like 0.4^t, and a chain with an eigenvalue near 1 mixes slowly
- PageRank is the stationary distribution of a random surfer on the link graph, once dead-end pages get a uniform jump and damping 0.85 is added: ranks 0.234, 0.187, 0.345 and 0.234 for the four-page web
- The Metropolis sampler builds a chain whose stationary distribution is a target you can only evaluate up to a constant: propose a symmetric move, accept with probability min(1, p(x') / p(x)), and remember that successive draws are correlated, so the effective sample size is smaller than the number of steps
#Quick Check
What does the Markov property say about a process?