Overview
Picture a token on a board of states. At each tick it moves according to probabilities that depend only on where it is now, not on how it got there. Those probabilities fill a matrix with one row per current state, and each row sums to 1. Multiplying a distribution over states by the matrix advances it one step, so powers of the matrix tell you about the far future. For most chains the distribution stops changing after many steps and settles on a stationary distribution: the long-run share of time spent in each state. Some chains have absorbing states that are never left, and then the questions become where the token ends up and how long that takes.
A short history
Andrey Markov introduced chains of dependent events in 1906 to show that the law of large numbers does not require independence. In 1913 he applied the idea to the sequence of vowels and consonants in Pushkin's Eugene Onegin. The model spread into physics, queueing and genetics, and later became the base of hidden Markov models for speech, of PageRank, and of Markov chain Monte Carlo sampling.
How it works
- List the states and fill the transition matrix , where entry is the probability of moving from state to state . Every row must sum to 1.
- Describe the start as a row vector of probabilities over states, and multiply it by once for each step.
- Find the stationary distribution: the row vector that leaves unchanged. The template takes the left eigenvector for eigenvalue 1, or iterates until nothing moves.
- Check that the chain is irreducible (every state can reach every other) so that the stationary distribution is unique, and find its period.
- If there are absorbing states, split the matrix into transient and absorbing parts and use the fundamental matrix to get absorption probabilities and expected times.
- Simulate a path by drawing each next state from the row of the current one, or estimate from an observed path by counting transitions.
Watch out for
- The memoryless assumption is strong. If the next step depends on the last two states, a chain on single states is the wrong model, though one on pairs of states can work.
- A reducible chain has more than one stationary distribution. The eigen method then returns just one of them, and it may not be the one your start leads to.
- A periodic chain never settles: its distribution cycles for ever. A stationary distribution still exists and still gives the long-run share of time in each state.
- Convergence can be very slow when the second largest eigenvalue is close to 1 in size. A short simulation then reflects the start, not the long run.
- A matrix estimated from a short path gives probability zero to transitions that happened not to occur. The smoothing argument avoids that.
Use cases
When to use it
Modelling systems that hop between discrete states, such as user sessions, weather or board games, and as the foundation of PageRank, hidden Markov models and Markov chain Monte Carlo.
In industry
- Web search
- Google's PageRank scores a page by the stationary distribution of a random surfer who follows links, which is a Markov chain over web pages.
- Speech recognition
- Hidden Markov models, which put a Markov chain over unobserved sound states, were the standard acoustic models for decades.
- Credit risk
- Rating agencies publish transition matrices giving the chance that a borrower moves from one credit rating to another within a year.
- Operations
- Call centres and networks model queue lengths as Markov chains to size staff and capacity.
Choosing it: what must hold
- A finite set of states that describes the system at each step.
- The Markov property: the next state depends on the current state only, not on the path that led there.
- Transition probabilities that stay the same over time, and enough observed transitions to estimate each row.
When to choose something else
| If | Use instead |
|---|---|
| The next step depends on several past steps | A higher-order chain, or a sequence model such as an LSTM or GRU |
| The true state is not observed directly | A hidden Markov model |
| The state is continuous, not a finite set | Stochastic processes, such as random walks and Brownian motion |
| An agent chooses actions that change the transitions | A Markov decision process, as in the reinforcement learning lessons |
Math foundations
The Markov property
The future depends on the past only through the present state. The numbers form the transition matrix, and each row is a probability distribution.
Many steps
With a row vector of starting probabilities, one multiplication by advances one step. Entry of is the probability of being in after steps from .
Stationary distribution
A distribution that one step leaves unchanged. It is a left eigenvector of with eigenvalue 1. For an irreducible chain it is unique and equals the long-run fraction of time spent in each state.
Absorbing chains
Order the states with transient ones first. holds moves among transient states and moves into absorbing ones. Entry of the fundamental matrix is the expected number of visits to transient state when starting from .
Where and when absorption happens
is the probability of ending in absorbing state from transient state . The vector holds the expected number of steps before absorption, the row sums of .
Mean first passage time
The expected number of steps to first reach a target state. Take one step, then continue from wherever you land. This is a linear system, which the template solves directly.
Estimating the matrix
The maximum likelihood estimate from an observed path: the share of departures from state that went to state .
Symbols
- the state at step
- the transition matrix; is the probability of moving from to
- the row vector of state probabilities at step
- the stationary distribution
- the block of transitions among transient states
- the block of transitions from transient to absorbing states
- the identity matrix
- the fundamental matrix
- the matrix of absorption probabilities
- the expected steps to absorption from each transient state
- a column vector of ones
- the expected number of steps from state to the target
- the number of observed moves from to
Worked by hand
A two-state weather chain: from sunny (state 0) it stays sunny with probability 0.9, and from rainy (state 1) it turns sunny with probability 0.5. So the rows of are and . Start on a sunny day.
In the long run five days in six are sunny, whatever the first day was. The third line balances the flow from sunny to rainy against the flow back, which is the stationary condition for two states.
Visual example
Loading the example.
Try this
- Click Rainy to start there and press Run. The bars end where they did from Sunny.
- Raise both stay sliders to 0.95 and step again: the chain forgets its start much more slowly.
- Set sunny stays sunny to 1. Sunny becomes absorbing and every start ends there.
Code sample
import numpy as np
from impl import MarkovChain, estimate_transition_matrix
chain = MarkovChain([[0.9, 0.1],
[0.5, 0.5]])
chain.stationary_distribution() # [0.8333, 0.1667]
chain.n_step_matrix(3) # three-step transition probabilities
path = chain.simulate(10000, start=0) # (10001,) integer states
estimate_transition_matrix(path) # close to the matrix aboveRead the implementation (137 lines)
"""Discrete-time Markov chains on a finite state space.
A chain is its transition matrix P, with P[i, j] the probability of moving from state i to state j. This module
computes n-step distributions, the stationary distribution, irreducibility and period, absorption probabilities
and expected times, mean first passage times, simulates paths, and estimates P from an observed path.
"""
from __future__ import annotations
import math
import numpy as np
try:
from .config import MarkovChainConfig
except ImportError: # run from the template's own folder
from config import MarkovChainConfig
def estimate_transition_matrix(sequence, n_states: int | None = None, smoothing: float = 0.0) -> np.ndarray:
"""Maximum likelihood transition matrix from one observed path.
sequence: 1-D array of integer states, length at least 2.
n_states: number of states; defaults to max(sequence) + 1.
smoothing: count added to every transition, so unseen moves keep a little probability.
Returns array (n_states, n_states). A state never left (and smoothing 0) gets a uniform row.
"""
seq = np.asarray(sequence, dtype=int).ravel()
if seq.size < 2 or seq.min() < 0:
raise ValueError("sequence needs at least two non-negative integer states")
k = int(seq.max()) + 1 if n_states is None else n_states
counts = np.full((k, k), float(smoothing))
np.add.at(counts, (seq[:-1], seq[1:]), 1.0)
totals = counts.sum(axis=1, keepdims=True)
return np.where(totals > 0, counts / np.where(totals > 0, totals, 1.0), 1.0 / k)
class MarkovChain:
"""A finite Markov chain with transition matrix P, array (n, n), rows summing to 1."""
def __init__(self, transition_matrix, config: MarkovChainConfig | None = None) -> None:
self.config = config or MarkovChainConfig()
P = np.asarray(transition_matrix, dtype=float)
if P.ndim != 2 or P.shape[0] != P.shape[1]:
raise ValueError("the transition matrix must be square")
if np.any(P < 0) or np.abs(P.sum(axis=1) - 1.0).max() > max(self.config.tolerance, 1e-8):
raise ValueError("every row of the transition matrix must be non-negative and sum to 1")
self.P = P
self.n_states = P.shape[0]
self.rng = np.random.default_rng(self.config.seed)
def n_step_matrix(self, n: int) -> np.ndarray:
"""P^n: entry (i, j) is the probability of being in j after n steps from i."""
return np.linalg.matrix_power(self.P, n)
def distribution_after(self, start, n: int) -> np.ndarray:
"""Distribution over states after n steps from the start distribution, array (n_states,)."""
return np.asarray(start, dtype=float) @ self.n_step_matrix(n)
def stationary_distribution(self) -> np.ndarray:
"""pi with pi P = pi and sum(pi) = 1, array (n_states,). Unique when the chain is irreducible."""
if self.config.method == "eigen":
values, vectors = np.linalg.eig(self.P.T)
v = np.real(vectors[:, np.argmin(np.abs(values - 1.0))])
return v / v.sum()
pi = np.full(self.n_states, 1.0 / self.n_states)
lazy = 0.5 * (self.P + np.eye(self.n_states)) # same stationary distribution, but never periodic
for _ in range(self.config.max_iter):
new = pi @ lazy
if np.abs(new - pi).max() < self.config.tolerance:
return new
pi = new
return pi
def is_irreducible(self) -> bool:
"""True when every state can be reached from every other state."""
reach = (self.P > 0) | np.eye(self.n_states, dtype=bool)
for _ in range(max(1, int(math.ceil(math.log2(self.n_states))))):
reach = (reach.astype(int) @ reach.astype(int)) > 0
return bool(reach.all())
def period(self) -> int:
"""Period of an irreducible chain: the gcd of the lengths of all cycles. 1 means aperiodic."""
if not self.is_irreducible():
raise ValueError("the period is defined here for irreducible chains only")
level = {0: 0}
queue, g = [0], 0
while queue:
u = queue.pop(0)
for v in np.nonzero(self.P[u] > 0)[0]:
v = int(v)
if v not in level:
level[v] = level[u] + 1
queue.append(v)
else:
g = math.gcd(g, level[u] + 1 - level[v])
return abs(g)
def absorbing_states(self) -> list[int]:
"""States that are never left: P[i, i] = 1."""
return [i for i in range(self.n_states) if self.P[i, i] == 1.0]
def _fundamental(self):
absorbing = self.absorbing_states()
if not absorbing:
raise ValueError("the chain has no absorbing state")
transient = [i for i in range(self.n_states) if i not in absorbing]
Q = self.P[np.ix_(transient, transient)]
N = np.linalg.inv(np.eye(len(transient)) - Q) # expected visits to each transient state
return transient, absorbing, N
def absorption_probabilities(self) -> tuple[list[int], list[int], np.ndarray]:
"""(transient states, absorbing states, B) with B[i, j] = P(end in absorbing j | start in transient i)."""
transient, absorbing, N = self._fundamental()
return transient, absorbing, N @ self.P[np.ix_(transient, absorbing)]
def expected_steps_to_absorption(self) -> np.ndarray:
"""Expected number of steps before absorption from each transient state, array (n_transient,)."""
_, _, N = self._fundamental()
return N.sum(axis=1)
def mean_first_passage_time(self, target: int) -> np.ndarray:
"""Expected steps to first reach `target` from each state, array (n_states,), 0 at the target itself."""
others = [i for i in range(self.n_states) if i != target]
Q = self.P[np.ix_(others, others)]
times = np.linalg.solve(np.eye(len(others)) - Q, np.ones(len(others)))
out = np.zeros(self.n_states)
out[others] = times
return out
def simulate(self, n_steps: int, start: int = 0) -> np.ndarray:
"""One random path. Returns integer array (n_steps + 1,) beginning with `start`."""
cumulative = np.cumsum(self.P, axis=1)
draws = self.rng.random(n_steps)
path = np.empty(n_steps + 1, dtype=int)
path[0] = start
for t in range(n_steps):
path[t + 1] = min(int(np.searchsorted(cumulative[path[t]], draws[t], side="right")), self.n_states - 1)
return path- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 8, run with
python3 -m unittest -v
Practice
Build MarkovChain([[0.9, 0.1], [0.5, 0.5]]) and check distribution_after([1, 0], 2) and stationary_distribution against the worked example. Simulate 10000 steps with simulate and pass the path to estimate_transition_matrix. Then build a four-state gambler's ruin chain with absorbing states at both ends and read absorption_probabilities and expected_steps_to_absorption.
Check on learning
- The chain with rows and has stationary distribution , yet starting from state 0 its distribution never converges. How can both be true?
A way to think about it
Follow the distribution for a few steps. Then compare the idea of a distribution that stays put with the idea of one that every start is drawn toward.
- The power method in the template iterates with and not with . Why does that not change the answer, and what does it fix?
A way to think about it
Check that implies . Then ask what adding a chance of staying put does to a chain that alternates.
- The second eigenvalue of the worked matrix is 0.4. Roughly how many steps until the start is forgotten, and what if it were 0.99?
A way to think about it
The distance to the stationary distribution shrinks by that factor every step. Solve for the step count that makes or small.
- Tomorrow's weather really depends on the last two days. How could you still use a Markov chain?
A way to think about it
Redefine what a state is. A pair of consecutive days carries the memory that a single day lacks.
- Why must be invertible for an absorbing chain in which every transient state can reach an absorbing one?
A way to think about it
Use the series form of . If absorption is certain, the powers of shrink to zero, so the sum is finite.