Course contents 20 / 22

20 / 22 · Random Processes and Sampling

Markov chains

Random processes with a one-step memory: the Markov property and the transition matrix, how the distribution evolves and settles at a stationary distribution, convergence and the ergodic theorem, n-gram language models and PageRank as Markov chains, and hitting probabilities in the gambler's ruin.

On this page 6

Our sampling-based guarantees so far mostly assumed independent draws. Many random processes are not like that, and their dependence unfolds in time: tomorrow’s weather depends on today’s, the next word on the previous ones, the next page a reader visits on the current page, the next state of a sampler on the current state. A Markov chain is the simplest model of such dependence: the future depends on the past only through the present. It is simple enough to analyse completely and rich enough to describe n-gram language models, web search and the samplers of the last two notes of the course. With actions and rewards added, it becomes the Markov decision process of reinforcement learning.

Notation. X0,X1,X2,…X_0, X_1, X_2, \dots take values in a finite set of states {1,…,K}\{1, \dots, K\}. PP is the K×KK \times K transition matrix, Pij=P(Xt+1=j∣Xt=i)P_{ij} = P(X_{t+1} = j \mid X_t = i); each row sums to 1. A distribution over states is a row vector π\pi.

The Markov property#

A sequence is a Markov chain if

P(Xt+1=j∣Xt=i,Xt−1,…,X0)=P(Xt+1=j∣Xt=i)=Pij.P(X_{t+1} = j \mid X_t = i, X_{t-1}, \dots, X_0) = P(X_{t+1} = j \mid X_t = i) = P_{ij} .

The first equality is the Markov property: the present state contains everything about the past that matters for the future. The second is a separate assumption, time homogeneity: the transition rule PijP_{ij} is the same at every time tt. All chains in this note are time-homogeneous, and all are finite except one example with a density and the last subsection of the next section. The reverse process that generates samples in a diffusion model is Markov but not homogeneous, since its transition rule changes from step to step (MCMC note). A three-state weather model, with sunny days followed by sunny days 70% of the time, is a Markov chain with

P=(0.70.20.10.30.40.30.20.30.5)P = \begin{pmatrix} 0.7 & 0.2 & 0.1 \\ 0.3 & 0.4 & 0.3 \\ 0.2 & 0.3 & 0.5 \end{pmatrix}

(rows and columns: sunny, cloudy, rainy). By the law of total probability, the distribution of the next state is the current distribution times the matrix:

πt+1=πtP,πt=π0Pt.\pi_{t+1} = \pi_t P, \qquad \pi_t = \pi_0 P^t .

The entry (Pt)ij(P^t)_{ij} is the probability of being in jj after tt steps from ii. On a continuous state space the matrix becomes a transition density K(y∣x)K(y \mid x), the density of Xt+1X_{t+1} at yy given Xt=xX_t = x. If XtX_t has density ptp_t, the law of total probability, with an integral over xx in place of the sum over ii, gives

pt+1(y)=∫K(y∣x) pt(x) dx.p_{t+1}(y) = \int K(y \mid x)\, p_t(x)\, dx .

For example, Xt+1=aXt+1−a2 εtX_{t+1} = a X_t + \sqrt{1 - a^2}\, \varepsilon_t with εt∼N(0,1)\varepsilon_t \sim N(0, 1) independent of the past has K(y∣x)=N(y; ax, 1−a2)K(y \mid x) = N(y;\, a x,\, 1 - a^2). If Xt∼N(m,v)X_t \sim N(m, v), then Xt+1X_{t+1} is a sum of two independent normal variables, so it is normal with mean ama m and variance a2v+1−a2a^2 v + 1 - a^2. With a=0.7a = 0.7 and X0=3X_0 = 3 the first three steps give N(2.1,0.51)N(2.1, 0.51), N(1.47,0.76)N(1.47, 0.76) and N(1.029,0.882)N(1.029, 0.882).

Starting the weather chain from a sunny day:

Figure

A Markov chain for the weather

The transition graph and the distributions by dayThree circles with arrows both ways; a table of the distributions for days 0, 1, 2 and 10.0.20.30.10.20.30.3sunny0.7cloudy0.4rainy0.5sunnycloudyrainyday 01.000.000.001day 10.700.200.102day 20.570.250.183day 100.4570.2830.2614The transition graph and the distributions by dayThree circles with arrows both ways; a table of the distributions for days 0, 1, 2 and 10.0.20.30.10.20.30.3sunny0.7cloudy0.4rainy0.5sunnycloudyrainyday 01.000.000.001day 10.700.200.102day 20.570.250.183day 100.4570.2830.2614
Three weather states; an arrow from state i to j carries the transition probability Pᵢⱼ, and the probability of staying is inside the circle. If day 0 is sunny (1), the distribution of the next day is the "sunny" row of the matrix (2), that of day 2 is π₁P (3); by day 10 it barely depends on the start and equals the stationary distribution 21/46, 13/46, 12/46 (4).

Stationary distributions#

A distribution π\pi with

πP=π\pi P = \pi

is stationary: if the chain starts in it, it stays in it. It is a left eigenvector of PP with eigenvalue 1, normalized to sum to 1, and it can be found by solving the linear system πP=π\pi P = \pi, ∑iπi=1\sum_i \pi_i = 1. For the weather chain π=(21/46,13/46,12/46)=(0.457,0.283,0.261)\pi = (21/46, 13/46, 12/46) = (0.457, 0.283, 0.261): in the long run 46% of days are sunny.

With a transition density the same condition reads

π(y)=∫K(y∣x) π(x) dx.\pi(y) = \int K(y \mid x)\, \pi(x)\, dx .

For the normal chain above, N(m,v)N(m, v) maps to N(am,a2v+1−a2)N(a m, a^2 v + 1 - a^2). It is stationary when m=amm = a m and v=a2v+1−a2v = a^2 v + 1 - a^2, which for ∣a∣<1\lvert a \rvert < 1 means m=0m = 0 and v=1v = 1: the chain keeps N(0,1)N(0, 1).

Stationarity is a statement about the distribution of each XtX_t, not about their dependence. In the stationary normal chain every XtX_t is N(0,1)N(0, 1), yet Corr⁡(Xt,Xt+1)=a\operatorname{Corr}(X_t, X_{t+1}) = a. In the weather chain started from π\pi, a sunny day has probability 0.4570.457, but a sunny day after a sunny day has probability 0.70.7. Samples from a stationary chain are correlated, and the effective sample size measures what this costs.

The figure suggests more: from a sunny start the distribution approaches π\pi within ten days. That holds for every starting distribution under two conditions:

  • Irreducible: every state can be reached from every other.
  • Aperiodic: the chain does not cycle with a fixed period. A chain that alternates deterministically between two states has the stationary distribution (1/2,1/2)(1/2, 1/2) but never approaches it from a fixed start.

The period of a state ii is

d(i)=gcd⁡{ n≥1:(Pn)ii>0 },d(i) = \gcd\{\, n \ge 1 : (P^n)_{ii} > 0 \,\} ,

the greatest common divisor of the times at which a return to ii is possible. In an irreducible chain all states have the same period (Levin, Peres and Wilmer, Lemma 1.6), and the chain is aperiodic when that period is 1. The alternating chain returns only at times 2,4,6,…2, 4, 6, \dots, so its period is 2.

A single self-loop is enough. If Pii>0P_{ii} > 0, then 11 belongs to the set of return times, the gcd is 1, and by the lemma the whole irreducible chain is aperiodic. The weather chain has Pii>0P_{ii} > 0 on the whole diagonal. Positive entries everywhere are more than needed. The chain 1→2→3→11 \to 2 \to 3 \to 1 with an added self-loop P11=P12=1/2P_{11} = P_{12} = 1/2 has five zero entries, yet it is irreducible and aperiodic. Solving πP=π\pi P = \pi gives π2=π1/2\pi_2 = \pi_1 / 2, π3=π2\pi_3 = \pi_2 and π=(1/2,1/4,1/4)\pi = (1/2, 1/4, 1/4), and P4P^4 already has all entries positive. Every finite irreducible aperiodic chain has some power with all entries positive (Proposition 1.7 of the same book).

A finite irreducible chain has exactly one stationary distribution (Levin, Peres and Wilmer, Corollary 1.17). If it is also aperiodic, πt→π\pi_t \to \pi from any start, at a geometric rate (the convergence theorem, Theorem 4.9 there). The intuition is coupling: run a second copy of the chain from π\pi. Because some power of PP has all entries positive, the two copies meet with positive probability in every block of that many steps, so they eventually meet. After that they can move together, and the first copy is then distributed as π\pi.

The ergodic theorem, the law of large numbers for Markov chains, concerns a single long run. For every function ff on the states and every start,

1n∑t=0n−1f(Xt)→Eπf=∑if(i) πi\frac1n \sum_{t=0}^{n-1} f(X_t) \to E_\pi f = \sum_i f(i)\, \pi_i

with probability 1 (Theorem C.1 of the same book). With ff the indicator of a state, the share of time spent in that state converges to its stationary probability. On a finite space every ff has a finite mean; on infinite spaces the theorem needs Eπ∣f∣<∞E_\pi \lvert f \rvert < \infty. The intuition: the returns to a fixed state cut the path into excursions that, by the Markov property, are independent and identically distributed, and the ordinary law of large numbers applies to them.

The ergodic theorem needs only irreducibility. The alternating two-state chain started in state 1 visits 1,2,1,2,…1, 2, 1, 2, \dots, so the share of time in state 1 tends to 1/2=π11/2 = \pi_1, while P(Xt=1)P(X_t = 1) alternates between 1 and 0 and has no limit. Aperiodicity is needed for the distribution of XtX_t, not for time averages; MCMC estimates are time averages.

The speed of convergence of πt\pi_t is set by the second largest absolute eigenvalue of PP, as diagonalizing PP shows: the distance to π\pi shrinks roughly like ∣λ2∣t\lvert \lambda_2 \rvert^t, here 0.473t0.473^t, so ten steps reduce it by a factor of about 1,800. The number of steps needed to get close is the mixing time, the central quantity for the samplers of the MCMC note.

Beyond finite chains#

On a countably infinite state space irreducibility is defined as before, but it no longer guarantees a stationary distribution. Let τi+=min⁡{t≥1:Xt=i}\tau_i^+ = \min\{t \ge 1 : X_t = i\} be the return time to ii. A state is recurrent if the chain started there returns with probability 1, and positive recurrent if moreover the mean return time Eiτi+E_i \tau_i^+ is finite. An irreducible chain on a countable space has a stationary distribution if and only if it is positive recurrent (Levin, Peres and Wilmer, Theorem 21.13). The distribution is then unique, with

πi=1Eiτi+\pi_i = \frac{1}{E_i \tau_i^+}

(Lemma 21.12, Kac), and with aperiodicity P(Xt=j∣X0=i)→πjP(X_t = j \mid X_0 = i) \to \pi_j from every start (Theorem 21.16). The intuition is the excursion picture: the chain visits ii once per excursion, so the long-run share of time at ii is one over the mean excursion length. An infinite mean return time leaves every state a share of zero, and nothing remains to normalize.

The symmetric random walk on the integers, ±1\pm 1 with probability 1/21/2 each, is irreducible and returns to its start with probability 1 (Example 21.4), but it has no stationary distribution. A stationary π\pi would satisfy πi=12πi−1+12πi+1\pi_i = \frac12 \pi_{i-1} + \frac12 \pi_{i+1}, so πi+1−πi=πi−πi−1\pi_{i+1} - \pi_i = \pi_i - \pi_{i-1}: the differences are a constant cc and πi=π0+c i\pi_i = \pi_0 + c\, i. Nonnegativity for all i∈Zi \in \mathbb Z forces c=0c = 0, and a constant π\pi sums to 00 or to ∞\infty, never to 1. By the theorem the walk is not positive recurrent: its mean return time is infinite (Example 21.10).

On a continuous space a single point is usually reached with probability 0, so conditions are stated for sets. Following Roberts and Rosenthal (2004), Section 3.2:

  • φ-irreducible: there is a nonzero measure φ\varphi such that from every xx, every set AA with φ(A)>0\varphi(A) > 0 has Pn(x,A)>0P^n(x, A) > 0 for some nn. For MCMC, φ\varphi is typically the target or the volume on its support.
  • Aperiodic: there are no d≥2d \ge 2 disjoint sets X1,…,Xd\mathcal X_1, \dots, \mathcal X_d with π(X1)>0\pi(\mathcal X_1) > 0 that the chain visits in a fixed cycle, X1→X2→⋯→Xd→X1\mathcal X_1 \to \mathcal X_2 \to \dots \to \mathcal X_d \to \mathcal X_1, with probability 1.
  • Harris recurrent: from every xx, every set BB with π(B)>0\pi(B) > 0 is reached with probability 1.

If a chain on Rd\mathbb R^d is φ-irreducible and aperiodic and has a stationary distribution π\pi, then the distribution of XnX_n converges to π\pi in total variation from π\pi-almost every start (Theorem 4), and 1n∑th(Xt)→Eπh\frac1n \sum_t h(X_t) \to E_\pi h with probability 1 for every hh with Eπ∣h∣<∞E_\pi \lvert h \rvert < \infty (Fact 5). If the chain is also Harris recurrent, the convergence holds from every start (the discussion after Example 3). The intuition is the coupling argument again, with a set of states that share a common piece of their next-step distribution playing the part of a single state.

The exceptional starts are real. On the states 1,2,3,…1, 2, 3, \dots let state 1 be absorbing, and from x≥2x \ge 2 jump to 1 with probability 1/x21/x^2, otherwise to x+1x + 1 (Example 3 there). The stationary distribution is the point mass at 1, and the chain is irreducible in the sense above with φ\varphi that point mass. From x=2x = 2, the probability of never reaching 1 is a product. We factor 1−1/j2=(j−1)(j+1)/j21 - 1/j^2 = (j-1)(j+1)/j^2, and the products of (j−1)/j(j-1)/j and of (j+1)/j(j+1)/j telescope to 1/N1/N and (N+1)/2(N+1)/2:

∏j=2N(1−1j2)=∏j=2N(j−1)(j+1)j⋅j=12⋅N+1N→12.\begin{aligned} \prod_{j=2}^{N} \Big(1 - \frac{1}{j^2}\Big) &= \prod_{j=2}^{N} \frac{(j-1)(j+1)}{j \cdot j} \\ &= \frac{1}{2} \cdot \frac{N+1}{N} \to \frac12 . \end{aligned}

With probability 1/21/2 the chain runs off to infinity and never converges. Harris recurrence rules this out. A Metropolis–Hastings chain whose proposal density is positive and continuous, with a finite p~\tilde p, is irreducible in this sense, aperiodic, and converges from every start (Section 3.2 there), and the MCMC note shows how a proposal with gaps can break irreducibility.

Language models as Markov chains#

A bigram language model is a Markov chain whose states are words: PijP_{ij} is the probability that word jj follows word ii, estimated from counts. Generating text from it is running the chain. For a bigram chain fitted to one long text, the stationary distribution is approximately the unigram word frequency: each word is followed by a word, and preceded by one, as often as it occurs, except at the two ends of the text, so the unigram frequencies satisfy the stationarity equation up to these boundary terms. Text made of separate sentences needs an end-of-sentence token that leads back to a start state, or the chain stops. An n-gram model with n>2n > 2 is a Markov chain whose states are contexts of n−1n - 1 words; its stationary distribution is over contexts, and the unigram frequency is its marginal for a single position of the context. Shannon’s 1948 paper generated “English” this way, from letter and word chains of increasing order, and the n-gram language models note builds such models from data.

A transformer language model is a Markov chain too, but on a far larger state: the whole context window. The Markov property is a statement about what the state contains, and making the state richer is how sequence models acquire longer memory.

PageRank#

A reader who follows a random link from each page performs a random walk, a Markov chain on the pages. Pages that many walks visit often are important; their importance is the stationary distribution. Two fixes make the chain well defined, irreducible and aperiodic: with probability 0.150.15 the reader jumps to a random page instead of following a link (and always jumps from a page without links). The stationary distribution of that chain is PageRank, the ranking signal behind the early Google search engine:

Figure

PageRank is the stationary distribution of a random walk

The link graph of five pagesPage circles sized by PageRank; A and C are large, D and E small.A0.367B0.186C0.375D0.043E0.030The link graph of five pagesPage circles sized by PageRank; A and C are large, D and E small.A0.367B0.186C0.375D0.043E0.030
Five pages and the links between them. A random surfer follows a random link from the page with probability 0.85 and jumps to a random page with probability 0.15. The share of time a long walk spends on each page is its PageRank (circle area): A 0.367, B 0.186, C 0.375, D 0.043, E 0.030. Four pages link to C, yet A is nearly as important: C's only link goes to A and passes all of C's weight to it.

The example shows what distinguishes PageRank from counting links: a page is important if important pages link to it. C has the most incoming links, but A, with links from C and D, is almost as important, because C sends all its weight to A.

Hitting probabilities: the gambler’s ruin#

Some chains have absorbing states that are never left, and the question is which one is reached first. A gambler with 3 coins bets one coin at a time on a fair game and stops at 0 or at 10. Let hah_a be the probability of reaching 10 from aa; conditioning on the first bet gives ha=12ha+1+12ha−1h_a = \frac12 h_{a+1} + \frac12 h_{a-1} with h0=0h_0 = 0, h10=1h_{10} = 1, so ha=a/10h_a = a/10 and h3=0.3h_3 = 0.3. The expected number of bets is a(10−a)=21a(10 - a) = 21. A slightly unfavourable game, winning each bet with probability 0.490.49, lowers the chance to 0.2590.259; starting from 50 coins with a target of 100 it is only 0.1190.119, not one half: over a long game a small edge compounds. The same first-step equations give hitting times and absorption probabilities for any chain, from customer funnels to the expected length of a random walk.

What changed#

Independent samplesMarkov chains
Dependencenonethe next state depends on the current one: PijP_{ij}
Distribution over timeconstantπt=π0Pt\pi_t = \pi_0 P^t
Long runthe law of large numbersstationary π=πP\pi = \pi P; the ergodic theorem for time averages
Speed1/n1/\sqrt nalso the mixing time, set by ∣λ2∣\lvert \lambda_2 \rvert
Examplesn-gram models, PageRank, random walks, MCMC

Limitations#

  • The Markov property is a modelling choice. Real processes have longer memory; enlarging the state (the last nn words, the full context) restores the property at the cost of a much larger state space.
  • Convergence can be slow. Chains with bottlenecks, such as two clusters of states joined by rare transitions, can take a very long time to mix, and a single run may show no sign of it.
  • Finite states hide subtleties. Infinite or continuous state spaces need conditions (positive recurrence, φ-irreducibility, Harris recurrence) that the finite case gets for free; see beyond finite chains.

What you should remember#

  • Markov property: the future depends on the past only through the present; Pij=P(Xt+1=j∣Xt=i)P_{ij} = P(X_{t+1} = j \mid X_t = i).
  • Distributions evolve by πt+1=πtP\pi_{t+1} = \pi_t P; (Pt)ij(P^t)_{ij} is the tt-step transition probability.
  • Stationary: πP=π\pi P = \pi. For finite irreducible aperiodic chains, πt→π\pi_t \to \pi from any start; time averages converge to EπfE_\pi f under irreducibility alone.
  • The second largest eigenvalue in absolute value sets the speed: distance to π\pi ≈∣λ2∣t\approx \lvert \lambda_2 \rvert^t.
  • n-gram models and PageRank are Markov chains; PageRank is the stationary distribution of a random surfer with teleportation.
  • Absorption probabilities and hitting times solve first-step equations; in the fair gambler’s ruin with target NN, ha=a/Nh_a = a/N.

Code#

The weather chain, its stationary distribution and a long run, PageRank, and the gambler’s ruin:

import numpy as np

# the weather chain: distributions after 1, 2 and 10 days from a sunny start
P = np.array([[0.7, 0.2, 0.1], [0.3, 0.4, 0.3], [0.2, 0.3, 0.5]])
pi = np.array([1.0, 0.0, 0.0])
for t in range(11):
    if t in (1, 2, 10):
        print(t, pi.round(3))
    pi = pi @ P
# 1 [0.7 0.2 0.1] | 2 [0.57 0.25 0.18] | 10 [0.457 0.283 0.261]

# the stationary distribution solves pi P = pi with sum 1; the eigenvalues set the speed
A = np.vstack([P.T - np.eye(3), np.ones(3)])
stationary = np.linalg.lstsq(A, np.array([0, 0, 0, 1.0]), rcond=None)[0]
print(stationary.round(4), (np.array([21, 13, 12]) / 46).round(4))   # [0.4565 0.2826 0.2609] twice
print(np.sort(np.abs(np.linalg.eigvals(P))).round(3))                # [0.127 0.473 1.   ]

# the ergodic theorem: the share of days in each state along one long run
rng = np.random.default_rng(0)
x, counts = 0, np.zeros(3)
for _ in range(100_000):
    counts[x] += 1
    x = rng.choice(3, p=P[x])
print((counts / counts.sum()).round(3))                               # [0.459 0.281 0.259]

# PageRank of five pages by power iteration, damping 0.85
links = {0: [1, 2], 1: [2], 2: [0], 3: [0, 2], 4: [3, 2]}
M = np.zeros((5, 5))
for i, outs in links.items():
    M[i, outs] = 1 / len(outs)
G = 0.85 * M + 0.15 / 5
r = np.full(5, 0.2)
for _ in range(200):
    r = r @ G
print(r.round(3))                                                     # [0.367 0.186 0.375 0.043 0.03 ]

# gambler's ruin: the probability of reaching N before 0 from a, winning each bet with probability p
ruin = lambda p, a, N: a / N if p == 0.5 else (1 - ((1 - p) / p) ** a) / (1 - ((1 - p) / p) ** N)
print(ruin(0.5, 3, 10), round(ruin(0.49, 3, 10), 3), round(ruin(0.49, 50, 100), 3))   # 0.3 0.259 0.119

Next#

The ergodic theorem says that a long run of a chain samples its stationary distribution. Turned around, this is a way to sample from a distribution that cannot be sampled directly: build a chain whose stationary distribution is the target. Before that idea, the next note collects the direct methods of Monte Carlo: inverse transforms, rejection sampling and importance sampling, and the variance that decides whether they work.

References#

  • J. R. Norris. Markov Chains. Cambridge University Press, 1997. Chapter 1 (discrete-time chains, hitting probabilities, stationary distributions, convergence, the ergodic theorem).
  • D. A. Levin, Y. Peres, E. L. Wilmer. Markov Chains and Mixing Times, 2nd ed. American Mathematical Society, 2017. Chapters 1, 4 and 12 (stationary distributions, mixing, the spectral gap): Lemma 1.6 and Proposition 1.7 (period), Corollary 1.17 (uniqueness), Theorem 4.9 (convergence); Chapter 21 (countable chains): Lemma 21.12, Theorems 21.13 and 21.16, Examples 21.4 and 21.10; Appendix C, Theorem C.1 (ergodic theorem).
  • G. O. Roberts, J. S. Rosenthal. General State Space Markov Chains and MCMC Algorithms. Probability Surveys, 1, 2004. Section 3.2: φ-irreducibility, aperiodicity, Harris recurrence, Theorem 4, Fact 5, Example 3, the Metropolis–Hastings running example.
  • C. E. Shannon. A Mathematical Theory of Communication. Bell System Technical Journal, 27(3), 1948. Markov approximations to English.
  • S. Brin, L. Page. The Anatomy of a Large-Scale Hypertextual Web Search Engine. Computer Networks and ISDN Systems, 30, 1998.