PageRank and Markov Chains
PageRank, the algorithm that made Google's early search results good, ranks web pages by the eigenvector of a huge matrix. Behind it is a Markov chain, a random surfer clicking links, and the method that computes it is the simplest eigenvalue algorithm there is: multiply by the matrix again and again.
Markov chains as matrices
A Markov chain moves between states; from state it goes to state with probability . Collect these in the transition matrix . Each column is a probability distribution (, column sums 1): is column-stochastic. If is the probability distribution of the state at time , then
This is matrix powers again. A stationary distribution is a probability vector with : an eigenvector for eigenvalue 1. Every column-stochastic matrix has eigenvalue 1, because (column sums are 1), so 1 is an eigenvalue of , and and have the same eigenvalues.
The random surfer
Model the web as a directed graph of pages and links. The surfer on page clicks one of its outgoing links uniformly at random. So with the number of links out of , if links to , else 0. The long-run fraction of time spent on each page measures its importance: a page is important if important pages link to it.
Two problems: a page with no outgoing links (a dangling node) makes a zero column, and groups of pages that link only to each other trap the surfer. The fix is teleportation: with probability (the damping factor, classically 0.85) follow a link, otherwise jump to a uniformly random page. The Google matrix is
has all entries positive, so the Perron–Frobenius theorem guarantees that eigenvalue 1 is simple, every other eigenvalue has , and there is a unique stationary vector with positive entries: the PageRank vector.
Power iteration
Start with any probability vector and multiply by repeatedly. Write in eigenvectors of ; then , and since every other term dies like . With , 50 iterations shrink the error by about , 100 iterations by , regardless of how many pages there are. Each step only needs a sparse matrix-vector product, so this scales to billions of pages.
import numpy as np
pages = ["Home", "Blog", "Docs", "About", "Shop"]
links = {0: [1, 2, 4], 1: [0, 2], 2: [0], 3: [0, 2], 4: [0, 1, 2]} # page -> pages it links to
n, alpha = len(pages), 0.85
M = np.zeros((n, n))
for j, outs in links.items():
for i in outs:
M[i, j] = 1 / len(outs)
G = alpha * M + (1 - alpha) / n * np.ones((n, n))
print("column sums of G:", np.round(G.sum(axis=0), 10))
x = np.full(n, 1 / n)
for t in range(1, 101):
x_new = G @ x
if t in (1, 2, 5, 20, 100):
print(f"iter {t:3d}: {np.round(x_new, 4)} change {np.abs(x_new - x).sum():.1e}")
x = x_new
for p, score in sorted(zip(pages, x), key=lambda t: -t[1]):
print(f"{p:6s} {score:.4f}")column sums of G: [1. 1. 1. 1. 1.]
iter 1: [0.4267 0.1433 0.3133 0.03 0.0867] change 6.8e-01
iter 2: [0.3946 0.1754 0.2491 0.03 0.1509] change 1.9e-01
iter 5: [0.3824 0.1795 0.2669 0.03 0.1412] change 2.0e-02
iter 20: [0.3852 0.1785 0.2672 0.03 0.1391] change 1.8e-09
iter 100: [0.3852 0.1785 0.2672 0.03 0.1391] change 0.0e+00
Home 0.3852
Docs 0.2672
Blog 0.1785
Shop 0.1391
About 0.0300
"About" has no incoming links, so it only gets the teleportation share . "Home" is linked from every other page and wins.
Check against the eigenvector
The same vector comes from an eigenvalue solver, and the second-largest eigenvalue modulus shows the convergence rate:
import numpy as np
links = {0: [1, 2, 4], 1: [0, 2], 2: [0], 3: [0, 2], 4: [0, 1, 2]}
n, alpha = 5, 0.85
M = np.zeros((n, n))
for j, outs in links.items():
M[outs, j] = 1 / len(outs)
G = alpha * M + (1 - alpha) / n
w, V = np.linalg.eig(G)
order = np.argsort(-np.abs(w))
pi = np.real(V[:, order[0]]); pi = pi / pi.sum() # scale the eigenvector to sum to 1
print("eigenvalue moduli:", np.round(np.abs(w[order]), 4))
print("stationary vector:", np.round(pi, 4))
print("G pi = pi:", np.allclose(G @ pi, pi))eigenvalue moduli: [1. 0.347 0.347 0.2833 0. ]
stationary vector: [0.3852 0.1785 0.2672 0.03 0.1391]
G pi = pi: True
Here , well below the guaranteed bound , which is why the power iteration above had converged to after only 20 steps: the error shrinks roughly like .
Note: At web scale nobody forms : it is dense. Instead compute with the sparse , which keeps every step proportional to the number of links.
In software
- Search and ranking. PageRank and its variants rank pages, papers (citation graphs), and people in social networks; personalized PageRank teleports to a user's own pages and drives "who to follow" features.
- Recommendation. Random walks on user–item graphs (Pinterest's Pixie, for example) are Markov chains.
- Language models. An n-gram text model is a Markov chain over words; LLM sampling is a (very large) Markov chain over contexts (Sampling).
- Games and simulation. Weather systems, AI behaviour states and procedural music often use Markov transition matrices; matrix powers predict where the system will be after steps.
- Power iteration is also how the top singular vector or eigenvector is computed in many ML libraries.
Exercises
Exercise 1: Two states
A light is ON or OFF each minute. From ON it stays ON with probability 0.9; from OFF it turns ON with probability 0.5. Find the stationary distribution.
Answer
: ON of the time.
Solution
(columns are "from"). gives , so and . With : , .
Exercise 2: Teleportation share
In a graph of pages with , what is the PageRank of a page that nobody links to?
Answer
0.015.
Solution
It only receives the teleportation part: (times the total probability 1).
Exercise 3: How many iterations?
With , about how many power iterations reduce the error by a factor of ?
Answer
About 85.
Solution
gives .
Exercise 4: A cycle (code)
Three pages link in a cycle 0 → 1 → 2 → 0. Compute PageRank with . Why is the answer what it is?
Answer
: the graph is symmetric under rotation, so all pages are equal.
Solution
Rotating the page labels maps to itself, so it also maps the unique stationary vector to itself; that forces equal entries.
import numpy as np
M = np.array([[0, 0, 1], [1, 0, 0], [0, 1, 0]], dtype=float)
G = 0.85 * M + 0.15 / 3
x = np.full(3, 1 / 3)
for _ in range(100):
x = G @ x
print(np.round(x, 4))[0.3333 0.3333 0.3333]
Test yourself
The PageRank vector is…
- the eigenvector of the Google matrix for eigenvalue 1, scaled to sum to 1
- the column sums of the link matrix
- the eigenvector for the smallest eigenvalue
- the number of incoming links of each page
Why add teleportation (damping) to the link matrix?
- To make the computation exact
- To handle dangling nodes and traps, making the stationary vector unique and power iteration converge
- To make symmetric
- To reduce the number of pages
Power iteration converges at a rate governed by…
- the number of pages
- , which is at most for the Google matrix
- the largest entry of
- the determinant of