Sign in

Markov chains

A process that moves between a finite set of states, where the next state depends only on the current one through a transition matrix.

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

  1. List the states and fill the transition matrix PP, where entry PijP_{ij} is the probability of moving from state ii to state jj. Every row must sum to 1.
  2. Describe the start as a row vector of probabilities over states, and multiply it by PP once for each step.
  3. Find the stationary distribution: the row vector that PP leaves unchanged. The template takes the left eigenvector for eigenvalue 1, or iterates until nothing moves.
  4. Check that the chain is irreducible (every state can reach every other) so that the stationary distribution is unique, and find its period.
  5. 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.
  6. Simulate a path by drawing each next state from the row of the current one, or estimate PP 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

IfUse instead
The next step depends on several past stepsA higher-order chain, or a sequence model such as an LSTM or GRU
The true state is not observed directlyA hidden Markov model
The state is continuous, not a finite setStochastic processes, such as random walks and Brownian motion
An agent chooses actions that change the transitionsA Markov decision process, as in the reinforcement learning lessons

Math foundations

  1. The Markov property

    P(Xt+1=j∣Xt=i, Xt−1,…,X0)=P(Xt+1=j∣Xt=i)=PijP(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 future depends on the past only through the present state. The numbers PijP_{ij} form the transition matrix, and each row is a probability distribution.

  2. Many steps

    πt=π0 P t\pi_{t} = \pi_{0}\,P^{\,t}

    With π0\pi_0 a row vector of starting probabilities, one multiplication by PP advances one step. Entry (i,j)(i, j) of PtP^{t} is the probability of being in jj after tt steps from ii.

  3. Stationary distribution

    π P=π,∑iπi=1\pi\,P = \pi, \qquad \sum_{i} \pi_i = 1

    A distribution that one step leaves unchanged. It is a left eigenvector of PP with eigenvalue 1. For an irreducible chain it is unique and equals the long-run fraction of time spent in each state.

  4. Absorbing chains

    P=(QR0I),N=(I−Q)−1=∑k=0∞QkP = \begin{pmatrix} Q & R \\ 0 & I \end{pmatrix}, \qquad N = (I - Q)^{-1} = \sum_{k=0}^{\infty} Q^{k}

    Order the states with transient ones first. QQ holds moves among transient states and RR moves into absorbing ones. Entry (i,j)(i, j) of the fundamental matrix NN is the expected number of visits to transient state jj when starting from ii.

  5. Where and when absorption happens

    B=NR,t=N 1B = N R, \qquad \mathbf{t} = N\,\mathbf{1}

    BijB_{ij} is the probability of ending in absorbing state jj from transient state ii. The vector t\mathbf{t} holds the expected number of steps before absorption, the row sums of NN.

  6. Mean first passage time

    mi=1+∑j≠targetPij mj,mtarget=0m_i = 1 + \sum_{j \ne \text{target}} P_{ij}\,m_j, \qquad m_{\text{target}} = 0

    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.

  7. Estimating the matrix

    P^ij=nij∑knik\hat{P}_{ij} = \frac{n_{ij}}{\sum_{k} n_{ik}}

    The maximum likelihood estimate from an observed path: the share of departures from state ii that went to state jj.

Symbols

XtX_t
the state at step tt
PP
the transition matrix; PijP_{ij} is the probability of moving from ii to jj
πt\pi_t
the row vector of state probabilities at step tt
π\pi
the stationary distribution
QQ
the block of transitions among transient states
RR
the block of transitions from transient to absorbing states
II
the identity matrix
NN
the fundamental matrix
BB
the matrix of absorption probabilities
t\mathbf{t}
the expected steps to absorption from each transient state
1\mathbf{1}
a column vector of ones
mim_i
the expected number of steps from state ii to the target
nijn_{ij}
the number of observed moves from ii to jj

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 PP are (0.9,0.1)(0.9, 0.1) and (0.5,0.5)(0.5, 0.5). Start on a sunny day.

π1=(1,0) P=(0.9, 0.1)\pi_1 = (1, 0)\,P = (0.9,\ 0.1)
π2=(0.9×0.9+0.1×0.5,  0.9×0.1+0.1×0.5)=(0.86, 0.14)\pi_2 = (0.9 \times 0.9 + 0.1 \times 0.5,\ \ 0.9 \times 0.1 + 0.1 \times 0.5) = (0.86,\ 0.14)
π0∗×0.1=π1∗×0.5 ⟹ π0∗=5 π1∗\pi_0^{\ast} \times 0.1 = \pi_1^{\ast} \times 0.5 \ \Longrightarrow\ \pi_0^{\ast} = 5\,\pi_1^{\ast}
π∗=(56, 16)≈(0.833, 0.167)\pi^{\ast} = \left(\tfrac{5}{6},\ \tfrac{1}{6}\right) \approx (0.833,\ 0.167)

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 above
Read 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

  1. The chain with rows (0,1)(0, 1) and (1,0)(1, 0) has stationary distribution (0.5,0.5)(0.5, 0.5), 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.

  2. The power method in the template iterates with 12(P+I)\tfrac{1}{2}(P + I) and not with PP. Why does that not change the answer, and what does it fix?
    A way to think about it

    Check that πP=π\pi P = \pi implies π⋅12(P+I)=π\pi \cdot \tfrac{1}{2}(P + I) = \pi. Then ask what adding a chance of staying put does to a chain that alternates.

  3. 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 0.4t0.4^{t} or 0.99t0.99^{t} small.

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

  5. Why must I−QI - Q 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 NN. If absorption is certain, the powers of QQ shrink to zero, so the sum is finite.