Markov Chains
So far, most random sequences in this course were independent. Many real processes have memory, but only a short one: tomorrow's weather depends on today's, the next word depends on the current one, a web surfer's next page depends on the page they are on. A Markov chain is the simplest model of such dependence.
Definition
A Markov chain has a set of states and a transition matrix with = the probability of moving from state to state in one step. Each row of sums to 1. The Markov property says that the next state depends only on the current state, not on the earlier history:
Example: a city's weather is sunny, cloudy or rainy.
Multi-step transitions
The probability of going from to in steps is the entry of the matrix power . For two steps, sum over the intermediate state: , which is exactly matrix multiplication. If the initial state has distribution (a row vector), the distribution after steps is .
import numpy as np
P = np.array([[0.6, 0.3, 0.1],
[0.3, 0.4, 0.3],
[0.2, 0.3, 0.5]])
states = ["sun", "cloud", "rain"]
print("P^2 =\n", np.round(np.linalg.matrix_power(P, 2), 3))
u = np.array([1.0, 0.0, 0.0]) # sunny today
for n in [1, 2, 3, 5, 10, 20]:
print(f"after {n:2d} days:", dict(zip(states, np.round(u @ np.linalg.matrix_power(P, n), 4).tolist())))P^2 =
[[0.47 0.33 0.2 ]
[0.36 0.34 0.3 ]
[0.31 0.33 0.36]]
after 1 days: {'sun': 0.6, 'cloud': 0.3, 'rain': 0.1}
after 2 days: {'sun': 0.47, 'cloud': 0.33, 'rain': 0.2}
after 3 days: {'sun': 0.421, 'cloud': 0.333, 'rain': 0.246}
after 5 days: {'sun': 0.394, 'cloud': 0.3333, 'rain': 0.2727}
after 10 days: {'sun': 0.3889, 'cloud': 0.3333, 'rain': 0.2777}
after 20 days: {'sun': 0.3889, 'cloud': 0.3333, 'rain': 0.2778}
After a couple of weeks, the forecast no longer depends on today: the distribution has converged to a stationary distribution with . This is a left eigenvector of with eigenvalue 1 (Eigenvectors), studied in Ergodic Chains.
Simulating a chain
To simulate, draw the next state from the row of the current state:
import random
from collections import Counter
P = {"sun": {"sun": 0.6, "cloud": 0.3, "rain": 0.1},
"cloud": {"sun": 0.3, "cloud": 0.4, "rain": 0.3},
"rain": {"sun": 0.2, "cloud": 0.3, "rain": 0.5}}
rng = random.Random(1)
state, path = "sun", []
for _ in range(100_000):
nxt = P[state]
state = rng.choices(list(nxt), weights=list(nxt.values()))[0]
path.append(state)
print("first 12 days:", " ".join(s[0].upper() for s in path[:12]))
c = Counter(path)
print("long-run fractions:", {s: round(c[s] / len(path), 4) for s in ["sun", "cloud", "rain"]})first 12 days: S C R C C C C R S S C C
long-run fractions: {'sun': 0.3888, 'cloud': 0.3327, 'rain': 0.2785}
The long-run fraction of time in each state matches the limit of , a law of large numbers for Markov chains.
Classifying states
- A state is absorbing if you can never leave it (). Chains where every state can reach an absorbing state are absorbing chains: games that end, processes that terminate.
- A chain is ergodic (irreducible) if every state can reach every other. It then has a unique stationary distribution.
- An ergodic chain is regular if some power has all entries positive; then from every start. A chain that alternates deterministically between two states is ergodic but not regular (it is periodic).
In software
Markov chains model user navigation (PageRank is the stationary distribution of a random surfer, see PageRank), text generation (n-gram models are Markov chains on words), queue lengths, cache states, and genome sequences. Markov chain Monte Carlo (MCMC) builds chains whose stationary distribution is a target distribution, and samples it by running the chain.
Exercises
Exercise 1: Two steps by hand
For the weather chain, what is the probability that it is rainy two days after a sunny day?
Answer
.
Solution
.
Exercise 2: Regular or not
Is the chain with regular? Does converge?
Answer
Not regular; oscillates unless .
Solution
alternates between and the identity, so no power is all positive. The chain is ergodic with stationary distribution , but from a fixed start it alternates forever.
Exercise 3: A text chain (code)
Build a word-level Markov chain from a short text: for each word, count which words follow it. Generate 12 words starting from "the".
Answer
The output is a sequence where every adjacent pair of words appeared somewhere in the text.
Solution
import random
from collections import defaultdict
text = ("the cat sat on the mat and the dog sat on the log and the cat saw the dog "
"and the dog saw the cat on the mat")
words = text.split()
follow = defaultdict(list)
for a, b in zip(words, words[1:]):
follow[a].append(b)
rng = random.Random(3)
w, out = "the", ["the"]
for _ in range(11):
w = rng.choice(follow[w])
out.append(w)
print(" ".join(out))
print("after 'the':", sorted(set(follow["the"])))the log and the cat on the mat and the cat on
after 'the': ['cat', 'dog', 'log', 'mat']
Choosing uniformly from the list of followers weights each successor by how often it followed the word: the empirical transition probabilities. Language models do the same with far longer contexts (Sampling from Language Models).
Test yourself
The probability of going from state to state in steps is…
- the entry of
Each row of a transition matrix…
- sums to 1
- sums to 0
- is a stationary distribution
- has one nonzero entry