TExcelTAD
Home › Probability Theory › Markov Chains

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 s1,…,srs_1, \ldots, s_r and a transition matrix PP with pijp_{ij} = the probability of moving from state ii to state jj in one step. Each row of PP sums to 1. The Markov property says that the next state depends only on the current state, not on the earlier history:

Pr⁡[Xn+1=j∣Xn=i,Xn−1,…,X0]=pij\Pr[X_{n+1} = j \mid X_n = i, X_{n-1}, \ldots, X_0] = p_{ij}

Example: a city's weather is sunny, cloudy or rainy.

P=(0.60.30.10.30.40.30.20.30.5)(rows and columns: sun, cloud, rain)P = \begin{pmatrix} 0.6 & 0.3 & 0.1 \\ 0.3 & 0.4 & 0.3 \\ 0.2 & 0.3 & 0.5 \end{pmatrix} \qquad \text{(rows and columns: sun, cloud, rain)}

Multi-step transitions

The probability of going from ii to jj in nn steps is the (i,j)(i, j) entry of the matrix power PnP^n. For two steps, sum over the intermediate state: pij(2)=∑kpikpkjp^{(2)}_{ij} = \sum_k p_{ik}p_{kj}, which is exactly matrix multiplication. If the initial state has distribution u\mathbf{u} (a row vector), the distribution after nn steps is uPn\mathbf{u}P^n.

python · try it yourself
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 w\mathbf{w} with wP=w\mathbf{w}P = \mathbf{w}. This is a left eigenvector of PP with eigenvalue 1 (Eigenvectors), studied in Ergodic Chains.

Simulating a chain

To simulate, draw the next state from the row of the current state:

python · try it yourself
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 uPn\mathbf{u}P^n, a law of large numbers for Markov chains.

Classifying states

  • A state is absorbing if you can never leave it (pii=1p_{ii} = 1). 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 PnP^n has all entries positive; then uPn→w\mathbf{u}P^n \to \mathbf{w} 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

0.06+0.09+0.05=0.20.06 + 0.09 + 0.05 = 0.2.

Solution

psun,rain(2)=0.6⋅0.1+0.3⋅0.3+0.1⋅0.5=0.2p^{(2)}_{\text{sun,rain}} = 0.6 \cdot 0.1 + 0.3 \cdot 0.3 + 0.1 \cdot 0.5 = 0.2.

Exercise 2: Regular or not

Is the chain with P=(0110)P = \begin{pmatrix} 0 & 1 \\ 1 & 0 \end{pmatrix} regular? Does uPn\mathbf{u}P^n converge?

Answer

Not regular; uPn\mathbf{u}P^n oscillates unless u=(1/2,1/2)\mathbf{u} = (1/2, 1/2).

Solution

PnP^n alternates between PP and the identity, so no power is all positive. The chain is ergodic with stationary distribution (1/2,1/2)(1/2, 1/2), 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
python · try it yourself
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 ii to state jj in nn steps is…

  1. pijnp_{ij}^n
  2. the (i,j)(i, j) entry of PnP^n
  3. npijn p_{ij}
  4. pij/np_{ij}/n

Each row of a transition matrix…

  1. sums to 1
  2. sums to 0
  3. is a stationary distribution
  4. has one nonzero entry