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 with values in a finite set of states is a Markov chain if the future depends on the past only through the present:
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 is the same at every . All chains in this topic are homogeneous.
The numbers form the transition matrix . Row is the distribution of the next state given the current state , so every entry is nonnegative and every row sums to . (Here is a matrix; is still a probability, and the brackets tell them apart.)
A three-state weather model, with rows and columns ordered sunny, cloudy, rainy:
After a sunny day comes another sunny day with probability . 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:
For example, from a sunny day the path sunny, sunny, cloudy has probability .
How the distribution moves
Where will the chain be in steps? Write the distribution of as a row vector with entries . The law of total probability, split over the current state, gives
This is a row vector times a matrix: , and is multiplied by itself times (Mathematics for ML covers matrices in depth). So one step of the chain is one multiplication, and steps are a matrix power:
The entry is the probability of being in state after steps from state .
Start the weather chain on a sunny day, . Then is simply the first row of , 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 agree to two decimals: from a cloudy or a rainy start the forecast for day 10 is also about . 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 is stationary if one step of the chain does not change it:
If the chain starts in , it stays in forever. In the language of linear algebra, is a left eigenvector of with eigenvalue , 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
the vector the table of the previous block was approaching. Check the first entry: . In the long run, 46% of days are sunny.
Stationarity is a statement about each on its own, not about how they depend on each other. Start the weather chain from . Every day is sunny with probability . Yet a sunny day after a sunny day has probability , not : neighbouring days stay strongly dependent. A long run of a stationary chain is therefore not an i.i.d. sample from . The topic Markov chain Monte Carlo measures what this dependence costs.
When a chain forgets its start
The weather chain reached 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, , have the stationary distribution . But from state 1 the probability goes and has no limit. The period of a state is the greatest common divisor of the times at which a return to is possible:
The swapping chain returns only at times , so its period is . In an irreducible chain all states have the same period, and the chain is aperiodic when it equals .
The convergence theorem says these are the only obstacles on a finite state space. A finite irreducible chain has exactly one stationary distribution . If it is also aperiodic, then from every starting distribution, and the distance shrinks geometrically fast.
A useful shortcut: in an irreducible chain, a single state with makes the whole chain aperiodic, since a return in one step puts into the set and the gcd becomes . 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 with probability 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 . 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 of the state and every start,
with probability . With 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 , so the share of time in state 1 tends to , even though 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 approach ? The eigenvalues of answer that. The largest is always , and the distance to shrinks roughly like , where is the second largest eigenvalue in absolute value. For the weather chain the eigenvalues are , and , so ten steps cut the distance by about . The number of steps needed to get close to is the mixing time.
A chain can mix very slowly. Two clusters of states joined by rare transitions give close to . 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. is the share of occurrences of word that are followed by word 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 is also a chain, but its states are contexts of the last 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 the reader jumps to a uniformly random page instead of following a link, and always jumps from a page with no links. With pages and the link-following matrix , the chain is
where is the matrix of ones (rows of dead ends in are first replaced by the uniform row ).
Every entry of is positive, so the chain is irreducible and aperiodic, is unique, and repeated multiplication 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 , almost that of C at , and B gets . 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 be the probability of reaching 10 from coins. Condition on the first bet (law of total probability again):
The equation says that each is the average of its neighbours, so is a straight line: and . The same method gives the expected number of bets, .
A slightly unfair game changes a lot. If each bet is won with probability , the chance falls from to . Starting with 50 coins and aiming for 100, it is 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.
Answers are saved on the server and tied to this browser until you sign in.