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
- 25Combinatorial graph LaplacianNormalized LaplaciansGraph Dirichlet energyAlgebraic connectivityConductance
- 26Stationary distributionCommunicating classes and irreducibilityPeriodicity and aperiodicity
- 02Moore-Penrose pseudoinverseMatrix exponential
- 09Power iteration
- 11Kernel trickCommon kernels and construction rules
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, and is row-stochastic. For column distributions, . In a random walk on a graph,
Summing over gives . 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 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.
To measure mixing and spectral gap, use . By similarity, and have the same eigenvalues. If are those of , those of are , all in . With and starting node ,
The bound follows from Cauchy-Schwarz and contraction in 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 . Laziness is essential here: without it, eigenvalue on a bipartite graph maintains oscillation even if .
To obtain a sufficient bound on , require the last term to be at most : it suffices that , 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 with has solution . If , heat-kernel diffusion multiplies coefficient by . High-frequency modes decay faster. The sum of temperatures is conserved because ; on a connected graph the signal tends to its uniform mean. With a normalized Laplacian or a continuous-time walk, conventions and equilibrium change.
The matrix is also a diffusion kernel: it is symmetric positive definite for finite , since its eigenvalues are . An entry 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 is a scale, not a number of integer layers. For near zero, 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.
PageRank and local search
In a directed graph, rows with no outgoing edges are dangling. Before iteration, replace them with a distribution summing to 1 (or another stated dangling-node distribution). With as teleportation probability and , PageRank satisfies
The update is an contraction by factor ; therefore a unique fixed point exists even if is concentrated at one node. Some texts call by the name : compare equations before comparing numbers. If dangling rows remain zero, iteration loses mass and does not implement this chain.
Personalized PageRank takes to explore around a seed. The series mixes geometrically distributed lengths with mean . A large favors short walks, although mass within a particular radius depends on structure.
The series explains the endpoint : no graph step occurs and the distribution stays at . At the other extreme, as approaches zero in a connected aperiodic graph, longer lengths receive more weight and the distribution approaches stationarity. Substituting into the equation does not guarantee uniqueness on every directed graph: contraction requires positive teleportation.
In push we maintain , . Processing deposits in and sends to its neighbors. The invariant is , with PPR extended linearly to mass vectors. Since and is stochastic, : residual mass is exactly the deposited vector’s error. The criterion does not by itself imply total error ; it does guarantee . 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 , effective resistance is
It equals the potential difference when one unit of current is injected at and removed at . 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 ; in an unweighted graph . A path of five unit resistors has resistance 5; in a six-cycle, two paths of three in parallel give .
In harmonic label propagation, values are fixed on labeled nodes and energy is minimized over unknown nodes. Separating and , the first-order equation is . If every component has at least one label, is positive definite and
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.
A soft alternative from Zhou and colleagues iterates , with and . Returning to 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.
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 . 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 . On a longer path, one can count processed support and compare error with residual mass; this is a structured realization, not a general benchmark.
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 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.
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([email protected](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.
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)@[email protected](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))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
Step 1 of 2. What is π_i P_ij?
Step 1 of 2. What is the gradient of fᵀLf with respect to unknown entries?
import numpy as np
def ppr_push(csr, seed, alpha, eps):
passKey ideas
Resistance and harmonic interpolation turn connectivity and learning questions into Laplacian systems. Their interpretation and validity depend on connectivity, boundaries and the evaluation protocol.