Skip to content
BIASED

Markov chains

Dependence through time: the Markov property and the transition matrix, distributions as matrix powers, the stationary distribution, irreducibility, aperiodicity and convergence, the ergodic theorem, n-gram text, PageRank and the gambler's ruin.

A one-step memory

The topic Hypothesis tests and A/B testing closed the statistics part of the course, and every result in it rested on one assumption: the observations are independent. Users in an A/B test, examples in a test set, tosses of a coin — each new draw knew nothing about the previous ones. That is what made the law of large numbers and the CLT work. Many random processes are not like that. Tomorrow's weather depends on today's, the next word of a sentence on the words before it, the next page a reader opens on the page they are reading. This topic studies the simplest model of such dependence through time.

A sequence X0,X1,X2,…X_0, X_1, X_2, \dots with values in a finite set of states {1,…,K}\{1, \dots, K\} is a Markov chain if the future depends on the past only through the present:

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 current state holds everything about the past that matters for the next step. The second is a separate assumption, time homogeneity: the rule PijP_{ij} is the same at every tt. All chains in this topic are homogeneous.

The numbers PijP_{ij} form the K×KK \times K transition matrix PP. Row ii is the distribution of the next state given the current state ii, so every entry is nonnegative and every row sums to 11. (Here PP is a matrix; P(⋅)P(\cdot) is still a probability, and the brackets tell them apart.)

A three-state weather model, with rows and columns ordered sunny, cloudy, rainy:

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}.

After a sunny day comes another sunny day with probability 0.70.7. The multiplication rule from the topic Conditional probability and Bayes' formula, together with the Markov property, gives the probability of a whole path as a product of one-step factors:

P(X0=i0,X1=i1,…,Xt=it)=P(X0=i0) Pi0i1Pi1i2⋯Pit−1it.P(X_0 = i_0, X_1 = i_1, \dots, X_t = i_t) = P(X_0 = i_0)\, P_{i_0 i_1} P_{i_1 i_2} \cdots P_{i_{t-1} i_t}.

For example, from a sunny day the path sunny, sunny, cloudy has probability 0.7⋅0.2=0.140.7 \cdot 0.2 = 0.14.

How the distribution moves

Where will the chain be in tt steps? Write the distribution of XtX_t as a row vector πt\pi_t with entries πt(i)=P(Xt=i)\pi_t(i) = P(X_t = i). The law of total probability, split over the current state, gives

P(Xt+1=j)=∑iP(Xt=i) Pij.P(X_{t+1} = j) = \sum_i P(X_t = i)\, P_{ij}.

This is a row vector times a matrix: (πP)j=∑iπiPij(\pi P)_j = \sum_i \pi_i P_{ij}, and PtP^t is PP multiplied by itself tt times (Mathematics for ML covers matrices in depth). So one step of the chain is one multiplication, and tt steps are a matrix power:

π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 state jj after tt steps from state ii.

Start the weather chain on a sunny day, π0=(1,0,0)\pi_0 = (1, 0, 0). Then π1\pi_1 is simply the first row of PP, and each further day is one more multiplication:

day sunny cloudy rainy
0 1 0 0
1 0.70 0.20 0.10
3 0.510 0.268 0.222
10 0.457 0.283 0.261

Something interesting happens by day 10. All three rows of P10P^{10} agree to two decimals: from a cloudy or a rainy start the forecast for day 10 is also about (0.457,0.283,0.261)(0.457, 0.283, 0.261). The chain has forgotten where it started. The next block names the distribution it settles into.

On a continuous state space the same picture holds with a transition density in place of the matrix and an integral in place of the sum. The samplers of the topic Markov chain Monte Carlo work that way.

The stationary distribution

A distribution π\pi is stationary if one step of the chain does not change it:

πP=π,∑iπi=1.\pi P = \pi, \qquad \sum_i \pi_i = 1.

If the chain starts in π\pi, it stays in π\pi forever. In the language of linear algebra, π\pi is a left eigenvector of PP with eigenvalue 11, scaled to sum to one (see the topic Determinants and eigenvalues in Mathematics for ML). In practice we solve the linear system above.

For the weather chain the solution is

π=(2146,1346,1246)≈(0.457,0.283,0.261),\pi = \Big(\frac{21}{46}, \frac{13}{46}, \frac{12}{46}\Big) \approx (0.457, 0.283, 0.261),

the vector the table of the previous block was approaching. Check the first entry: (21⋅0.7+13⋅0.3+12⋅0.2)/46=21/46(21 \cdot 0.7 + 13 \cdot 0.3 + 12 \cdot 0.2)/46 = 21/46. In the long run, 46% of days are sunny.

Stationarity is a statement about each XtX_t on its own, not about how they depend on each other. Start the weather chain from π\pi. Every day is sunny with probability 0.4570.457. Yet a sunny day after a sunny day has probability 0.70.7, not 0.4570.457: neighbouring days stay strongly dependent. A long run of a stationary chain is therefore not an i.i.d. sample from π\pi. The topic Markov chain Monte Carlo measures what this dependence costs.

When a chain forgets its start

The weather chain reached π\pi from every start. That does not happen in every chain. There are two ways to fail.

The chain is cut into pieces. Suppose the states form two groups with no transitions between them. A chain started in one group never sees the other. Each group has its own stationary distribution, any mixture of the two is stationary too, and the limit depends on the start. A chain is irreducible if every state can be reached from every other in some number of steps.

The chain cycles. Two states that swap deterministically, P=(0110)P = \begin{pmatrix} 0 & 1 \\ 1 & 0 \end{pmatrix}, have the stationary distribution (1/2,1/2)(1/2, 1/2). But from state 1 the probability P(Xt=1)P(X_t = 1) goes 1,0,1,0,…1, 0, 1, 0, \dots and has no limit. The period of a state ii is the greatest common divisor of the times at which a return to ii is possible:

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

The swapping chain returns only at times 2,4,6,…2, 4, 6, \dots, so its period is 22. In an irreducible chain all states have the same period, and the chain is aperiodic when it equals 11.

The convergence theorem says these are the only obstacles on a finite state space. A finite irreducible chain has exactly one stationary distribution π\pi. If it is also aperiodic, then πt→π\pi_t \to \pi from every starting distribution, and the distance shrinks geometrically fast.

A useful shortcut: in an irreducible chain, a single state with Pii>0P_{ii} > 0 makes the whole chain aperiodic, since a return in one step puts 11 into the set and the gcd becomes 11. The weather chain has positive entries everywhere, which is more than needed.

Infinite state spaces need more care. The symmetric random walk on the integers, a step of ±1\pm 1 with probability 1/21/2 each, is irreducible, yet it has no stationary distribution at all: the walk spreads out forever and never settles.

The ergodic theorem and the speed

The convergence theorem is about the distribution of a single XtX_t. In practice we usually have one long run of the chain and average along it. The ergodic theorem is the law of large numbers for that case. For a finite irreducible chain, every function ff of the state and every start,

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

with probability 11. With ff the indicator of a state, the share of time the chain spends there converges to its stationary probability. A long weather simulation has about 46% sunny days.

The ergodic theorem needs only irreducibility. The swapping 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, even though P(Xt=1)P(X_t = 1) never settles. The intuition: returns to a fixed state cut the path into excursions, and by the Markov property these excursions are independent and identically distributed. The ordinary law of large numbers applies to them.

How fast does πt\pi_t approach π\pi? The eigenvalues of PP answer that. The largest is always 11, and the distance to π\pi shrinks roughly like ∣λ2∣t\lvert \lambda_2 \rvert^t, where λ2\lambda_2 is the second largest eigenvalue in absolute value. For the weather chain the eigenvalues are 11, 0.4730.473 and 0.1270.127, so ten steps cut the distance by about 0.473−10≈18000.473^{-10} \approx 1800. The number of steps needed to get close to π\pi is the mixing time.

A chain can mix very slowly. Two clusters of states joined by rare transitions give ∣λ2∣\lvert \lambda_2 \rvert close to 11. The chain then spends a long time in one cluster, and a single run may show no sign that the other one exists.

Text and PageRank

Two famous models are Markov chains.

n-gram text. A bigram language model is a chain whose states are words. PijP_{ij} is the share of occurrences of word ii that are followed by word jj in a corpus, and generating text means running the chain. For a bigram chain fitted to one long text, the stationary distribution is approximately the plain word frequency: each word is followed by a word as often as it occurs. Shannon generated "English" this way in 1948. An n-gram model with n>2n > 2 is also a chain, but its states are contexts of the last n−1n - 1 words. A transformer with a context window is a chain too, on an enormous state: the whole window. The Markov property is a statement about what the state contains, and a richer state is how a sequence model gets a longer memory.

PageRank. A reader who follows a random link from each page performs a random walk on the web, a Markov chain on pages. Pages that the walk visits often are important, so their importance is the stationary distribution. Two things can break it. A page with no outgoing links has a zero row, so the link-following matrix is not even a transition matrix. A group of pages that link only to each other traps the walk, so the chain need not be irreducible. Teleportation fixes both: with probability 0.150.15 the reader jumps to a uniformly random page instead of following a link, and always jumps from a page with no links. With NN pages and the link-following matrix MM, the chain is

G=0.85 M+0.15N 11⊤,G = 0.85\, M + \frac{0.15}{N}\, \mathbf 1 \mathbf 1^{\top},

where 11⊤\mathbf 1 \mathbf 1^{\top} is the N×NN \times N matrix of ones (rows of dead ends in MM are first replaced by the uniform row 1/N1/N).

Every entry of GG is positive, so the chain is irreducible and aperiodic, π\pi is unique, and repeated multiplication r←rGr \leftarrow r G from any start converges to it. This power iteration is how PageRank was computed for the early Google.

Five pages: A links to B and C; B to C; C to A; D to A and C; E to D and C. Page C has four incoming links, A only two. Yet the PageRank of A is 0.3670.367, almost that of C at 0.3750.375, and B gets 0.1860.186. C sends its whole weight along its only link, to A. A page is important when important pages link to it, not when many pages do.

Hitting probabilities

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 coins. Condition on the first bet (law of total probability again):

ha=12ha+1+12ha−1,h0=0,h10=1.h_a = \tfrac12 h_{a+1} + \tfrac12 h_{a-1}, \qquad h_0 = 0, \quad h_{10} = 1.

The equation says that each hah_a is the average of its neighbours, so hh is a straight line: ha=a/10h_a = a/10 and h3=0.3h_3 = 0.3. The same method gives the expected number of bets, a(10−a)=21a(10 - a) = 21.

A slightly unfair game changes a lot. If each bet is won with probability 0.490.49, the chance falls from 0.30.3 to 0.2590.259. Starting with 50 coins and aiming for 100, it is 0.1190.119 rather than one half: over a long game, a small edge compounds. These first-step equations work for any chain: write one equation per state by conditioning on the first move, set the boundary values, solve the linear system. A customer funnel with absorbing "bought" and "left" states is solved exactly the same way.

The topic has turned dependence through time into linear algebra: a matrix moves distributions, its stationary vector describes the long run, and the ergodic theorem says that one long run samples that vector. Read backwards, this last fact is a way to sample from a distribution we cannot sample directly: build a chain whose stationary distribution is the target, run it, and average. That is Markov chain Monte Carlo, the last topic of the course. First we need the plain version of the idea: estimating an expectation we cannot integrate by averaging random draws. The next topic, Monte Carlo methods, does that with independent samples and measures its error with the CLT.

Check your understanding

The same questions as in Pulse. Answers are shared between modes.

Full notes

Answers are saved on the server and tied to this browser until you sign in.