TExcelTAD
Home › Linear Algebra & Matrix Theory › PageRank and Markov Chains

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 nn states; from state jj it goes to state ii with probability PijP_{ij}. Collect these in the transition matrix PP. Each column is a probability distribution (entries≥0\text{entries} \ge 0, column sums 1): PP is column-stochastic. If xt\mathbf{x}_t is the probability distribution of the state at time tt, then

xt+1=Pxt,soxt=Ptx0\mathbf{x}_{t+1} = P\mathbf{x}_t, \qquad \text{so} \qquad \mathbf{x}_t = P^t \mathbf{x}_0

This is matrix powers again. A stationary distribution is a probability vector π\pi with Pπ=πP\pi = \pi: an eigenvector for eigenvalue 1. Every column-stochastic matrix has eigenvalue 1, because 1TP=1T\mathbf{1}^T P = \mathbf{1}^T (column sums are 1), so 1 is an eigenvalue of PTP^T, and PP and PTP^T have the same eigenvalues.

The random surfer

Model the web as a directed graph of pages and links. The surfer on page jj clicks one of its outgoing links uniformly at random. So with L(j)L(j) the number of links out of jj, Mij=1/L(j)M_{ij} = 1/L(j) if jj links to ii, 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 α\alpha (the damping factor, classically 0.85) follow a link, otherwise jump to a uniformly random page. The Google matrix is

G=αM+(1−α)/n⋅11T(dangling columns of M replaced by 1/n first)G = \alpha M + (1 - \alpha)/n \cdot \mathbf{1}\mathbf{1}^T \qquad \text{(dangling columns of } M \text{ replaced by } 1/n \text{ first)}

GG has all entries positive, so the Perron–Frobenius theorem guarantees that eigenvalue 1 is simple, every other eigenvalue has ∣λ∣≤α\lvert \lambda \rvert \le \alpha, and there is a unique stationary vector with positive entries: the PageRank vector.

Power iteration

Start with any probability vector and multiply by GG repeatedly. Write x0=π+∑ciwi\mathbf{x}_0 = \pi + \sum c_i \mathbf{w}_i in eigenvectors of GG; then Gtx0=π+∑ciλitwiG^t \mathbf{x}_0 = \pi + \sum c_i \lambda_i^t \mathbf{w}_i, and since ∣λi∣≤α<1\lvert \lambda_i \rvert \le \alpha < 1 every other term dies like αt\alpha^t. With α=0.85\alpha = 0.85, 50 iterations shrink the error by about 0.8550≈3⋅10−40.85^{50} \approx 3 \cdot 10^{-4}, 100 iterations by 10−710^{-7}, regardless of how many pages there are. Each step only needs a sparse matrix-vector product, so this scales to billions of pages.

python · try it yourself
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 (1−α)/n=0.03(1 - \alpha)/n = 0.03. "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:

python · try it yourself
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 ∣λ2∣≈0.347\lvert \lambda_2 \rvert \approx 0.347, well below the guaranteed bound α=0.85\alpha = 0.85, which is why the power iteration above had converged to 10−910^{-9} after only 20 steps: the error shrinks roughly like 0.347t0.347^t.

Note: At web scale nobody forms GG: it is dense. Instead compute Gx=αMx+(1−α)/n⋅(sum of x)⋅1G\mathbf{x} = \alpha M\mathbf{x} + (1 - \alpha)/n \cdot (\text{sum of } \mathbf{x}) \cdot \mathbf{1} with the sparse MM, 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 tt 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

π=(56,16)\pi = \left(\frac{5}{6}, \frac{1}{6}\right): ON 56\frac{5}{6} of the time.

Solution

P=[0.90.50.10.5]P = \begin{bmatrix} 0.9 & 0.5 \\ 0.1 & 0.5 \end{bmatrix} (columns are "from"). Pπ=πP\pi = \pi gives 0.9a+0.5b=a0.9a + 0.5b = a, so 0.5b=0.1a0.5b = 0.1a and a=5ba = 5b. With a+b=1a + b = 1: a=56a = \frac{5}{6}, b=16b = \frac{1}{6}.

Exercise 2: Teleportation share

In a graph of n=10n = 10 pages with α=0.85\alpha = 0.85, what is the PageRank of a page that nobody links to?

Answer

0.015.

Solution

It only receives the teleportation part: (1−α)/n=0.15/10=0.015(1 - \alpha)/n = 0.15/10 = 0.015 (times the total probability 1).

Exercise 3: How many iterations?

With α=0.85\alpha = 0.85, about how many power iterations reduce the error by a factor of 10610^6?

Answer

About 85.

Solution

0.85t=10−60.85^t = 10^{-6} gives t=6ln⁡10/(−ln⁡0.85)≈13.8155/0.1625≈85t = 6 \ln 10 / (-\ln 0.85) \approx 13.8155/0.1625 \approx 85.

Exercise 4: A cycle (code)

Three pages link in a cycle 0 → 1 → 2 → 0. Compute PageRank with α=0.85\alpha = 0.85. Why is the answer what it is?

Answer

(13,13,13)\left(\frac{1}{3}, \frac{1}{3}, \frac{1}{3}\right): the graph is symmetric under rotation, so all pages are equal.

Solution

Rotating the page labels maps GG to itself, so it also maps the unique stationary vector to itself; that forces equal entries.

python · try it yourself
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…

  1. the eigenvector of the Google matrix for eigenvalue 1, scaled to sum to 1
  2. the column sums of the link matrix
  3. the eigenvector for the smallest eigenvalue
  4. the number of incoming links of each page

Why add teleportation (damping) to the link matrix?

  1. To make the computation exact
  2. To handle dangling nodes and traps, making the stationary vector unique and power iteration converge
  3. To make GG symmetric
  4. To reduce the number of pages

Power iteration converges at a rate governed by…

  1. the number of pages
  2. ∣λ2∣/∣λ1∣\lvert \lambda_2 \rvert / \lvert \lambda_1 \rvert, which is at most α\alpha for the Google matrix
  3. the largest entry of GG
  4. the determinant of GG