Module contents
Lesson 4 of 30Core 110 min

Random walks, diffusion and PageRank

Study random walks, stationary distributions and spectral mixing bounds, heat diffusion, PageRank and local push, effective resistance, and harmonic label propagation.

After this lesson you can

  • Prove degree-proportional stationarity and explain uniqueness and convergence.
  • Bound lazy-walk mixing time using the normalized Laplacian spectral gap.
  • Calculate PageRank and personalized PageRank with iteration and local push, relating teleportation to locality.
  • Calculate effective resistance and relate it to commute times.
  • Implement harmonic label propagation and compare it with a classifier that ignores edges.

Before you start

A probability walking along edges

Imagine a citation network where we know the category of a few papers. Can we transfer that information to their neighbors without treating a connection as definitive proof? A random walk makes an assumption explicit: from a node, the next is chosen among its neighbors with probability proportional to edge weight. Structure can retain local information for a long time when there is a bottleneck between communities.

We begin with a finite, connected, undirected graph with nonnegative weights and at least one edge. Its adjacency matrix is symmetric, di=∑jAij>0d_i=\sum_j A_{ij}>0 and P=D−1A\mat{P}=\mat{D}^{-1}\mat{A} is row-stochastic. For column distributions, pt+1=P⊤pt\vb p_{t+1}=\mat{P}\T\vb p_t. In a random walk on a graph,

πi=divol⁡(G),πiPij=Aijvol⁡(G)=πjPji.\pi_i=\frac{d_i}{\operatorname{vol}(G)},\quad \pi_iP_{ij}=\frac{A_{ij}}{\operatorname{vol}(G)}=\pi_jP_{ji}.

Summing over ii gives P⊤π=π\mat P\T\boldsymbol\pi=\boldsymbol\pi. Equality of flows is called detailed balance. Connectivity makes the chain irreducible and its stationary distribution unique, but does not guarantee convergence of the simple walk: on a bipartite graph it alternates between the two parts. The lazy walk Q=(I+P)/2\mat Q=(\mat I+\mat P)/2 has a probability of staying put and is aperiodic. With disconnected components, each has its own stationary distribution and initial mass remains in its component; isolated nodes require an additional convention.

InteractiveFrom the starting node to equilibrium
1234567812345678110⁻²10⁻⁴step 0step 40TV: log scale, floor 10⁻⁵
exact p = [1.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000]
π = [0.154, 0.115, 0.115, 0.115, 0.154, 0.115, 0.115, 0.115]
1
0
Exact TV0.8462
Empirical TV0.8462
Lazy gap0.0567
Two four-node cliques joined by one to four bridges. Circle sizes and the histogram show one thousand walkers simulated with a fixed seed from node 1; the exact curve uses total variation on a logarithmic scale.

To measure mixing and spectral gap, use ∥p−q∥TV=12∑i∣pi−qi∣\norm{p-q}_{\mathrm{TV}}=\frac12\sum_i|p_i-q_i|. By similarity, P\mat P and I−Lsym\mat I-\mat L_{\mathrm{sym}} have the same eigenvalues. If 0=λ1<λ2≤⋯≤λn≤20=\lambda_1<\lambda_2\le\cdots\le\lambda_n\le2 are those of Lsym\mat L_{\mathrm{sym}}, those of Q\mat Q are 1−λk/21-\lambda_k/2, all in [0,1][0,1]. With γ=λ2/2\gamma=\lambda_2/2 and starting node ii,

∥(Q⊤)tei−π∥TV≤12πi(1−γ)t≤e−γt2πi.\norm{(\mat Q\T)^t\vb e_i-\boldsymbol\pi}_{\mathrm{TV}} \le \frac{1}{2\sqrt{\pi_i}}(1-\gamma)^t \le \frac{e^{-\gamma t}}{2\sqrt{\pi_i}}.

The bound follows from Cauchy-Schwarz and contraction in L2(π)L^2(\pi) norm after removing the constant mode. It is an upper guarantee, not an exact prediction for each trajectory; the prefactor matters. For worst-case mixing, use πmin⁡\pi_{\min}. Laziness is essential here: without it, eigenvalue −1-1 on a bipartite graph maintains oscillation even if λ2>0\lambda_2>0.

To obtain a sufficient bound on tmix(ϵ)t_{\mathrm{mix}}(\epsilon), require the last term to be at most ϵ\epsilon: it suffices that t≥γ−1log⁡[1/(2ϵπmin⁡)]t\ge \gamma^{-1}\log[1/(2\epsilon\sqrt{\pi_{\min}})], rounded up when positive. This expression reveals two causes of slowness: a spectral bottleneck and starting at a node with small stationary probability. The figure’s exact curve may fall faster than the bound. The thousand walkers are a finite seeded sample; even at equilibrium their histogram fluctuates, so empirical distance need not reach zero.

Heat and filters

The equation x˙=−Lx\dot{\vb x}=-\mat L\vb x with L=D−A\mat L=\mat D-\mat A has solution x(t)=e−tLx(0)\vb x(t)=e^{-t\mat L}\vb x(0). If Luk=λkuk\mat L\vb u_k=\lambda_k\vb u_k, heat-kernel diffusion multiplies coefficient uk⊤x(0)\vb u_k\T\vb x(0) by e−tλke^{-t\lambda_k}. High-frequency modes decay faster. The sum of temperatures is conserved because 1⊤L=0\vb 1\T\mat L=0; on a connected graph the signal tends to its uniform mean. With a normalized Laplacian or a continuous-time walk, conventions and equilibrium change.

InteractiveHeat and spectral modes
123456781234eigenspaces by λ: initial grey, blue at t
1
0.0
Total mass1.000
Maximum temperature1.000
A unit source diffuses under the graph's combinatorial Laplacian. Bars show the norm of the initial and current projection into each eigenspace in increasing eigenvalue order; grouping repeated eigenvalues makes the result independent of the chosen basis.

The matrix Kt=e−tL\mat K_t=e^{-t\mat L} is also a diffusion kernel: it is symmetric positive definite for finite tt, since its eigenvalues are e−tλk>0e^{-t\lambda_k}>0. An entry Kt(i,j)K_t(i,j) compares nodes through all time-weighted walks; it is generally neither a distance nor a conditional probability without specified orientation and normalization. See the original work of Kondor and Lafferty.

Time tt is a scale, not a number of integer layers. For tt near zero, Kt≈I−tLK_t\approx I-tL and the immediate neighborhood dominates; at large times, components outside the kernel decay. On a disconnected graph diffusion does not cross components and each retains its own mean. The kernel remains valid but does not compare information transmitted between disconnected components.

In a directed graph, rows with no outgoing edges are dangling. Before iteration, replace them with a distribution vv summing to 1 (or another stated dangling-node distribution). With 0<α≤10<\alpha\le1 as teleportation probability and β=1−α\beta=1-\alpha, PageRank satisfies

p=αv+βP⊤p,(I−βP⊤)p=αv.\vb p=\alpha\vb v+\beta\mat P\T\vb p, \qquad (\mat I-\beta\mat P\T)\vb p=\alpha\vb v.

The update is an L1L^1 contraction by factor β\beta; therefore a unique fixed point exists even if vv is concentrated at one node. Some texts call β\beta by the name α\alpha: compare equations before comparing numbers. If dangling rows remain zero, iteration loses mass and does not implement this chain.

Personalized PageRank takes v=esv=e_s to explore around a seed. The series α∑k≥0βk(P⊤)kes\alpha\sum_{k\ge0}\beta^k(\mat P\T)^k e_s mixes geometrically distributed lengths with mean β/α\beta/\alpha. A large α\alpha favors short walks, although mass within a particular radius depends on structure.

The series explains the endpoint α=1\alpha=1: no graph step occurs and the distribution stays at vv. At the other extreme, as α\alpha approaches zero in a connected aperiodic graph, longer lengths receive more weight and the distribution approaches stationarity. Substituting α=0\alpha=0 into the equation does not guarantee uniqueness on every directed graph: contraction requires positive teleportation.

InteractiveTeleportation and locality
12345678
PPR = [0.297, 0.145, 0.145, 0.145, 0.108, 0.053, 0.053, 0.053]
push = [0.272, 0.126, 0.127, 0.128, 0.087, 0.038, 0.041, 0.040]
1
0.15
0.01
90% radius2
Nodes processed8
Residual mass0.1406
Size represents exact PPR; the radius uses graph distance and contains at least 90% of the mass. Push uses residual threshold rᵢ > εdᵢ on this undirected graph and reports the nodes actually processed.

In push we maintain p=0p=0, r=esr=e_s. Processing uu deposits αru\alpha r_u in pup_u and sends βruPuv\beta r_uP_{uv} to its neighbors. The invariant is p+PPR⁡(r)=PPR⁡(es)p+\operatorname{PPR}(r)=\operatorname{PPR}(e_s), with PPR extended linearly to mass vectors. Since r≥0r\ge0 and P\mat P is stochastic, ∥PPR⁡(r)∥1=∥r∥1\norm{\operatorname{PPR}(r)}_1=\norm r_1: residual mass is exactly the deposited vector’s L1L^1 error. The criterion ri≤ϵdir_i\le\epsilon d_i does not by itself imply total error ϵ\epsilon; it does guarantee ∥r∥1≤ϵvol⁡(G)\norm r_1\le\epsilon\operatorname{vol}(G). A degree-normalized PPR sweep can find local cuts; its guarantees require specific assumptions, as in Andersen, Chung and Lang.

Current, labels and boundary conditions

For two nodes of a connected weighted graph with conductances AijA_{ij}, effective resistance is

Ruv=(eu−ev)⊤L+(eu−ev).R_{uv}=(\vb e_u-\vb e_v)\T\mat L^+(\vb e_u-\vb e_v).

It equals the potential difference when one unit of current is injected at uu and removed at vv. Fixing a reference potential and solving the reduced system avoids forming a dense pseudoinverse when few pairs are needed. For the reversible simple walk, expected commute time satisfies Huv+Hvu=vol⁡(G)RuvH_{uv}+H_{vu}=\operatorname{vol}(G)R_{uv}; in an unweighted graph vol⁡(G)=2m\operatorname{vol}(G)=2m. A path of five unit resistors has resistance 5; in a six-cycle, two paths of three in parallel give 3/23/2.

In harmonic label propagation, values YLY_L are fixed on labeled nodes and energy is minimized over unknown nodes. Separating LL and UU, the first-order equation is LUUFU=WULYL\mat L_{UU}\mat F_U=\mat W_{UL}\mat Y_L. If every component has at least one label, LUU\mat L_{UU} is positive definite and

FU=LUU−1WULYL.\mat F_U=\mat L_{UU}^{-1}\mat W_{UL}\mat Y_L.

Each unknown row is the weighted average of its neighbors. With one-hot labels, columns can be interpreted as first-hitting probabilities for the classes; they can also be ambiguous if the graph connects categories. A component with no labels has no unique solution: abstain, add a condition or state a regularization. The method of Zhu, Ghahramani and Lafferty formalizes this relationship.

InteractiveLabels on two moons
Harmonic solution on graph
1-NN in coordinates, without edges
Label on click
Known labels4
Harmonic / 1-NN disagreements8
Symmetrized 4-NN graph over 24 deterministic points. Click nodes to set or remove labels. The view compares the harmonic solution with the nearest labeled neighbor in coordinate space; disagreement does not measure accuracy without independent ground-truth labels.

A soft alternative from Zhou and colleagues iterates F(t+1)=ρSF(t)+(1−ρ)YF^{(t+1)}=\rho S F^{(t)}+(1-\rho)Y, with S=D−1/2AD−1/2S=D^{-1/2}AD^{-1/2} and 0<ρ<10<\rho<1. Returning to YY at each step also allows predictions on labeled nodes to change; this is not the same fixed-boundary problem. In both methods quality depends on the relationship between edges and classes, and leakage-free evaluation must separate training and test labels.

Lab: PageRank, diffusion and resistance

The following functions work with a nonnegative CSR sparse adjacency matrix. In PageRank, dangling nodes send their mass to the same teleportation distribution. For push we choose an undirected graph without isolates and check the residual invariant. Degree-relative stopping controls local work; it is not a direct total-error bound independent of volume.

[ ]Sparse PageRank and pushBrowser
import numpy as np
import networkx as nx
from scipy import sparse
from scipy.sparse.linalg import spsolve, expm_multiply

def transition(A):
    A=sparse.csr_matrix(A, dtype=float)
    d=np.asarray(A.sum(axis=1)).ravel()
    inv=np.divide(1.,d,out=np.zeros_like(d),where=d>0)
    P=sparse.diags(inv) @ A
    return P.tocsr(), d

def pagerank(A, v, alpha=.15, tol=1e-12):
    v=np.asarray(v,dtype=float); v=v/v.sum()
    P,d=transition(A); p=v.copy()
    for iteration in range(10000):
        nxt=alpha*v+(1-alpha)*(P.T@p+p[d==0].sum()*v)
        if np.linalg.norm(nxt-p,1)<tol:
            return nxt
        p=nxt
    raise RuntimeError('iteración sin converger')

def ppr_push(A, seed, alpha=.15, eps=1e-4):
    A=sparse.csr_matrix(A,dtype=float)
    P,d=transition(A)
    if np.any(d<=0):
        raise ValueError('push de este ejemplo requiere grados positivos')
    p=np.zeros(A.shape[0]); r=np.zeros_like(p); r[seed]=1
    touched=set()
    while True:
        active=np.flatnonzero(r>eps*d)
        if not len(active): break
        u=int(active[0]); amount=r[u]; r[u]=0
        p[u]+=alpha*amount
        start,end=P.indptr[u:u+2]
        np.add.at(r,P.indices[start:end],(1-alpha)*amount*P.data[start:end])
        touched.add(u)
    return p,r,touched

G=nx.barbell_graph(5,0)
A=nx.to_scipy_sparse_array(G,nodelist=range(len(G)),dtype=float,format='csr')
v=np.eye(1,len(G),0).ravel(); exact=pagerank(A,v)
approx,residual,touched=ppr_push(A,0)
nx_value=nx.pagerank(G,alpha=.85,personalization=dict(enumerate(v)),tol=1e-13,max_iter=10000)
assert np.allclose(exact,[nx_value[i] for i in range(len(G))],atol=1e-10)
assert np.isclose(np.linalg.norm(exact-approx,1),residual.sum(),atol=1e-10)
print('PPR:',np.round(exact,5).tolist())
print('push: nodos tocados',len(touched),'de',len(G),'error L1',round(np.linalg.norm(exact-approx,1),7),'residuo',round(residual.sum(),7))

# Un nodo colgante: la masa se redistribuye a la semilla.
directed=sparse.csr_matrix([[0,1,0],[0,0,1],[0,0,0]],dtype=float)
pv=np.array([1.,0.,0.]); out=pagerank(directed,pv)
DG=nx.from_scipy_sparse_array(directed,create_using=nx.DiGraph)
ref=nx.pagerank(DG,alpha=.85,personalization=dict(enumerate(pv)),tol=1e-13,max_iter=10000)
assert np.allclose(out,[ref[i] for i in range(3)],atol=1e-10) and np.isclose(out.sum(),1)
print('dirigido con colgante:',np.round(out,6).tolist())

In this execution on the ten-node graph, push error and residual sum both equaled 0.0020776; all ten nodes were processed. On the three-node directed graph with a dangling last row, the resulting distribution was approximately [0.388727,0.330418,0.280855][0.388727,0.330418,0.280855]. The cell checks both outputs against NetworkX under the same teleportation convention.

The preceding push always selects the first active node for readability. A work queue avoids scanning all nodes at each iteration. No claim is made that this implementation’s cost is independent of nn. On a longer path, one can count processed support and compare error with residual mass; this is a structured realization, not a general benchmark.

[ ]Local scope of pushBrowser
long_graph=nx.path_graph(1000)
long_A=nx.to_scipy_sparse_array(long_graph,nodelist=range(1000),dtype=float,format='csr')
approx,residual,touched=ppr_push(long_A,0,alpha=.15,eps=1e-4)
seed=np.eye(1,1000,0).ravel(); exact=pagerank(long_A,seed,alpha=.15)
err=np.linalg.norm(exact-approx,1)
assert np.isclose(err,residual.sum(),atol=1e-10)
print('nodos procesados:',len(touched),'de',len(long_graph),'error L1:',round(err,7))

With the seed at one endpoint and the stated parameters, push processed 15 of 1000 nodes and left L1L^1 error 0.0018231. That count changes with threshold, teleportation and structure; this implementation still scans the complete residual vector when selecting the next node.

For an electrical comparison, fix zero potential at the final node, solve the reduced Laplacian and compare with the pseudoinverse only on small graphs.

[ ]Resistance and heatBrowser
def resistance(A,u,v):
    A=sparse.csr_matrix(A,dtype=float)
    L=sparse.diags(np.asarray(A.sum(axis=1)).ravel())-A
    b=np.zeros(A.shape[0]); b[u]=1; b[v]=-1
    potential=np.r_[spsolve(L[:-1,:-1].tocsc(),b[:-1]),0.]
    return float(potential[u]-potential[v])

for graph,u,v,expected in [(nx.path_graph(6),0,5,5.),(nx.cycle_graph(6),0,3,1.5)]:
    a=nx.to_scipy_sparse_array(graph,nodelist=range(len(graph)),dtype=float,format='csr')
    L=sparse.diags(np.asarray(a.sum(axis=1)).ravel())-a
    b=np.eye(len(graph))[u]-np.eye(len(graph))[v]
    r=resistance(a,u,v); dense=float(b@np.linalg.pinv(L.toarray())@b)
    assert np.isclose(r,dense) and np.isclose(r,expected)
    x=expm_multiply(-1.2*L,b)
    vals,U=np.linalg.eigh(L.toarray()); spectral=U@(np.exp(-1.2*vals)*(U.T@b))
    assert np.allclose(x,spectral)
    print('resistencia:',round(r,6),'calor: error espectral',float(np.max(np.abs(x-spectral))))

Lab: labels on Cora

The next cell requires local Python with torch-geometric, SciPy and scikit-learn. It downloads Cora to a temporary directory on first use. It uses official Planetoid masks: training labels as boundaries and test nodes only for evaluation. The graph is converted to undirected, without self-loops or multiplicity. The method is transductive: it sees the entire structure, including test nodes, but not their labels. Logistic regression sees only training attributes and labels; it predicts on test without edges. These are not equivalent inductive conditions.

A component without labels produces abstention in the harmonic problem; coverage and accuracy among covered test nodes are reported. The restart method produces a score for all, but an unlabeled disconnected component has zero scores and its argmax tie-break is a convention, not information obtained from the graph. Its informative coverage is also reported. Do not tune hyperparameters on test: here they are fixed beforehand and the result describes one split.

[ ]Cora: harmonic, restart and featuresLocal GPU
import tempfile
from pathlib import Path
import numpy as np
from scipy import sparse
from scipy.sparse.csgraph import connected_components
from scipy.sparse.linalg import spsolve
from sklearn.linear_model import LogisticRegression
from threadpoolctl import threadpool_limits
from torch_geometric.datasets import Planetoid
from torch_geometric.utils import to_scipy_sparse_matrix

data=Planetoid(str(Path(tempfile.gettempdir())/'oryon-graph-datasets'/'cora'), 'Cora')[0]
n=data.num_nodes
A=to_scipy_sparse_matrix(data.edge_index,num_nodes=n).tocsr().astype(float)
A=(A+A.T).tocsr(); A.setdiag(0); A.eliminate_zeros(); A.data[:]=1
degree=np.asarray(A.sum(axis=1)).ravel()
train=np.flatnonzero(data.train_mask.numpy()); test=np.flatnonzero(data.test_mask.numpy())
labels=data.y.numpy(); classes=int(labels.max())+1
Y=np.zeros((n,classes)); Y[train,labels[train]]=1
_,component=connected_components(A,directed=False)
covered=np.isin(component,np.unique(component[train]))
known=np.zeros(n,dtype=bool); known[train]=True
unknown=np.flatnonzero(covered & ~known)
L=sparse.diags(degree)-A
F=np.zeros_like(Y); F[train]=Y[train]
F[unknown]=spsolve(L[unknown][:,unknown].tocsc(), A[unknown][:,train]@Y[train])
covered_test=test[covered[test]]
print('nodos/aristas no dirigidas:',n,A.nnz//2,'train/test:',len(train),len(test))
print('armónica: cobertura test',round(len(covered_test)/len(test),4),
      'exactitud cubierta',round(float(np.mean(F[covered_test].argmax(axis=1)==labels[covered_test])),4))

inv=np.divide(1.,np.sqrt(degree),out=np.zeros_like(degree),where=degree>0)
S=sparse.diags(inv)@A@sparse.diags(inv)
rho=.9; Z=Y.copy()
for iteration in range(1000):
    Znew=rho*(S@Z)+(1-rho)*Y
    delta=np.max(np.abs(Znew-Z)); Z=Znew
    if delta<1e-10: break
else: raise RuntimeError('restitución sin converger')
print('restitución: iteraciones',iteration+1,'cobertura informativa',round(float(np.mean(covered[test])),4),
      'exactitud test con desempate',round(float(np.mean(Z[test].argmax(axis=1)==labels[test])),4),
      'exactitud cubierta',round(float(np.mean(Z[covered_test].argmax(axis=1)==labels[covered_test])),4))

features=data.x.numpy()
model=LogisticRegression(max_iter=2000,random_state=0)
with threadpool_limits(limits=1):
    model.fit(features[train],labels[train])
    pred=model.predict(features[test])
print('logística: exactitud test',round(float(np.mean(pred==labels[test])),4),
      'exactitud cubierta',round(float(np.mean(pred[covered[test]]==labels[covered_test])),4))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

In one local execution, the converted graph had 2708 nodes and 5278 edges, with 140 training labels and 1000 test nodes. Harmonic test coverage was 0.941 and accuracy among covered nodes was 0.7598. Restart accuracy was 0.7556 among covered nodes and 0.7130 on all test nodes with the stated tie-break; logistic regression obtained 0.5760 over all test nodes and 0.5824 on the same covered nodes. The 59 abstentions are also part of the result. The comparison uses one split with fixed hyperparameters and does not establish a conclusion for all graphs or seeds.

Exercises

Proof
Prove: Prove that the distribution proportional to degree satisfies detailed balance and is stationary.
0
Finite undirected graph with positive degrees; P_ij = A_ij / d_i.

Step 1 of 2. What is π_i P_ij?

Proof
Prove: Derive the harmonic solution as the energy minimizer with fixed labels.
0
Every component has at least one labeled node, so L_UU is positive definite.

Step 1 of 2. What is the gradient of fᵀLf with respect to unknown entries?

Numeric
What is the effective resistance between endpoints of a path of five unit-resistance edges?
Numeric
What is the effective resistance between opposite nodes of a cycle of six unit-resistance edges?
Quiz
What happens if dangling-node rows stay zero in the iteration without correction?
Code
Implement ppr_push(csr, seed, alpha, eps) for a nonnegative CSR matrix without zero-degree rows, with 0 < alpha ≤ 1 and eps > 0. Return p and r. Initialize r at the seed; while r[i] > eps degree[i], deposit alphar[i] and distribute the rest through the normalized row. Use the first active node; the test checks residual mass and its L1 error bound.
import numpy as np
def ppr_push(csr, seed, alpha, eps):
  pass
Shift+Enter to run

Key ideas

Key idea
Walks, heat and PageRank propagate information over the same graph using different rules and time scales. The spectrum controls relaxation, while the push residual quantifies the portion of PageRank not yet deposited.

Resistance and harmonic interpolation turn connectivity and learning questions into Laplacian systems. Their interpretation and validity depend on connectivity, boundaries and the evaluation protocol.