Module contents
Lesson 3 of 31Core 110 min

Markov chains II: stationary distribution, convergence and the ergodic theorem

When a stationary distribution exists, when it is unique, and when the chain converges to it. Prove the convergence theorem by coupling, the ergodic theorem for time averages, and the Markov-chain central limit theorem with its asymptotic variance governing MCMC error. Study reversibility and detailed balance, then apply the results to PageRank.

After this lesson you can

  • Calculate stationary distributions by solving πP = π, using power iteration, and using detailed balance when applicable.
  • Prove the convergence theorem by coupling two chains.
  • Estimate the asymptotic variance of a time average using batches and autocorrelations and construct appropriate confidence intervals.
  • Recognize a reversible chain and exploit reversibility to obtain π without solving systems.
  • Implement sparse PageRank and analyze the damping factor's role in convergence speed.

Before you start

A distribution that stays fixed while the chain moves

A server switches between load states, an MCMC chain explores possible parameters, and a browser jumps between pages. In each case we want to know what fraction of time is spent in each state and whether the result depends on where the system started. Two questions arise: does a distribution remain unchanged under a transition? Do distributions started in other states reach it?

Compare two copies that move separately until they meet and then use the same transitions. If one starts in equilibrium, they agree once they meet. The probability that they remain separate bounds the distance between their laws.

InteractiveCoupling two chains
X starts at 0; Y starts from the uniform stationary distribution. If they start apart, the copies are independent until they meet and then share steps.
Step0
X0
Y1
  • Exact probability of no meeting
  • Exact distance to stationarity

The curves come from the matrix with probability 0.05 of changing state. While separate, the probability of remaining separate for a step is 0.95² + 0.05² = 0.905. Half the pairs start apart; hence P(T > n) = 0.5 · 0.905ⁿ. TV distance is 0.5 · 0.9ⁿ and lies below that bound.

step 0
State of X0
State of Y1
Meeting in the samplenot yet
P(T > n), exact0.5000
TV distance, exact0.5000
Follow two copies of the same chain and compare the exact distance to stationarity with the probability that they have not met. One copy starts from the stationary distribution; after meeting they share their steps.

Stationarity and return cycles

A stationary distribution is a row distribution π\pi satisfying πP=π\pi P=\pi. If X0∼πX_0\sim\pi, then Xn∼πX_n\sim\pi for every nn and, by homogeneity, the law of any time block is unchanged by shifting it. Stationarity does not mean each path stays fixed.

A finite irreducible chain has a unique π\pi with positive components. For a countable irreducible chain, existence of a stationary distribution is equivalent to positive recurrence. If Ti+=inf⁡{n≥1:Xn=i}T_i^+=\inf\{n\ge1:X_n=i\}, the return relation is

πi=1EiTi+.\pi_i=\frac1{\E_iT_i^+}.

The argument is regenerative. Each visit to ii starts a cycle; by the strong Markov property, successive cycles are independent and identically distributed. A cycle includes its initial time and ends just before the next return. It contains exactly one visit to ii. When its expected length is finite, the strong law for sums of lengths and rewards identifies the fraction of visits to ii with one visit per cycle divided by mean cycle length. The same calculation for every state gives an invariant distribution, and irreducibility guarantees uniqueness. The first return must be after time zero: using Ti=0T_i=0 would make the formula nonsensical.

To calculate π\pi, solve (P⊤−I)π⊤=0(P\T-I)\pi\T=0 together with ∑iπi=1\sum_i\pi_i=1, or iterate μn+1=μnP\mu_{n+1}=\mu_nP if convergence holds. The relevant eigenvector is the left eigenvector of PP. Detailed balance, studied later, offers another route when the chain is reversible.

Periodicity: equilibrium without convergence

For a state admitting a return, the period of ii is the greatest common divisor of {n≥1:Piin>0}\{n\ge1:P^n_{ii}>0\}. If that set is empty, leave the period undefined. Periodicity is a class property when a return exists. If the period is one, the state is aperiodic. In a chain that alternates deterministically between two states, π=(1/2,1/2)\pi=(1/2,1/2) is stationary, but starting from the first state the laws alternate between (1,0)(1,0) and (0,1)(0,1) and never converge to π\pi.

InteractiveA periodic chain and its lazy version

The chain starts at state 0. At each step it stays with probability λ; otherwise it advances around 0 → 1 → 2 → 3 → 4 → 5 → 0. Each bar is a probability of the exact distribution at the selected step.

00.20.40.60.81011020304050probability

Distance to the uniform distribution is half the sum of absolute differences. The dashed line uses the same cycle with λ = 0.50.

  • Selected laziness: 0.00
  • Reference: laziness 0.50

At λ = 0 the distribution cycles without converging, although uniform is stationary. For 0 < λ < 1 returns occur at consecutive steps and the chain is aperiodic. With λ near 1, staying too often also slows mixing.

0.00
step 0
Mass in even states100.0 %
TV distance to uniform0.8333
Stationary probability per state16.7 %
Advance along an even cycle and add a probability of staying in the same state. Compare the law at the current step with the uniform law and observe what happens when the stay probability is very high.

For a finite irreducible chain, Pλ=λI+(1−λ)PP_\lambda=\lambda I+(1-\lambda)P with 0<λ<10<\lambda<1 preserves stationary distributions, remains irreducible, and has positive self-transitions, so it is aperiodic. With λ=1\lambda=1 there is no movement and irreducibility is lost if there is more than one state. Adding laziness removes periodic oscillation, but making it increasingly large can slow exploration.

Convergence by coupling

Proof

Let X0∼μX_0\sim\mu and, independently, Y0∼πY_0\sim\pi. Both copies evolve with matrix PP independently until T=inf⁡{n≥0:Xn=Yn}T=\inf\{n\ge0:X_n=Y_n\}; from TT they use the same random transition. Each marginal still has matrix PP, and Yn∼πY_n\sim\pi. For any set AA, the difference between P(Xn∈A)\Pr(X_n\in A) and P(Yn∈A)\Pr(Y_n\in A) can only come from the event Xn≠YnX_n\ne Y_n. Taking the supremum over AA,

∥μPn−π∥TV≤P(T>n).\|\mu P^n-\pi\|_{\mathrm{TV}}\le\Pr(T>n).

Justify the primitivity lemma used here: there is mm with Pm(i,j)>0P^m(i,j)>0 for every pair. Choose a state zz. Its return lengths have greatest common divisor one, so a finite subfamily of those lengths does too. Nonnegative sums of that subfamily contain every sufficiently large integer: for each residue modulo one length there is a sum with that residue, and adding multiples of that length reaches all subsequent values with the same residue. From each ii there is a path to zz, and from zz one to each jj; inserting returns to zz between them gives a path of length nn for every sufficiently large nn. Since there are finitely many pairs, one bound works for all of them.

Fix zz and ε=min⁡i,jPm(i,z)Pm(j,z)>0\varepsilon=\min_{i,j}P^m(i,z)P^m(j,z)>0. While the copies have not met, the probability that both are in zz at the end of the next block of mm steps is at least ε\varepsilon. Hence P(T>km)≤(1−ε)k→0\Pr(T>km)\le(1-\varepsilon)^k\to0. This bound can be very conservative, but it proves convergence.

∎

A coupling is a joint construction of variables preserving their marginals. If both copies started in fixed states, the same argument would bound the distance between their two laws, not automatically the distance to π\pi. On a finite space, total variation distance is half the sum of absolute probability differences.

Averaging over time

The ergodic theorem says that, for a finite irreducible chain and any real function ff on its states,

1n∑k=0n−1f(Xk)⟶∑iπif(i)casi seguramente.\frac1n\sum_{k=0}^{n-1}f(X_k)\longrightarrow\sum_i\pi_i f(i)\quad\text{casi seguramente}.

It does not require aperiodicity: even in deterministic alternation, the proportion of visits to each state tends to one half while the instantaneous law oscillates. On a countable irreducible positive recurrent space, ∑iπi∣f(i)∣<∞\sum_i\pi_i|f(i)|<\infty is required. The proof groups terms into cycles between visits to a reference state: pairs of cycle length and sum of ff over the cycle are iid by strong Markov. The strong law applied to both, together with control of the last incomplete cycle, gives the ratio of expected reward to expected duration, equal to πf\pi f.

Uncertainty with dependent samples

For a finite irreducible and aperiodic chain, the Markov-chain central limit theorem states, for real ff,

n(fˉn−πf)⇒N(0,σf2),σf2=γ0+2∑k≥1γk,\sqrt n(\bar f_n-\pi f)\Rightarrow\Normal(0,\sigma_f^2),\qquad \sigma_f^2=\gamma_0+2\sum_{k\ge1}\gamma_k,

where γk=Cov⁡π(f(X0),f(Xk))\gamma_k=\Cov_\pi(f(X_0),f(X_k)). The series converges absolutely in this finite aperiodic case; the variance can be zero, giving a degenerate limit. The same result requires additional hypotheses on general spaces: writing the sum formally is not enough. If γ0>0\gamma_0>0, the integrated autocorrelation time is τint=σf2/γ0\tau_{\mathrm{int}}=\sigma_f^2/\gamma_0 and the approximate effective sample size is n/τintn/\tau_{\mathrm{int}}. Negative autocorrelation can give an effective size greater than nn.

Consider the two-state chain with switching probability 0.050.05 and f(i)=if(i)=i. It has π=(1/2,1/2)\pi=(1/2,1/2), γ0=1/4\gamma_0=1/4 and ρk=0.9k\rho_k=0.9^k. By the geometric series, τint=(1+0.9)/(1−0.9)=19\tau_{\mathrm{int}}=(1+0.9)/(1-0.9)=19 and σf2=4.75\sigma_f^2=4.75. Its asymptotic standard error is 19\sqrt{19} times the value under independence. This figure is a model property, not a performance measurement.

InteractiveCoverage with and without dependence
Interval for the mean
  • Covers truth
  • Does not cover truth
  • True mean = 0.5

The first 20 of 200 replicates are drawn; coverage counts all. Each starts in the uniform stationary distribution of a symmetric two-state chain. The observed function is the state itself, so its true mean is 0.5.

Both intervals use the 1.96 normal quantile. The naive interval treats values as independent; the other estimates error using sample variance of consecutive batch means. Coverage is a simulated frequency, not a guarantee: short batches retain dependence and few batches estimate variance poorly.

2 %
Observations per replicate
Observations per batch
Displayed intervals
Naive coverage53 / 200 (26.5 %)
Batch coverage182 / 200 (91.0 %)
Batches per replicate20
Initial seed2603
Lag-1 autocorrelation0.96
Compare intervals built as if states were independent with batch-based intervals in reproducible replications. Finite-sample coverage fluctuates; coverage near the nominal value is not guaranteed for every choice of batch length.

To estimate σf2\sigma_f^2 by batches, divide a path of length n=abn=ab into aa blocks of size bb, calculate their means fˉ1,…,fˉa\bar f_1,\ldots,\bar f_a, and use σ^f2=b s2(fˉ1,…,fˉa)\hat\sigma_f^2=b\,s^2(\bar f_1,\ldots,\bar f_a). Blocks that are too short retain dependence; too few blocks give an unstable estimate. Asymptotic theory requires both bb and aa to grow under suitable assumptions. An approximate normal interval is fˉn±1.96σ^f2/n\bar f_n\pm1.96\sqrt{\hat\sigma_f^2/n}; its coverage need not equal 0.950.95 exactly in a finite sample.

Reversibility

A positive distribution π\pi satisfies detailed balance and reversibility if πiPij=πjPji\pi_iP_{ij}=\pi_jP_{ji} for each pair. Summing over ii gives ∑iπiPij=πj∑iPji=πj\sum_i\pi_iP_{ij}=\pi_j\sum_iP_{ji}=\pi_j, so detailed balance implies stationarity. The converse is false: a deterministic directed three-state cycle has a stationary uniform distribution, but its forward flow is not balanced edge by edge.

In a finite connected undirected graph with at least one edge, the walk choosing a neighbor uniformly has πi=deg⁡(i)/(2∣E∣)\pi_i=\deg(i)/(2|E|). For an edge i↔ji\leftrightarrow j, both flows are 1/(2∣E∣)1/(2|E|); outside edges they are zero. With Dπ=diag⁡(π)D_\pi=\diag(\pi), the matrix Dπ1/2PDπ−1/2D_\pi^{1/2}PD_\pi^{-1/2} is symmetric by detailed balance. It is similar to PP, so the spectrum of PP is real. Positivity of π\pi ensures that the inverse exists.

PageRank: a walk that can always escape

PageRank is the stationary distribution of a link walk with teleportation. Let HH be the row matrix of normalized links for nodes with outgoing edges and zero rows for dangling nodes. Let vv be a teleportation distribution with all components positive and 0≤α<10\le\alpha<1. If dd indicates dangling nodes, the column update is

xn+1=α(H⊤xn+(d⊤xn)v)+(1−α)v.\vb x_{n+1}=\alpha\big(H\T\vb x_n+(\vb d\T\vb x_n)\vb v\big)+(1-\alpha)\vb v.

A dangling node redistributes its mass according to vv. Teleportation gives every transition a positive contribution, so there is a unique stationary distribution. Moreover, distance L1L^1 between two iterates contracts by at most the factor α\alpha, because the stochastic part does not increase that distance. This bound does not say that all graphs take exactly the same time or that the second eigenvalue alone determines a finite tolerance.

InteractivePageRank and damping
Group AGroup B70 % of links remain in A90 % of links remain in B30 %10 %A116.3 %A216.3 %B133.7 %B233.7 %

Each page distributes equally between the two pages of the chosen group. Arrows show links, not teleportation. A group without outgoing links is a link trap.

All mass starts at A1. Iterations stop when L1 change is at most 1e-10, or upon reaching 3000. The chart shows that iteration’s result. With α below 1, uniform teleportation ensures a unique stationary distribution.

In this symmetric family, the second eigenvalue is α(1 − q − r), with q and r the crossing fractions; when B is a sink, r = 1/2 is used for uniform redistribution. The other two eigenvalues are zero.

30 %
10 %
0.85
Total mass1.000000
Second eigenvalue0.5100
Magnitude of second eigenvalue0.5100
Iterations35
L1 change in the last iteration7.53e-11
Modify the graph, dangling nodes and damping factor. Compare ranking, convergence and the second eigenvalue of the displayed model.

Lab: estimating chain error

First calculate the stationary distribution of the two-state chain in three ways: a normalized linear system, a left eigenvector, and power iteration. Then compare total variation distance with the exact formula for this example. The value 0.90.9 is the matrix’s nontrivial eigenvalue, which controls the difference between its rows in this particular case.

[ ]Three ways to calculate the stationary distributionBrowser
import numpy as np

P = np.array([[0.95, 0.05], [0.05, 0.95]])
A = P.T - np.eye(2)
A[-1] = 1
b = np.array([0., 1.])
pi_sistema = np.linalg.solve(A, b)
valores, vectores = np.linalg.eig(P.T)
v = vectores[:, np.argmin(np.abs(valores - 1))].real
pi_auto = v / v.sum()
mu = np.array([1., 0.])
for _ in range(200):
    mu = mu @ P
print('sistema:', pi_sistema)
print('autovector izquierdo:', np.round(pi_auto, 8))
print('potencia:', np.round(mu, 8))
for n in [0, 10, 50]:
    ley = np.array([1., 0.]) @ np.linalg.matrix_power(P, n)
    tv = 0.5 * np.abs(ley - pi_sistema).sum()
    print('paso, TV matricial y exacta:', n, round(tv, 8), round(0.5 * 0.9**n, 8))
print('varianza asintótica exacta:', 0.25 * (1 + 0.9) / (1 - 0.9))

Power iteration is not a universal procedure for every stochastic matrix: in the periodic two-state chain it can oscillate indefinitely. A matrix that is not irreducible need not have a unique stationary distribution. In this example all three conditions of the finite theorem hold.

Now estimate the variance of an average using both batches and autocovariances. Geyer’s initial positive sequence estimator groups Γ^k=γ^2k+γ^2k+1\hat\Gamma_k=\hat\gamma_{2k}+\hat\gamma_{2k+1} and sums up to, but excluding, the first nonpositive pair. The theoretical structure motivating truncation requires reversibility; we do not claim it for an arbitrary chain. In short samples the estimate may be unstable or even nonpositive, calling for a better sample rather than hiding the issue. See Geyer’s documentation.

[ ]Batches and autocovariancesBrowser
def var_lotes(x, b):
    x = np.asarray(x, dtype=float)
    a = len(x) // b
    if b < 1 or a < 2:
        raise ValueError('se requieren al menos dos lotes no vacíos')
    medias = x[:a*b].reshape(a, b).mean(axis=1)
    return b * medias.var(ddof=1)

def var_geyer(x):
    x = np.asarray(x, dtype=float)
    centrada = x - x.mean()
    n = len(x)
    # Denominador n común para todas las autocovarianzas.
    gamma = np.correlate(centrada, centrada, mode='full')[n-1:] / n
    pares = gamma[:2*(n//2)].reshape(-1, 2).sum(axis=1)
    corte = np.flatnonzero(pares <= 0)
    limite = int(corte[0]) if len(corte) else len(pares)
    return -gamma[0] + 2 * pares[:limite].sum()

rng = np.random.default_rng(26031)
n = 8_000
x = np.empty(n, dtype=int)
x[0] = rng.integers(0, 2)
for t in range(1, n):
    x[t] = x[t-1] ^ (rng.random() < 0.05)
print('media:', round(x.mean(), 5))
print('varianza ingenua:', round(x.var(), 5))
print('varianza por lotes, b=200:', round(var_lotes(x, 200), 5))
print('varianza Geyer:', round(var_geyer(x), 5))
print('varianza exacta:', 4.75)

This calculation uses a path started from the stationary distribution; a real application must justify the start or address the initial period. The code does not guarantee a good approximation from any given batch. The next cell estimates coverage from 200 independent replications. Each column contains a chain and rows are time points: transitions are generated for all chains at once.

[ ]Interval coverageBrowser
rng = np.random.default_rng(26032)
replicas, n, b = 200, 2_000, 100
trayectorias = np.empty((n, replicas), dtype=np.int8)
trayectorias[0] = rng.integers(0, 2, replicas)
for t in range(1, n):
    trayectorias[t] = trayectorias[t-1] ^ (rng.random(replicas) < 0.05)
medias = trayectorias.mean(axis=0)
ingenua = trayectorias.var(axis=0, ddof=1)
lotes = trayectorias.reshape(n // b, b, replicas).mean(axis=1)
asintotica = b * lotes.var(axis=0, ddof=1)
cubre_ingenua = np.abs(medias - 0.5) <= 1.96 * np.sqrt(ingenua / n)
cubre_lotes = np.abs(medias - 0.5) <= 1.96 * np.sqrt(asintotica / n)
print('cobertura ingenua:', int(cubre_ingenua.sum()), '/', replicas)
print('cobertura por lotes:', int(cubre_lotes.sum()), '/', replicas)
print('error estándar de la proporción con p=0.95:', round(np.sqrt(.95*.05/replicas), 4))

The last line gives a scale of variation if true coverage were 0.950.95, not an exact interval or proof that it is. Both methods use the same replications to facilitate comparison; changing the seed changes the results.

Lab: sparse PageRank on real dependencies

Use dependencies declared in metadata of packages installed in the runtime environment, a real graph that can vary with the environment. An edge i→ji\to j means package ii declares an active dependency on jj and both are installed. Optional dependencies whose markers are not satisfied are excluded. This subgraph is not promised to be the complete catalog, and the ranking has no claimed causal interpretation.

The implementation uses sparse CSR matrices and never creates a dense teleportation matrix. Compare the result with networkx.pagerank, matching the dangling-node vector and stopping tolerance. The NetworkX documentation specifies that its criterion multiplies tol by the number of nodes.

[ ]Installed dependency graphBrowser
import re
import importlib.metadata as metadata
from packaging.requirements import Requirement
import scipy.sparse as sp
import networkx as nx

def normalizar(nombre):
    return re.sub(r'[-_.]+', '-', nombre).lower()

distribuciones = {normalizar(d.metadata['Name']): d for d in metadata.distributions()
                  if d.metadata.get('Name')}
nombres = sorted(distribuciones)
indice = {nombre: i for i, nombre in enumerate(nombres)}
aristas = set()
for nombre, dist in distribuciones.items():
    for texto in dist.requires or []:
        try:
            req = Requirement(texto)
        except Exception:
            continue
        if req.marker is not None and not req.marker.evaluate({'extra': ''}):
            continue
        destino = normalizar(req.name)
        if destino in indice:
            aristas.add((indice[nombre], indice[destino]))

filas = [i for i, j in aristas]
columnas = [j for i, j in aristas]
adj = sp.csr_matrix((np.ones(len(aristas)), (filas, columnas)), shape=(len(nombres), len(nombres)))
print('paquetes instalados:', len(nombres), 'aristas activas entre ellos:', len(aristas))
print('algunas aristas:', sorted((nombres[i], nombres[j]) for i, j in aristas)[:8])
[ ]Sparse iteration and comparison with NetworkXBrowser
def pagerank_disperso(adj, alpha=0.85, tol=1e-10, max_iter=1000):
    n = adj.shape[0]
    if n == 0 or not 0 <= alpha < 1:
        raise ValueError('se necesita un grafo no vacío y 0 <= alpha < 1')
    grados = np.asarray(adj.sum(axis=1)).ravel()
    inverso = np.divide(1., grados, out=np.zeros_like(grados), where=grados > 0)
    H = sp.diags(inverso) @ adj
    v = np.full(n, 1/n)
    x = v.copy()
    for paso in range(1, max_iter+1):
        nuevo = alpha * (H.T @ x + x[grados == 0].sum() * v) + (1-alpha) * v
        if np.abs(nuevo-x).sum() < tol:
            return nuevo, paso
        x = nuevo
    raise RuntimeError('la iteración no convergió')

if len(nombres) == 0:
    raise RuntimeError('no hay metadatos de paquetes instalados')
G = nx.from_scipy_sparse_array(adj, create_using=nx.DiGraph)
for alpha in [0.5, 0.85, 0.95]:
    rango, pasos = pagerank_disperso(adj, alpha)
    referencia = nx.pagerank(G, alpha=alpha, tol=1e-10/len(nombres), max_iter=1000)
    error = np.abs(rango - np.array([referencia[i] for i in range(len(nombres))])).sum()
    print('alpha, pasos, diferencia L1:', alpha, pasos, round(error, 12))
print('tres paquetes mejor clasificados:', [(nombres[i], round(rango[i], 6)) for i in np.argsort(-rango)[:3]])

If two packages have very close scores, their order can change with tolerance or environment. The sequence of iteration counts observed on this graph is not a universal rule for all graphs.

Exercises

QuizA three-state stationary distribution
A three-state transition matrix has every row equal to (0.2, 0.3, 0.5). What is its stationary distribution?
NumericProbability and return time
Let P have every row equal to (0.2, 0.3, 0.5). What is the mean first return time to state 1? States are numbered 1, 2, 3.
QuizWhat fails in each example
Which examples show that existence of a stationary distribution does not guarantee convergence from every initial state?

More than one answer may be correct.

QuizAn additional assumption in infinite space
On Z, a chain stays put with probability 1/2 and moves to each neighbor with probability 1/4. What prevents applying the convergence theorem to a stationary probability distribution?
ProofProving convergence
Prove: For a finite irreducible aperiodic chain, prove that the law from any initial distribution converges to its stationary distribution.
0
Use two copies, one started from the initial distribution and one from the stationary distribution.

Step 1 of 3. How are the copies constructed?

ProofDetailed balance on a graph
Prove: Prove that detailed balance implies stationarity and find the stationary distribution of a uniform walk on a finite connected undirected graph with at least one edge.
0
The sum of graph degrees is 2|E|.

Step 1 of 3. What happens when summing πᵢPᵢⱼ over i?

CodeBatch asymptotic variance
Implement asymptotic_variance(samples, batch_size): discard the trailing samples that do not form a complete batch and return batch size times the sample variance of batch means. There are at least two complete batches.
import numpy as np

def asymptotic_variance(samples, batch_size):
  pass
Shift+Enter to run
Key idea

The stationary distribution describes equilibrium; aperiodicity and finite irreducibility permit convergence to it. Time averages converge under weaker hypotheses, but their uncertainty depends on autocovariances. Detailed balance constructs reversible chains, and PageRank adds teleportation to ensure a unique distribution.