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.
Stationarity and return cycles
A stationary distribution is a row distribution satisfying . If , then for every 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 with positive components. For a countable irreducible chain, existence of a stationary distribution is equivalent to positive recurrence. If , the return relation is
The argument is regenerative. Each visit to 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 . When its expected length is finite, the strong law for sums of lengths and rewards identifies the fraction of visits to 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 would make the formula nonsensical.
To calculate , solve together with , or iterate if convergence holds. The relevant eigenvector is the left eigenvector of . 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 is the greatest common divisor of . 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, is stationary, but starting from the first state the laws alternate between and and never converge to .
For a finite irreducible chain, with preserves stationary distributions, remains irreducible, and has positive self-transitions, so it is aperiodic. With 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 and, independently, . Both copies evolve with matrix independently until ; from they use the same random transition. Each marginal still has matrix , and . For any set , the difference between and can only come from the event . Taking the supremum over ,
Justify the primitivity lemma used here: there is with for every pair. Choose a state . 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 there is a path to , and from one to each ; inserting returns to between them gives a path of length for every sufficiently large . Since there are finitely many pairs, one bound works for all of them.
Fix and . While the copies have not met, the probability that both are in at the end of the next block of steps is at least . Hence . 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 . 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 on its states,
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, is required. The proof groups terms into cycles between visits to a reference state: pairs of cycle length and sum of 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 .
Uncertainty with dependent samples
For a finite irreducible and aperiodic chain, the Markov-chain central limit theorem states, for real ,
where . 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 , the integrated autocorrelation time is and the approximate effective sample size is . Negative autocorrelation can give an effective size greater than .
Consider the two-state chain with switching probability and . It has , and . By the geometric series, and . Its asymptotic standard error is times the value under independence. This figure is a model property, not a performance measurement.
To estimate by batches, divide a path of length into blocks of size , calculate their means , and use . Blocks that are too short retain dependence; too few blocks give an unstable estimate. Asymptotic theory requires both and to grow under suitable assumptions. An approximate normal interval is ; its coverage need not equal exactly in a finite sample.
Reversibility
A positive distribution satisfies detailed balance and reversibility if for each pair. Summing over gives , 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 . For an edge , both flows are ; outside edges they are zero. With , the matrix is symmetric by detailed balance. It is similar to , so the spectrum of is real. Positivity of ensures that the inverse exists.
PageRank: a walk that can always escape
PageRank is the stationary distribution of a link walk with teleportation. Let be the row matrix of normalized links for nodes with outgoing edges and zero rows for dangling nodes. Let be a teleportation distribution with all components positive and . If indicates dangling nodes, the column update is
A dangling node redistributes its mass according to . Teleportation gives every transition a positive contribution, so there is a unique stationary distribution. Moreover, distance between two iterates contracts by at most the factor , 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.
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 is the matrix’s nontrivial eigenvalue, which controls the difference between its rows in this particular case.
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 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.
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.
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 , 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 means package declares an active dependency on 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.
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])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
More than one answer may be correct.
Step 1 of 3. How are the copies constructed?
Step 1 of 3. What happens when summing πᵢPᵢⱼ over i?
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):
passThe 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.