Algorithm Search⌘K

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
Properties
deterministicnot exactofflineiterative
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 S1,…,SnS_1, \ldots, S_n, each a list of tokens, and a number kk. The similarity of two sentences is

wij=∣{v:v∈Si and v∈Sj}∣log⁡∣Si∣+log⁡∣Sj∣,i≠j,w_{ij} = \frac{|\{ v : v \in S_i \text{ and } v \in S_j \}|}{\log |S_i| + \log |S_j|}, \qquad i \ne j,

where the numerator counts distinct shared words and ∣Si∣|S_i| is the number of tokens. Set wij=0w_{ij} = 0 where the numerator is 0 or the denominator is not positive, and wii=0w_{ii} = 0. The graph is undirected, so wij=wjiw_{ij} = w_{ji}. Let outj=∑kwjk\mathrm{out}_j = \sum_k w_{jk}. The TextRank scores are the solution of

WS(i)=(1−d)+d∑j:wji>0wjioutjWS(j),i=1,…,n,WS(i) = (1 - d) + d \sum_{j : w_{ji} > 0} \frac{w_{ji}}{\mathrm{out}_j} WS(j), \qquad i = 1, \ldots, n,

with the damping factor d=0.85d = 0.85. The output is the kk sentences with the highest scores, in document order. In matrix form, with Mij=wji/outjM_{ij} = w_{ji} / \mathrm{out}_j (and 0 for outj=0\mathrm{out}_j = 0), the scores solve (I−dM) WS=(1−d)1(I - dM)\,WS = (1 - d)\mathbf{1}.

The algorithm

  1. TEXTRANK(S, d, ε, k) ▷ S: n sentences; d = 0.85, ε = 0.0001 in the paper
  2. 1for each pair i ≠ j do w_ij ← shared words / (log |S_i| + log |S_j|), or 0
  3. 2for each j do out_j ← Σ_k w_jk
  4. 3for each i do WS(i) ← 1
  5. 4repeat
  6. 5for each i do new(i) ← (1 - d) + d · Σ_(j : w_ji > 0) (w_ji / out_j) · WS(j)
  7. 6δ ← Σ_i |new(i) - WS(i)|
  8. 7WS ← new
  9. 8until δ < ε
  10. 9return 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 NN words, with NN 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 w12=3/(2ln⁡6)=0.837166w_{12} = 3 / (2 \ln 6) = 0.837166. Sentences 1 and 3 share cat, and 2 and 3 share dog, so w13=w23=1/(2ln⁡6)=0.279055w_{13} = w_{23} = 1/(2 \ln 6) = 0.279055. Sentence 4 shares no word with any other. So out1=out2=1.116221\mathrm{out}_1 = \mathrm{out}_2 = 1.116221, out3=0.558111\mathrm{out}_3 = 0.558111, and out4=0\mathrm{out}_4 = 0.

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 0.15+0.85 (0.75⋅1+0.5⋅1)=1.21250.15 + 0.85 \,(0.75 \cdot 1 + 0.5 \cdot 1) = 1.2125, since sentence 2 gives three quarters of its weight to sentence 1 and sentence 3 gives half. The fixed point solves x=0.15+0.85 (0.75x+0.5y)x = 0.15 + 0.85\,(0.75 x + 0.5 y) and y=0.15+0.85⋅0.5xy = 0.15 + 0.85 \cdot 0.5 x, so x=0.21375/0.181875=1.175258x = 0.21375 / 0.181875 = 1.175258. With ε=0.0001\varepsilon = 0.0001 the loop stops after 7 rounds. For k=2k = 2 the summary is sentences 1 and 2. The isolated sentence 4 keeps 1−d=0.151 - d = 0.15.

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 MM sums to 1 (for a vertex with edges) or 0 (for an isolated vertex), so ∥M∥1≤1\|M\|_1 \le 1, and the map x↦(1−d)1+dMxx \mapsto (1 - d)\mathbf{1} + d M x is a contraction with factor d<1d < 1 in the 1-norm. By the Banach fixed point theorem it has exactly one fixed point WS∗WS^*, and the iteration converges to it from any start.
  • Rate and stopping rule. The error shrinks by the factor dd each round, and when line L8 stops with change δ\delta, the error is at most dδ/(1−d)d\delta / (1 - d) in the 1-norm, which is 5.67 δ5.67\,\delta for d=0.85d = 0.85.
  • Mass. If no vertex is isolated, ∑iWS∗(i)=n\sum_i WS^*(i) = n. An isolated vertex has score 1−d1 - d.

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 W=(wij)W = (w_{ij}) be the n×nn \times n weight matrix built by line L1. It is symmetric, nonnegative and has a zero diagonal. Let outj=∑kwjk\mathrm{out}_j = \sum_k w_{jk} (line L2), and let MM be the n×nn \times n matrix with Mij=wji/outjM_{ij} = w_{ji} / \mathrm{out}_j when outj>0\mathrm{out}_j > 0 and Mij=0M_{ij} = 0 otherwise. Fix 0≤d<10 \le d < 1. Line L5 computes F(x)=(1−d)1+dMxF(x) = (1 - d)\mathbf{1} + d M x from x=WSx = WS, because the terms with wji=0w_{ji} = 0 are 0. The norm is ∥x∥1=∑i∣xi∣\|x\|_1 = \sum_i |x_i|.

Lemma 1 (column sums). Column jj of MM sums to 1 if outj>0\mathrm{out}_j > 0 and to 0 otherwise. Hence ∥My∥1≤∥y∥1\|M y\|_1 \le \|y\|_1 for every vector yy.

Proof. If outj>0\mathrm{out}_j > 0, then ∑iMij=∑iwji/outj=1\sum_i M_{ij} = \sum_i w_{ji} / \mathrm{out}_j = 1. Otherwise the column is 0. Since M≥0M \ge 0, ∥My∥1=∑i∣∑jMijyj∣≤∑j∣yj∣∑iMij≤∥y∥1\|My\|_1 = \sum_i |\sum_j M_{ij} y_j| \le \sum_j |y_j| \sum_i M_{ij} \le \|y\|_1. □\square

Lemma 2 (contraction). ∥F(x)−F(y)∥1≤d∥x−y∥1\|F(x) - F(y)\|_1 \le d \|x - y\|_1.

Proof. F(x)−F(y)=dM(x−y)F(x) - F(y) = dM(x - y); apply Lemma 1. □\square

Theorem 1 (fixed point and convergence). FF has exactly one fixed point WS∗WS^*. The sequence x0=1x_0 = \mathbf{1}, xt+1=F(xt)x_{t+1} = F(x_t) of lines L3 to L7 satisfies ∥xt−WS∗∥1≤dt∥x0−WS∗∥1\|x_t - WS^*\|_1 \le d^t \|x_0 - WS^*\|_1.

Proof. Rn\mathbb{R}^n with the 1-norm is complete, and FF is a contraction with factor d<1d < 1 by Lemma 2, so the Banach fixed point theorem gives one fixed point and convergence from any start. The rate follows by induction: ∥xt+1−WS∗∥1=∥F(xt)−F(WS∗)∥1≤d∥xt−WS∗∥1\|x_{t+1} - WS^*\|_1 = \|F(x_t) - F(WS^*)\|_1 \le d \|x_t - WS^*\|_1. Equivalently, I−dMI - dM is invertible (its Neumann series ∑tdtMt\sum_t d^t M^t converges), and WS∗=(1−d)(I−dM)−11WS^* = (1 - d)(I - dM)^{-1}\mathbf{1}. □\square

Theorem 2 (stopping rule). If line L8 stops after computing xt+1x_{t+1} with δ=∥xt+1−xt∥1<ε\delta = \|x_{t+1} - x_t\|_1 < \varepsilon, then ∥xt+1−WS∗∥1≤d1−d δ\|x_{t+1} - WS^*\|_1 \le \frac{d}{1 - d}\,\delta.

Proof. Let e=∥xt+1−WS∗∥1e = \|x_{t+1} - WS^*\|_1. By Lemma 2, e≤d∥xt−WS∗∥1≤d(∥xt−xt+1∥1+e)=d(δ+e)e \le d\|x_t - WS^*\|_1 \le d(\|x_t - x_{t+1}\|_1 + e) = d(\delta + e). Rearranging gives e(1−d)≤dδe(1 - d) \le d\delta. □\square

Theorem 3 (mass). Let ZZ be the set of isolated vertices (outj=0\mathrm{out}_j = 0) and AA the rest. Then WS∗(i)=1−dWS^*(i) = 1 - d for i∈Zi \in Z, and ∑i∈AWS∗(i)=∣A∣\sum_{i \in A} WS^*(i) = |A|.

Proof. For i∈Zi \in Z, wji=wij=0w_{ji} = w_{ij} = 0 for every jj, so row ii of MM is 0 and the fixed point equation gives WS∗(i)=1−dWS^*(i) = 1 - d. For i∈Ai \in A, row ii of MM has nonzero entries only in columns jj with wji>0w_{ji} > 0, and those jj are in AA. Summing the fixed point equation over i∈Ai \in A gives ∑i∈AWS∗(i)=(1−d)∣A∣+d∑j∈AWS∗(j)∑i∈AMij\sum_{i \in A} WS^*(i) = (1 - d)|A| + d \sum_{j \in A} WS^*(j) \sum_{i \in A} M_{ij}. For j∈Aj \in A, every ii with Mij>0M_{ij} > 0 has wji>0w_{ji} > 0, so i∈Ai \in A, and by Lemma 1 the inner sum is 1. So s=∑i∈AWS∗(i)s = \sum_{i \in A} WS^*(i) satisfies s=(1−d)∣A∣+dss = (1 - d)|A| + ds, which gives s=∣A∣s = |A|. ■\blacksquare

Remark (scale). Replacing WW by cWcW for a constant c>0c > 0 leaves every MijM_{ij} 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 kk 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 WS∗WS^*; 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 ε\varepsilon 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 (n2)\binom{n}{2} pairs. With a hash set of the words of each sentence, one pair costs O(∣Si∣+∣Sj∣)O(|S_i| + |S_j|) expected time, so the graph takes O(nN)O(n N) expected time for NN tokens and O(n2)O(n^2) space. Each round of lines L5 to L7 takes O(n2)O(n^2) time on the dense matrix, or O(n+E)O(n + E) on a list of the EE nonzero edges. To get the error below η\eta from a start with error e0e_0 takes I≤log⁡(e0/η)/log⁡(1/d)I \le \log(e_0 / \eta) / \log(1/d) rounds, about 14.2 rounds per factor of 10 for d=0.85d = 0.85. This is a worst case bound; the example above needed 7 rounds. In total: O(nN+In2)O(nN + I n^2) time.

Properties

  • Unsupervised. It needs no training data and no corpus, only the text.
  • Scale invariance. The scores depend on the weights only through wji/outjw_{ji} / \mathrm{out}_j, 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 (1−d)/n(1 - d)/n in place of 1−d1 - d divides every score by nn, 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 log⁡1+log⁡1=0\log 1 + \log 1 = 0 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 outj=0\mathrm{out}_j = 0. Line L5 must skip it as a source; dividing by outj\mathrm{out}_j 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 nn. The error bound above holds for the 1-norm.
  • The meaning of d. In this formula d=0.85d = 0.85 is the weight of the links, and 1−d1 - d is the restart. Some papers on LexRank use dd 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.

textrank.pyI0RawGitHub
# 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

  1. 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)
  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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.expected
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • at least three sources
  • a scene preset for the example