Algorithmcore
TextRank
Also called TextRank keyword extraction.
Rank sentences or words by weighted PageRank with d = 0.85 on a graph whose edges weigh word overlap or co-occurrence, then extract the top ones. A heuristic with no training.
- Time
- O(n N + I n²) expected
- Space
- O(n²) extra
- Where
- I = the number of iterations; N = the number of tokens; n = the number of sentences
- Model
- Word RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Rada Mihalcea, Paul Tarau, 2004
TextRank builds a graph from one text and ranks its vertices with a weighted form of PageRank. For summarization the vertices are the sentences, and the weight of an edge is the number of words two sentences share, divided by the sum of the logarithms of their lengths. For keyword extraction the vertices are words, joined when they occur close together. The best sentences form an extractive summary, and the best words form the keywords. Rada Mihalcea and Paul Tarau published the method in 2004. The ranking is a fixed point that the iteration finds to any precision; its use as a summarizer is a heuristic whose value is measured.
In plain words
Think of the sentences of an article as people at a meeting. Two sentences that use the same words "agree" with each other, and the more words they share, the stronger the link. A sentence that many others agree with is probably about the main topic.
TextRank turns this into numbers. Each sentence starts with the score 1. In each round, a sentence collects a share of the scores of the sentences linked to it, in proportion to the link weights, and a fixed amount of 0.15. After some rounds the scores stop changing. The sentences with the highest scores make the summary.
For keywords, the same scoring runs on words. Two nouns or adjectives that stand next to each other are linked, and the words with the highest scores become the keywords.
The problem
The input is a text split into sentences , each a list of tokens, and a number . The similarity of two sentences is
where the numerator counts distinct shared words and is the number of tokens. Set where the numerator is 0 or the denominator is not positive, and . The graph is undirected, so . Let . The TextRank scores are the solution of
with the damping factor . The output is the sentences with the highest scores, in document order. In matrix form, with (and 0 for ), the scores solve .
The algorithm
TEXTRANK(S, d, ε, k) ▷ S: n sentences; d = 0.85, ε = 0.0001 in the paper- 1
for each pair i ≠ j do w_ij ← shared words / (log |S_i| + log |S_j|), or 0 - 2
for each j do out_j ← Σ_k w_jk - 3
for each i do WS(i) ← 1 - 4
repeat - 5
for each i do new(i) ← (1 - d) + d · Σ_(j : w_ji > 0) (w_ji / out_j) · WS(j) - 6
δ ← Σ_i |new(i) - WS(i)| - 7
WS ← new - 8
until δ < ε - 9
return the k sentences with the largest WS, in document order
Line L1 builds the graph and line L2 the total weight at each vertex. Lines L4 to L8 are the iteration of the weighted PageRank formula of Section 2.2 of the paper, started at 1 as in the paper. Line L6 measures the change in the 1-norm. The paper stops at a threshold of 0.0001 and reports that this takes 20 to 30 rounds. Line L9 sorts by score and breaks ties by the earlier sentence.
Keywords. Section 3.1 of the paper runs the same ranking on words. A syntactic filter keeps the candidate words (nouns and adjectives worked best). Two candidates are joined by an unweighted, undirected edge when they occur within a window of words, with from 2 to 10 (2 worked best). After the ranking, the top third of the vertices are marked in the text, and runs of adjacent marked words are joined into one keyword, as "Matlab code" in the paper. The paper does not say whether the window counts the words that the filter removed; the code counts positions in the filtered sequence, so window 2 joins two candidates with only non-candidates between them.
Example
Take four sentences: (1) "the cat sat on the mat", (2) "the dog sat on the log", (3) "a cat and a dog met", (4) "birds fly south". Sentences 1 and 2 share the, sat and on, so . Sentences 1 and 3 share cat, and 2 and 3 share dog, so . Sentence 4 shares no word with any other. So , , and .
| round | WS(1) | WS(2) | WS(3) | WS(4) |
|---|---|---|---|---|
| 0 | 1 | 1 | 1 | 1 |
| 1 | 1.212500 | 1.212500 | 0.575000 | 0.15 |
| 2 | 1.167344 | 1.167344 | 0.665312 | 0.15 |
| 3 | 1.176939 | 1.176939 | 0.646121 | 0.15 |
| 7 | 1.175261 | 1.175261 | 0.649478 | 0.15 |
| fixed point | 1.175258 | 1.175258 | 0.649485 | 0.15 |
In round 1, sentence 1 gets , since sentence 2 gives three quarters of its weight to sentence 1 and sentence 3 gives half. The fixed point solves and , so . With the loop stops after 7 rounds. For the summary is sentences 1 and 2. The isolated sentence 4 keeps .
Correctness
Three facts make the method well defined. These are theorems; the full proofs are in the proofs file.
- Unique fixed point. Every column of sums to 1 (for a vertex with edges) or 0 (for an isolated vertex), so , and the map is a contraction with factor in the 1-norm. By the Banach fixed point theorem it has exactly one fixed point , and the iteration converges to it from any start.
- Rate and stopping rule. The error shrinks by the factor each round, and when line L8 stops with change , the error is at most in the 1-norm, which is for .
- Mass. If no vertex is isolated, . An isolated vertex has score .
Whether the high-scoring sentences make a good summary is not a theorem. TextRank does not optimize coverage or redundancy; it is a centrality heuristic, and its quality is measured with ROUGE.
Proof: The TextRank iteration converges to the unique fixed point, with a bound for its stopping rulefull
Let be the weight matrix built by line L1. It is symmetric, nonnegative and has a zero diagonal. Let (line L2), and let be the matrix with when and otherwise. Fix . Line L5 computes from , because the terms with are 0. The norm is .
Lemma 1 (column sums). Column of sums to 1 if and to 0 otherwise. Hence for every vector .
Proof. If , then . Otherwise the column is 0. Since , .
Lemma 2 (contraction). .
Proof. ; apply Lemma 1.
Theorem 1 (fixed point and convergence). has exactly one fixed point . The sequence , of lines L3 to L7 satisfies .
Proof. with the 1-norm is complete, and is a contraction with factor by Lemma 2, so the Banach fixed point theorem gives one fixed point and convergence from any start. The rate follows by induction: . Equivalently, is invertible (its Neumann series converges), and .
Theorem 2 (stopping rule). If line L8 stops after computing with , then .
Proof. Let . By Lemma 2, . Rearranging gives .
Theorem 3 (mass). Let be the set of isolated vertices () and the rest. Then for , and .
Proof. For , for every , so row of is 0 and the fixed point equation gives . For , row of has nonzero entries only in columns with , and those are in . Summing the fixed point equation over gives . For , every with has , so , and by Lemma 1 the inner sum is 1. So satisfies , which gives .
Remark (scale). Replacing by for a constant leaves every unchanged, so the scores do not depend on the base of the logarithm in line L1.
Remark (output). Line L9 sorts the indices by (score descending, index ascending) and returns the first sorted by index, which is the set of the definition. The scores used are those of the final iterate, which are within the bound of Theorem 2 of ; since the errors of two coordinates add up to at most that bound, two sentences can be ranked in the wrong order only if their true scores differ by at most the bound. A smaller makes this gap as small as needed.
Remark (keywords). The keyword graph is the same construction with weights 0 or 1, so Theorems 1 to 3 hold for it too.
Complexity
Line L1 compares all pairs. With a hash set of the words of each sentence, one pair costs expected time, so the graph takes expected time for tokens and space. Each round of lines L5 to L7 takes time on the dense matrix, or on a list of the nonzero edges. To get the error below from a start with error takes rounds, about 14.2 rounds per factor of 10 for . This is a worst case bound; the example above needed 7 rounds. In total: time.
Properties
- Unsupervised. It needs no training data and no corpus, only the text.
- Scale invariance. The scores depend on the weights only through , so multiplying every weight by the same constant changes nothing. In particular the base of the logarithm does not matter.
- Not normalized. With this form, the scores average 1 over the vertices that have edges; they are not probabilities. The variant with in place of divides every score by , so it gives the same ranking, and scores that sum to 1 when no vertex is isolated.
- Length. The logarithms in the denominator damp the advantage of long sentences, but long sentences still share more words and tend to score higher.
- Redundancy. Two near copies of the same central sentence both score high, and both can be picked.
- Undirected graphs worked best. In the keyword experiments, forward and backward directed graphs gave lower scores than the undirected graph (a measurement).
Variants and improvements
- LexRank. Erkan and Radev (2004) published a close method at the same time, with an idf-weighted cosine similarity, a threshold on the edges and the stationary distribution of a random walk.
- Keyword extraction. The word graph of Section 3.1, with a part of speech filter and the joining of adjacent keywords. On 500 Inspec abstracts with window 2, TextRank had precision 31.2, recall 43.1 and F-measure 36.2, against 25.2, 51.7 and 33.9 for the best supervised system of Hulth (2003) (measurements, in percent).
- Other similarities. Later systems replace the word overlap with BM25, with tf-idf cosine, or with the cosine of sentence embeddings.
- Biased ranking. With a nonuniform restart vector the ranking becomes personalized PageRank, which can favor sentences near a query or at the start of the text.
- Redundancy control. Selecting the sentences one at a time with maximal marginal relevance avoids near duplicates.
When to use it
Use TextRank as an unsupervised baseline for extractive summaries or keywords of a single document, when you have no training data. On 567 DUC 2002 news articles with 100-word summaries, it scored 0.4708 in ROUGE unigram recall with no stemming, against 0.4814 for the best of 15 systems and 0.4599 for the baseline of the first sentences (measurements, Table 2). It would rank third in that column. For news with a strong lead structure, compare it with the first sentences of the article before you use it.
Pitfalls
- Zero denominator. Two one-word sentences give in line L1. Treat the weight as 0, or drop one-word sentences before you build the graph.
- Dangling vertex. A sentence with no shared words has . Line L5 must skip it as a source; dividing by there fails.
- Stop words. If the stop words are kept, "the" and "of" link almost every pair of sentences, and the ranking mostly measures sentence length. Remove them or weight the words.
- Max-norm and 1-norm. A stopping test with the largest change per vertex instead of the sum in line L6 stops earlier for large . The error bound above holds for the 1-norm.
- The meaning of d. In this formula is the weight of the links, and is the restart. Some papers on LexRank use for the restart weight. Check the formula, not only the number.
- Ties. Line L9 needs a fixed tie rule; with symmetric sentences, as in the example, two scores can be equal.
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/textrank/. The authors are listed in prov/FCW45A.jsonl.
"""TextRank of Mihalcea and Tarau (2004): sentence extraction and keywords.
Sentences are lists of str tokens; the module does no tokenization, no stop
word removal and no part of speech tagging. Words are compared after lower
casing.
The ranking is the weighted PageRank of the paper,
WS(i) = (1 - d) + d * sum over j of w[j][i] / out(j) * WS(j),
with out(j) the sum of the weights on the edges of j, d = 0.85 and all scores
starting at 1. A vertex with no edges keeps the score 1 - d. The iteration
stops when the 1-norm of the change is below eps.
Sentence similarity: the number of distinct words that two sentences share,
divided by log |S_i| + log |S_j| (natural logarithm, lengths in tokens). The
weight is 0 when the sentences share no word or when the denominator is not
positive (two one-word sentences, or an empty sentence).
"""
import math
from typing import Callable, Dict, List, Sequence, Tuple
Matrix = List[List[float]]
def overlap_similarity(a: Sequence[str], b: Sequence[str]) -> float:
"""Return |a and b| / (log |a| + log |b|), or 0 where it is not defined."""
if not a or not b:
return 0.0
common = len({w.lower() for w in a} & {w.lower() for w in b})
den = math.log(len(a)) + math.log(len(b))
if common == 0 or den <= 0.0:
return 0.0
return common / den
def similarity_matrix(sentences: Sequence[Sequence[str]]) -> Matrix:
"""Return the symmetric weight matrix of the sentence graph, with a zero diagonal."""
n = len(sentences)
w = [[0.0] * n for _ in range(n)]
for i in range(n):
for j in range(i + 1, n):
w[i][j] = w[j][i] = overlap_similarity(sentences[i], sentences[j]) # @line L1
return w
def weighted_pagerank(
w: Matrix, d: float = 0.85, eps: float = 1e-4, max_iter: int = 1000
) -> Tuple[List[float], int]:
"""Iterate the weighted PageRank of TextRank on the weight matrix w.
w[j][i] is the weight of the edge from j to i. Returns the scores and the
number of iterations.
"""
n = len(w)
out = [sum(row) for row in w] # @line L2
ws = [1.0] * n # @line L3
it = 0
while it < max_iter: # @line L4
it += 1
new = []
for i in range(n):
s = 0.0
for j in range(n):
if w[j][i] > 0.0:
s += w[j][i] / out[j] * ws[j]
new.append((1.0 - d) + d * s) # @line L5
delta = sum(abs(x - y) for x, y in zip(new, ws)) # @line L6
ws = new # @line L7
if delta < eps: # @line L8
break
return ws, it
def textrank_scores(
sentences: Sequence[Sequence[str]], d: float = 0.85, eps: float = 1e-4
) -> List[float]:
"""Return the TextRank score of every sentence."""
return weighted_pagerank(similarity_matrix(sentences), d, eps)[0]
def textrank_summarize(
sentences: Sequence[Sequence[str]], k: int, d: float = 0.85, eps: float = 1e-4
) -> List[int]:
"""Return the indices of the k best sentences in document order (ties to the earlier one)."""
ws = textrank_scores(sentences, d, eps)
order = sorted(range(len(sentences)), key=lambda i: (-ws[i], i))
return sorted(order[:k]) # @line L9
def cooccurrence_graph(
tokens: Sequence[str], is_candidate: Callable[[str], bool], window: int = 2
) -> Tuple[List[str], Matrix]:
"""Build the unweighted keyword graph.
The candidates are the tokens that pass the filter, lower cased, in order.
Two candidates are joined when they occur fewer than `window` positions
apart in that filtered sequence (window = 2 joins neighbours).
"""
seq = [t.lower() for t in tokens if is_candidate(t)]
words: List[str] = []
index: Dict[str, int] = {}
for t in seq:
if t not in index:
index[t] = len(words)
words.append(t)
n = len(words)
w = [[0.0] * n for _ in range(n)]
for i in range(len(seq)):
for j in range(i + 1, min(i + window, len(seq))):
a, b = index[seq[i]], index[seq[j]]
if a != b:
w[a][b] = w[b][a] = 1.0
return words, w
def textrank_keywords(
tokens: Sequence[str],
is_candidate: Callable[[str], bool],
window: int = 2,
d: float = 0.85,
eps: float = 1e-4,
) -> List[str]:
"""Return the keywords of a text: the top third of the vertices, with adjacent ones joined.
The top T = max(1, n // 3) vertices are marked in the text, and each maximal
run of adjacent marked tokens becomes one keyword. Keywords are returned in
order of first occurrence, without repeats.
"""
words, w = cooccurrence_graph(tokens, is_candidate, window)
if not words:
return []
ws, _ = weighted_pagerank(w, d, eps)
t = max(1, len(words) // 3)
order = sorted(range(len(words)), key=lambda i: (-ws[i], i))
top = {words[i] for i in order[:t]}
out: List[str] = []
run: List[str] = []
for tok in list(tokens) + [""]:
low = tok.lower()
if tok and is_candidate(tok) and low in top:
run.append(low)
else:
if run:
phrase = " ".join(run)
if phrase not in out:
out.append(phrase)
run = []
return out
test_textrank.py 170 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/textrank/. The authors are listed in prov/FCW45A.jsonl.
import math
import random
from textrank import (
cooccurrence_graph,
overlap_similarity,
similarity_matrix,
textrank_keywords,
textrank_scores,
textrank_summarize,
weighted_pagerank,
)
def solve(a, b):
"""Solve a x = b by Gaussian elimination with partial pivoting."""
n = len(a)
m = [row[:] + [b[i]] for i, row in enumerate(a)]
for c in range(n):
p = max(range(c, n), key=lambda r: abs(m[r][c]))
m[c], m[p] = m[p], m[c]
for r in range(n):
if r != c and m[r][c] != 0.0:
f = m[r][c] / m[c][c]
for k in range(c, n + 1):
m[r][k] -= f * m[c][k]
return [m[i][n] / m[i][i] for i in range(n)]
def exact_scores(w, d):
"""The fixed point of WS = (1 - d) + d M WS, from the linear system (I - d M) WS = (1 - d) 1."""
n = len(w)
out = [sum(row) for row in w]
a = [[(1.0 if i == j else 0.0) - (d * w[j][i] / out[j] if out[j] > 0 else 0.0)
for j in range(n)] for i in range(n)]
return solve(a, [1.0 - d] * n)
def page_example():
text = [
"the cat sat on the mat",
"the dog sat on the log",
"a cat and a dog met",
"birds fly south",
]
return [s.split() for s in text]
def test_similarity_formula():
a = "the cat sat on the mat".split()
b = "the dog sat on the log".split()
# Shared distinct words: the, sat, on.
assert abs(overlap_similarity(a, b) - 3 / (2 * math.log(6))) < 1e-12
assert overlap_similarity(a, "birds fly south".split()) == 0.0
# Two one-word sentences: the denominator is log 1 + log 1 = 0.
assert overlap_similarity(["sun"], ["sun"]) == 0.0
assert overlap_similarity([], ["sun"]) == 0.0
# Case is ignored, and repeats count once in the numerator.
assert abs(overlap_similarity(["The", "the"], ["the", "x"]) - 1 / (2 * math.log(2))) < 1e-12
def test_page_example():
s = page_example()
w = similarity_matrix(s)
assert abs(w[0][1] - 0.837166) < 1e-6
assert abs(w[0][2] - 0.279055) < 1e-6
assert abs(w[1][2] - 0.279055) < 1e-6
assert all(w[3][j] == 0.0 for j in range(4))
# By symmetry WS = (x, x, y, 0.15) with x = 0.15 + 0.85 (3/4 x + 1/2 y) and
# y = 0.15 + 0.85 (1/4 x + 1/4 x), so x = 0.21375 / 0.181875.
x = 0.21375 / 0.181875
y = 0.15 + 0.425 * x
ws, it = weighted_pagerank(w, 0.85, 1e-4)
assert it == 7
assert all(abs(a - b) < 1e-4 for a, b in zip(ws, [x, x, y, 0.15]))
assert abs(x - 1.175258) < 1e-6 and abs(y - 0.649485) < 1e-6
first, _ = weighted_pagerank(w, 0.85, 0.0, max_iter=1)
assert all(abs(a - b) < 1e-12 for a, b in zip(first, [1.2125, 1.2125, 0.575, 0.15]))
assert textrank_summarize(s, 2) == [0, 1]
def test_log_base_does_not_matter():
# Scaling every weight by the same factor leaves w[j][i] / out(j) unchanged.
s = page_example()
w = similarity_matrix(s)
w10 = [[x * math.log(10) for x in row] for row in w]
a, _ = weighted_pagerank(w, 0.85, 1e-12)
b, _ = weighted_pagerank(w10, 0.85, 1e-12)
assert all(abs(x - y) < 1e-12 for x, y in zip(a, b))
def test_page_example_unequal():
s = page_example()
s[2] = "a cat and a dog met on the mat".split()
ws = textrank_scores(s, 0.85, 1e-12)
ex = exact_scores(similarity_matrix(s), 0.85)
assert all(abs(x - y) < 1e-9 for x, y in zip(ws, ex))
assert textrank_summarize(s, 1) == [0]
def test_fixed_point_and_sum():
rng = random.Random(2004)
vocab = ["w%d" % i for i in range(8)]
for _ in range(500):
n = rng.randint(1, 6)
s = [[rng.choice(vocab) for _ in range(rng.randint(0, 6))] for _ in range(n)]
w = similarity_matrix(s)
for i in range(n):
assert w[i][i] == 0.0
for j in range(n):
assert w[i][j] == w[j][i] >= 0.0
d = rng.choice([0.5, 0.85, 0.9])
ws, it = weighted_pagerank(w, d, 1e-11)
ex = exact_scores(w, d)
assert all(abs(x - y) < 1e-8 for x, y in zip(ws, ex))
# Columns of M sum to 1 for vertices with edges, so the scores sum to n
# when no vertex is isolated; an isolated vertex keeps 1 - d.
iso = [i for i in range(n) if sum(w[i]) == 0.0]
for i in iso:
assert abs(ws[i] - (1 - d)) < 1e-12
if not iso:
assert abs(sum(ws) - n) < 1e-8
assert all(x >= 1 - d - 1e-12 for x in ws)
def test_stopping_rule_bound():
# After a stop with change delta, the 1-norm error is at most d / (1 - d) * delta.
rng = random.Random(7)
vocab = list("abcdefg")
for _ in range(200):
s = [[rng.choice(vocab) for _ in range(rng.randint(2, 6))] for _ in range(5)]
w = similarity_matrix(s)
eps = 1e-3
ws, _ = weighted_pagerank(w, 0.85, eps)
ex = exact_scores(w, 0.85)
err = sum(abs(x - y) for x, y in zip(ws, ex))
assert err <= 0.85 / 0.15 * eps + 1e-12
def test_cooccurrence_graph_against_brute_force():
rng = random.Random(11)
vocab = ["n%d" % i for i in range(5)] + ["of", "the"]
cand = lambda t: not t.lower() in ("of", "the")
for _ in range(300):
toks = [rng.choice(vocab) for _ in range(rng.randint(0, 12))]
win = rng.randint(2, 5)
words, w = cooccurrence_graph(toks, cand, win)
seq = [t.lower() for t in toks if cand(t)]
assert sorted(words) == sorted(set(seq))
for a in range(len(words)):
for b in range(len(words)):
near = any(seq[i] == words[a] and seq[j] == words[b] and 0 < abs(i - j) < win
for i in range(len(seq)) for j in range(len(seq)))
assert (w[a][b] == 1.0) == (near and a != b)
def test_keywords_join_adjacent():
toks = "Matlab code for plotting ambiguity functions".split()
cand = lambda t: t.lower() in {"matlab", "code", "plotting", "ambiguity", "functions"}
kw = textrank_keywords(toks, cand, window=2)
# Five vertices on a path; T = 1, the top vertex is the second one (code).
assert kw == ["code"]
toks2 = "linear constraints over natural numbers and linear constraints".split()
cand2 = lambda t: t.lower() in {"linear", "constraints", "natural", "numbers"}
kw2 = textrank_keywords(toks2, cand2, window=2)
assert all(k in ("linear", "constraints", "linear constraints", "natural", "numbers") for k in kw2)
assert textrank_keywords([], cand2) == []
History
PageRank (Brin and Page, 1998) ranked web pages by the stationary distribution of a random surfer. In 2004 two groups applied the same idea to text: Rada Mihalcea and Paul Tarau at EMNLP with TextRank, for keywords and sentences, and Güneş Erkan and Dragomir Radev in JAIR with LexRank, for multi-document summaries. TextRank's keyword method became a standard baseline for unsupervised keyphrase extraction, and graph ranking of sentences remained a common unsupervised baseline in summarization research before neural methods took over.
References
- Mihalcea and Tarau 2004, Section 2.2 (the weighted score with d = 0.85), Section 3.1 (keyword extraction, the window, the filter, a third of the vertices, Table 1), Section 4.1 (the sentence similarity), Section 4.2 (DUC 2002, Table 2)
- 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, Section 3 (the related method on a cosine similarity graph)
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 FCW45A Edit this page History Report an error Markdown