Algorithmcore
LexRank
Also called lexical PageRank summarization.
Score sentences by the stationary distribution of a random walk on a graph of idf-weighted cosine similarities above a threshold (0.1), with random jumps, found by the power method.
- Time
- O(n N + I n²) expected
- Space
- O(n²) extra
- Where
- I = the number of power method steps; N = the number of tokens; n = the number of sentences
- Model
- Word RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Güneş Erkan, Dragomir R. Radev, 2004
LexRank scores the sentences of a document or of a cluster of documents by their centrality in a similarity graph. Two sentences are joined when the cosine of their tf-idf vectors is above a threshold. A random walk on this graph, with a small chance of jumping to a random sentence at each step, has a unique stationary distribution, and the probability of each sentence in it is its LexRank score. The power method computes it. Güneş Erkan and Dragomir Radev published the method in 2004 as the graph form of eigenvector centrality, the idea behind PageRank. The scores are exact up to the stopping tolerance; their use for picking summary sentences is a heuristic.
In plain words
In a set of news stories about one event, the sentences about the main facts are repeated in many forms. LexRank links two sentences when they use enough of the same informative words. A sentence linked to many other sentences is central, and its score should be high.
Counting links alone gives a vote to every sentence, even to one that only links to unimportant sentences. LexRank instead lets each sentence pass its score to its neighbors, in equal parts, over and over. A sentence is then important when important sentences link to it. A small share of the score is spread over all sentences in each round, so that the result is unique.
The process stops when the scores no longer change. The scores add up to 1. The top sentences form the summary.
The problem
The input is a set of sentences , an idf table, a threshold and a jump probability . For a word and a sentence , let be the number of times occurs in . The idf-modified cosine (equation 2 of the paper) is
with for a collection of documents of which contain . The adjacency matrix has if and 0 otherwise, and . The matrix divides each row of by its sum, the degree. LexRank is the probability vector with
where is the matrix of ones (equation 9 of the paper). In continuous LexRank (Section 3.3), instead. The output is the sentences with the highest .
The algorithm
LEXRANK(S, idf, t, d, ε) ▷ S: n sentences; t = 0.1; d: jump probability- 1
for i ← 1 to n do for j ← 1 to n do - 2
c_ij ← idf-modified cosine of S_i and S_j - 3
A_ij ← 1 if i = j or c_ij > t, else 0 ▷ continuous: A_ij ← c_ij - 4
for each i do deg_i ← Σ_j A_ij; B_ij ← A_ij / deg_i for each j - 5
p ← (1/n, ..., 1/n) - 6
repeat - 7
q_j ← d / n + (1 - d) Σ_i B_ij p_i for each j - 8
δ ← Σ_j |q_j - p_j|; p ← q - 9
until δ < ε - 10
return p
Lines L1 to L4 are Algorithm 3 of the paper, and lines L5 to L10 are its power method, Algorithm 2, applied to the matrix with random jumps. Line L3 keeps the self loop: the cosine of a sentence with itself is 1, so every degree is at least 1 and line L4 never divides by 0. Line L7 is one step of the random walk: with probability it follows an edge of the current sentence, chosen uniformly (or in proportion to the weights in the continuous form), and with probability it jumps to any sentence. The paper reports experiments with from 0.1 to 0.4 and finds 0.1 best.
Example
Four sentences: (1) "the storm hit the coast", (2) "the storm flooded the coast roads", (3) "flooded roads closed schools", (4) "schools reopened after the storm". The idf comes from these four sentences: for "the" and "storm", for "coast", "roads", "flooded" and "schools", and for the rest. The cosines are
| 1 | 2 | 3 | 4 | |
|---|---|---|---|---|
| 1 | 1 | 0.3912 | 0 | 0.0698 |
| 2 | 0.3912 | 1 | 0.3847 | 0.0860 |
| 3 | 0 | 0.3847 | 1 | 0.1236 |
| 4 | 0.0698 | 0.0860 | 0.1236 | 1 |
With the graph is the path 1 - 2 - 3 - 4 with self loops, so the degrees are 2, 3, 3, 2, and the rows of are , , and . With :
| step | ||||
|---|---|---|---|---|
| 0 | 0.25 | 0.25 | 0.25 | 0.25 |
| 1 | 0.214583 | 0.285417 | 0.285417 | 0.214583 |
| 2 | 0.209566 | 0.290434 | 0.290434 | 0.209566 |
| 3 | 0.208855 | 0.291145 | 0.291145 | 0.208855 |
| limit | 43/206 = 0.208738 | 30/103 = 0.291262 | 30/103 | 43/206 |
By symmetry the limit is with and , which gives . Without jumps () the limit is the degree vector over its sum, . Sentences 2 and 3 tie; with the tie rule picks sentence 2. Continuous LexRank breaks the tie: it gives .
Correctness
The matrix is row stochastic, and for all its entries are positive. So the Markov chain is irreducible and aperiodic, and by the Perron-Frobenius theorem it has exactly one stationary distribution; the paper uses this argument. The convergence of the power method has a short direct proof: each step keeps the sum of equal to 1, and the difference to the limit is multiplied by , whose 1-norm is at most . So the error falls at least by the factor per step, and when line L9 stops with change , the error is at most . For a symmetric and , the degree vector divided by its sum is stationary, which ties LexRank to degree centrality (Section 3.1 of the paper). These are theorems; the full proofs are in the proofs file.
That the most central sentences make a good summary is a heuristic. The paper measures it with ROUGE on DUC data.
Proof: LexRank has a unique stationary distribution, and the power method converges to it at rate 1 - dfull
Let be the matrix of lines L1 to L3, with and , and let be with each row divided by its sum (line L4). The rows of are probability vectors, because each row sum of is at least . Fix , let be the matrix of ones and . Line L7 computes when , since . The norm is , and .
Lemma 1. If then .
Proof. , so . Its sum is , because each row of sums to .
Lemma 2. For every with , and .
Proof. has every entry equal to , which gives the first claim. For the second, .
Theorem 1 (existence and uniqueness). There is exactly one with .
Proof. Let . By Lemma 1, maps into itself. For , has sum 0, so by Lemma 2 . Since , is a contraction of the closed set , and the Banach fixed point theorem gives exactly one fixed point. (Equivalently: all entries of are positive, so the chain is irreducible and aperiodic, and the Perron-Frobenius theorem gives the same conclusion. This is the argument of the paper.)
Theorem 2 (rate and stopping rule). Let and . Then . If line L9 stops with , then .
Proof. Each by Lemma 1, so has sum 0, and Lemma 2 gives . Induction gives the first bound, and two distributions are at distance at most 2. For the second, let ; then , so .
Theorem 3 (degree centrality). Let be symmetric and . Then , with , satisfies . If the graph of the nonzero entries of is connected, is the only stationary distribution, and the power method converges to it.
Proof. Let . Then , using . If the graph is connected, the chain is irreducible, and it is aperiodic because . A finite irreducible aperiodic chain has a unique stationary distribution, and applied times to any distribution tends to it as .
Remark (isolated vertex). If row of has only its diagonal entry and column has only its diagonal entry, the fixed point equation gives , so for any .
Remark (output). By Theorem 2 the returned vector is within of in the 1-norm, so two sentences whose exact scores differ by more than that bound are returned in the right order.
Complexity
Line L2 needs the tf vectors of the sentences, built in expected time with hash tables. One cosine takes expected time, so all pairs take time, and the matrices take space. Each power step costs on the dense matrix, or with the edges of the threshold graph, since the jump term adds the same to every entry. Reaching error takes at most steps, about 14 steps per factor of 10 for . In total: time.
Properties
- A probability vector. The scores are positive and sum to 1 (a theorem), so scores from clusters of different sizes are not comparable without rescaling. The paper prints them divided by the largest score.
- Depends on the threshold. A high threshold removes most edges, and the scores tend to . The paper measured that 0.1 gave the best ROUGE-1 among 0.1, 0.2, 0.3 and 0.4 on DUC 2004 Task 2.
- Isolated sentences. A sentence with no edge except its self loop passes all its mass back to itself, so and exactly. In a small graph this can be more than a connected sentence gets: add "the council met on friday" as a fifth sentence to a similar set of storm sentences, and it can outscore the end sentences of a path.
- Symmetric similarity. The graph is undirected. With and a connected graph, LexRank equals degree centrality; the jumps make it differ.
- Idf from a corpus. The paper takes the idf from a large corpus. Computing it from the input sentences, as in the example, gives 0 to a word that occurs in every sentence.
Variants and improvements
- Degree centrality. The degree of each sentence in the threshold graph, which is the case on a connected graph. The paper compares it with LexRank.
- Continuous LexRank. The weights are the cosines themselves, with no threshold (Section 3.3). The paper reports that thresholded LexRank did better than continuous LexRank in its experiments (a measurement).
- TextRank. The same year, Mihalcea and Tarau used a word overlap similarity and the unnormalized PageRank formula.
- Within MEAD. In the paper, LexRank is one feature in the MEAD system, combined with the position and length of the sentence, and followed by a reranker that removes redundant sentences. Without a reranker, two near copies of a central sentence both rank high.
- Biased LexRank. A jump vector that favors sentences similar to a query gives query-focused summaries, as in personalized PageRank.
When to use it
Use LexRank for unsupervised extractive summaries of a cluster of related documents, where a sentence repeated in many forms is likely to be important. Combine it with a redundancy step such as maximal marginal relevance, and with sentence position for news. Compute the idf from a corpus in the same domain. For a single short document, the graph is small and the scores are close to uniform, so the method has little to work with.
Pitfalls
- Two meanings of d. In equation 8 of the paper, is the jump probability and is "typically chosen in the interval [0.1, 0.2]". Its Table 2 says "setting the damping factor to 0.85", which uses the other convention, where 0.85 is the probability of following a link. Writing into line L7 gives a walk that jumps 85 percent of the time, and scores close to uniform.
- No self loop. If line L3 drops the diagonal, a sentence with no edge has degree 0, and line L4 divides by 0.
- Threshold at or above 1. A test for the diagonal too would remove every self loop when . Line L3 keeps separate.
- Column or row. is row stochastic, and line L7 sums over the rows . Using in place of computes another vector, which is not a distribution.
- Plain cosine. The cosine of the raw counts gives stop words most of the weight. Use the idf weights of equation 2.
- Stopping too early. Two scores closer than the error bound can come out in the wrong order. Use a small , or check ties.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/lexrank/. The authors are listed in prov/EFQYD8.jsonl.
"""LexRank of Erkan and Radev (2004), with a threshold or with continuous weights.
Sentences are lists of str tokens; the module does no tokenization, no stop
word removal and no stemming. Words are compared after lower casing.
Similarity: the idf-modified cosine (equation 2 of the paper),
sum_w tf(w, x) tf(w, y) idf(w)^2
/ ( sqrt(sum_w (tf(w, x) idf(w))^2) * sqrt(sum_w (tf(w, y) idf(w))^2) ).
The idf table is given by the caller (the paper computes it from a large
corpus); `idf_from_sentences` uses the sentences themselves as documents,
idf(w) = log(n / n_w). A word missing from the table gets idf 0. A sentence
whose weighted vector is zero has cosine 0 with every other sentence.
Graph: A[i][j] = 1 if the cosine is above the threshold, else 0 (LexRank), or
A[i][j] = the cosine (continuous LexRank). The diagonal is always 1, as the
cosine of a nonzero vector with itself, so no row is empty. B is A with each
row divided by its sum.
Ranking: the stationary distribution of the chain d/n J + (1 - d) B, where d
is the probability of a random jump (equation 8 of the paper writes d for this
jump probability, between 0.1 and 0.2). It is found by the power method from
the uniform vector, stopping when the 1-norm of the change is below eps.
"""
import math
from collections import Counter
from typing import Dict, List, Optional, Sequence, Tuple
Matrix = List[List[float]]
def idf_from_sentences(sentences: Sequence[Sequence[str]]) -> Dict[str, float]:
"""Return idf(w) = log(n / n_w), with each sentence as a document."""
n = len(sentences)
df: Counter = Counter()
for s in sentences:
df.update({w.lower() for w in s})
return {w: math.log(n / c) for w, c in df.items()}
def idf_modified_cosine(x: Sequence[str], y: Sequence[str], idf: Dict[str, float]) -> float:
"""Return the idf-modified cosine of two sentences, 0 if a vector is zero."""
tx = Counter(w.lower() for w in x)
ty = Counter(w.lower() for w in y)
num = sum(tx[w] * ty[w] * idf.get(w, 0.0) ** 2 for w in tx if w in ty)
nx = math.sqrt(sum((c * idf.get(w, 0.0)) ** 2 for w, c in tx.items()))
ny = math.sqrt(sum((c * idf.get(w, 0.0)) ** 2 for w, c in ty.items()))
if nx == 0.0 or ny == 0.0:
return 0.0
return num / (nx * ny)
def lexrank_matrix(
sentences: Sequence[Sequence[str]],
threshold: float = 0.1,
idf: Optional[Dict[str, float]] = None,
continuous: bool = False,
) -> Matrix:
"""Return the row-stochastic matrix B of the sentence graph."""
if idf is None:
idf = idf_from_sentences(sentences)
n = len(sentences)
a = [[0.0] * n for _ in range(n)]
for i in range(n): # @line L1
for j in range(n):
if i == j:
a[i][j] = 1.0
continue
c = idf_modified_cosine(sentences[i], sentences[j], idf) # @line L2
if continuous:
a[i][j] = c
else:
a[i][j] = 1.0 if c > threshold else 0.0 # @line L3
b = []
for i in range(n):
deg = sum(a[i]) # @line L4
b.append([x / deg for x in a[i]])
return b
def power_method(
b: Matrix, d: float = 0.15, eps: float = 1e-8, max_iter: int = 10000
) -> Tuple[List[float], int]:
"""Return the stationary distribution of d/n J + (1 - d) B and the number of steps."""
n = len(b)
if n == 0:
return [], 0
p = [1.0 / n] * n # @line L5
it = 0
while it < max_iter: # @line L6
it += 1
q = [d / n + (1.0 - d) * sum(b[i][j] * p[i] for i in range(n))
for j in range(n)] # @line L7
delta = sum(abs(x - y) for x, y in zip(q, p)) # @line L8
p = q
if delta < eps: # @line L9
break
return p, it # @line L10
def lexrank(
sentences: Sequence[Sequence[str]],
threshold: float = 0.1,
d: float = 0.15,
eps: float = 1e-8,
idf: Optional[Dict[str, float]] = None,
continuous: bool = False,
) -> List[float]:
"""Return the LexRank score of every sentence; the scores sum to 1."""
b = lexrank_matrix(sentences, threshold, idf, continuous)
return power_method(b, d, eps)[0]
def lexrank_summarize(
sentences: Sequence[Sequence[str]],
k: int,
threshold: float = 0.1,
d: float = 0.15,
idf: Optional[Dict[str, float]] = None,
continuous: bool = False,
) -> List[int]:
"""Return the indices of the k best sentences in document order (ties to the earlier one)."""
p = lexrank(sentences, threshold, d, 1e-10, idf, continuous)
order = sorted(range(len(sentences)), key=lambda i: (-p[i], i))
return sorted(order[:k])
test_lexrank.py 174 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/lexrank/. The authors are listed in prov/EFQYD8.jsonl.
import math
import random
from fractions import Fraction
from lexrank import (
idf_from_sentences,
idf_modified_cosine,
lexrank,
lexrank_matrix,
lexrank_summarize,
power_method,
)
def stationary_exact(b, d):
"""Solve p = M^T p with sum(p) = 1 exactly, for M = d/n J + (1 - d) B (Fractions)."""
n = len(b)
m = [[d / n + (1 - d) * b[i][j] for j in range(n)] for i in range(n)]
# Rows of the system: sum_i M[i][j] p_i - p_j = 0 for j < n - 1, and sum p = 1.
rows = []
for j in range(n - 1):
rows.append([m[i][j] - (1 if i == j else 0) for i in range(n)] + [Fraction(0)])
rows.append([Fraction(1)] * n + [Fraction(1)])
for c in range(n):
p = next(r for r in range(c, n) if rows[r][c] != 0)
rows[c], rows[p] = rows[p], rows[c]
for r in range(n):
if r != c and rows[r][c] != 0:
f = rows[r][c] / rows[c][c]
rows[r] = [x - f * y for x, y in zip(rows[r], rows[c])]
return [rows[i][n] / rows[i][i] for i in range(n)]
def page_example():
text = [
"the storm hit the coast",
"the storm flooded the coast roads",
"flooded roads closed schools",
"schools reopened after the storm",
]
return [s.split() for s in text]
def threshold_graph(sentences, t, idf):
n = len(sentences)
return [[1 if i == j or idf_modified_cosine(sentences[i], sentences[j], idf) > t else 0
for j in range(n)] for i in range(n)]
def test_cosine_formula():
idf = {"a": 1.0, "b": 2.0, "c": 0.5}
x = ["a", "b", "b"]
y = ["b", "c"]
num = 2 * 1 * 4.0
nx = math.sqrt(1.0 + (2 * 2.0) ** 2)
ny = math.sqrt(4.0 + 0.25)
assert abs(idf_modified_cosine(x, y, idf) - num / (nx * ny)) < 1e-12
assert abs(idf_modified_cosine(x, x, idf) - 1.0) < 1e-12
assert idf_modified_cosine(["z"], x, idf) == 0.0
assert idf_modified_cosine([], x, idf) == 0.0
def test_page_example():
s = page_example()
idf = idf_from_sentences(s)
assert abs(idf["the"] - math.log(4 / 3)) < 1e-12
assert abs(idf["hit"] - math.log(4)) < 1e-12
assert abs(idf_modified_cosine(s[0], s[1], idf) - 0.3912) < 1e-4
assert abs(idf_modified_cosine(s[1], s[2], idf) - 0.3847) < 1e-4
assert abs(idf_modified_cosine(s[2], s[3], idf) - 0.1236) < 1e-4
assert abs(idf_modified_cosine(s[0], s[3], idf) - 0.0698) < 1e-4
assert idf_modified_cosine(s[0], s[2], idf) == 0.0
b = lexrank_matrix(s, 0.1)
assert b == [[0.5, 0.5, 0.0, 0.0], [1 / 3, 1 / 3, 1 / 3, 0.0],
[0.0, 1 / 3, 1 / 3, 1 / 3], [0.0, 0.0, 0.5, 0.5]]
p, it = power_method(b, 0.15, 1e-8)
want = [Fraction(43, 206), Fraction(30, 103), Fraction(30, 103), Fraction(43, 206)]
assert all(abs(x - float(y)) < 1e-8 for x, y in zip(p, want))
one, _ = power_method(b, 0.15, 0.0, max_iter=1)
step = [Fraction(103, 480), Fraction(137, 480), Fraction(137, 480), Fraction(103, 480)]
assert all(abs(x - float(y)) < 1e-12 for x, y in zip(one, step))
assert lexrank_summarize(s, 1) == [1]
assert lexrank_summarize(s, 2) == [1, 2]
pc = lexrank(s, continuous=True)
assert abs(sum(pc) - 1) < 1e-9 and pc[1] > pc[2] > pc[0] > pc[3]
def test_exact_stationary_threshold():
rng = random.Random(457)
vocab = ["w%d" % i for i in range(7)]
d = Fraction(3, 20)
for _ in range(500):
n = rng.randint(1, 5)
s = [[rng.choice(vocab) for _ in range(rng.randint(0, 5))] for _ in range(n)]
t = rng.choice([0.0, 0.1, 0.2, 0.3])
idf = idf_from_sentences(s)
a = threshold_graph(s, t, idf)
b_exact = [[Fraction(x, sum(row)) for x in row] for row in a]
b = lexrank_matrix(s, t, idf)
assert all(abs(b[i][j] - float(b_exact[i][j])) < 1e-15 for i in range(n) for j in range(n))
p, _ = power_method(b, 0.15, 1e-12)
want = stationary_exact(b_exact, d)
assert abs(sum(want) - 1) == 0
assert all(abs(x - float(y)) < 1e-9 for x, y in zip(p, want))
assert abs(sum(p) - 1) < 1e-12 and all(x > 0 for x in p)
def test_degree_centrality_when_d_is_zero():
# On a connected symmetric graph with self loops, the stationary distribution
# of B is proportional to the degrees.
rng = random.Random(22)
vocab = list("abcde")
done = 0
while done < 150:
n = rng.randint(2, 6)
s = [[rng.choice(vocab) for _ in range(rng.randint(1, 4))] for _ in range(n)]
idf = idf_from_sentences(s)
a = threshold_graph(s, 0.1, idf)
seen, stack = {0}, [0]
while stack:
u = stack.pop()
for v in range(n):
if a[u][v] and v not in seen:
seen.add(v)
stack.append(v)
if len(seen) < n:
continue
done += 1
deg = [sum(row) for row in a]
p, _ = power_method(lexrank_matrix(s, 0.1, idf), 0.0, 1e-13, max_iter=100000)
assert all(abs(x - y / sum(deg)) < 1e-6 for x, y in zip(p, deg))
def test_continuous_rows_and_sum():
rng = random.Random(9)
vocab = ["v%d" % i for i in range(6)]
for _ in range(200):
n = rng.randint(1, 5)
s = [[rng.choice(vocab) for _ in range(rng.randint(0, 5))] for _ in range(n)]
b = lexrank_matrix(s, continuous=True)
for i in range(n):
assert abs(sum(b[i]) - 1) < 1e-12
for j in range(n):
assert b[i][j] >= 0
p = lexrank(s, continuous=True, eps=1e-12)
assert abs(sum(p) - 1) < 1e-9
# The fixed point equation holds.
q = [0.15 / n + 0.85 * sum(b[i][j] * p[i] for i in range(n)) for j in range(n)]
assert all(abs(x - y) < 1e-9 for x, y in zip(p, q))
def test_power_method_rate():
# The 1-norm error shrinks at least by the factor 1 - d per step.
rng = random.Random(5)
vocab = list("abcdef")
for _ in range(100):
s = [[rng.choice(vocab) for _ in range(rng.randint(1, 4))] for _ in range(5)]
b = lexrank_matrix(s, 0.1)
star, _ = power_method(b, 0.15, 1e-14, max_iter=100000)
prev = None
for t in range(1, 8):
p, _ = power_method(b, 0.15, 0.0, max_iter=t)
err = sum(abs(x - y) for x, y in zip(p, star))
if prev is not None:
assert err <= 0.85 * prev + 1e-12
prev = err
def test_empty_input():
assert lexrank([]) == []
assert lexrank_summarize([], 3) == []
History
Erkan and Radev built LexRank on the PageRank work of Brin and Page (1998) and on the centroid method of the MEAD summarizer of Radev and colleagues. They showed that degree and eigenvector centrality on a cosine graph pick better sentences than the centroid method on DUC 2003 and DUC 2004 data. A version called LexPageRank appeared at EMNLP 2004, at the same conference as TextRank, and the full article appeared in JAIR the same year. LexRank became a standard unsupervised baseline for multi-document summarization.
References
- Gunes Erkan and Dragomir R. Radev, LexRank, Graph-based Lexical Centrality as Salience in Text Summarization, Journal of Artificial Intelligence Research 22, 2004, pages 457 to 479, equation 2 (the idf-modified cosine), Section 3.1 (degree centrality), Section 3.2 (the stationary distribution, equations 8 and 9, Algorithms 2 and 3), Section 3.3 (continuous LexRank), Section 5.1 (the thresholds 0.1 to 0.4)
- Mihalcea and Tarau 2004, Section 4 (the related method with a word overlap similarity)
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag EFQYD8 Edit this page History Report an error Markdown