Algorithm Search⌘K

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
Properties
deterministicnot exactofflineiterative
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 S1,…,SnS_1, \ldots, S_n, an idf table, a threshold tt and a jump probability dd. For a word ww and a sentence xx, let tfw,x\mathrm{tf}_{w,x} be the number of times ww occurs in xx. The idf-modified cosine (equation 2 of the paper) is

cos⁡(x,y)=∑wtfw,x tfw,y idfw2∑w(tfw,x idfw)2 ∑w(tfw,y idfw)2,\cos(x, y) = \frac{\sum_{w} \mathrm{tf}_{w,x}\, \mathrm{tf}_{w,y}\, \mathrm{idf}_w^2}{\sqrt{\sum_{w} (\mathrm{tf}_{w,x}\, \mathrm{idf}_w)^2}\ \sqrt{\sum_{w} (\mathrm{tf}_{w,y}\, \mathrm{idf}_w)^2}},

with idfw=log⁡(N/nw)\mathrm{idf}_w = \log(N / n_w) for a collection of NN documents of which nwn_w contain ww. The adjacency matrix has Aij=1A_{ij} = 1 if cos⁡(Si,Sj)>t\cos(S_i, S_j) > t and 0 otherwise, and Aii=1A_{ii} = 1. The matrix BB divides each row of AA by its sum, the degree. LexRank is the probability vector pp with

p=[dnU+(1−d)B]Tp,∑ipi=1,p = \Bigl[\frac{d}{n} U + (1 - d) B\Bigr]^{\mathsf T} p, \qquad \sum_i p_i = 1,

where UU is the n×nn \times n matrix of ones (equation 9 of the paper). In continuous LexRank (Section 3.3), Aij=cos⁡(Si,Sj)A_{ij} = \cos(S_i, S_j) instead. The output is the kk sentences with the highest pip_i.

The algorithm

  1. LEXRANK(S, idf, t, d, ε) ▷ S: n sentences; t = 0.1; d: jump probability
  2. 1for i ← 1 to n do for j ← 1 to n do
  3. 2c_ij ← idf-modified cosine of S_i and S_j
  4. 3A_ij ← 1 if i = j or c_ij > t, else 0 ▷ continuous: A_ij ← c_ij
  5. 4for each i do deg_i ← Σ_j A_ij; B_ij ← A_ij / deg_i for each j
  6. 5p ← (1/n, ..., 1/n)
  7. 6repeat
  8. 7q_j ← d / n + (1 - d) Σ_i B_ij p_i for each j
  9. 8δ ← Σ_j |q_j - p_j|; p ← q
  10. 9until δ < ε
  11. 10return 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 1−d1 - d it follows an edge of the current sentence, chosen uniformly (or in proportion to the weights in the continuous form), and with probability dd it jumps to any sentence. The paper reports experiments with tt 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: log⁡(4/3)=0.2877\log(4/3) = 0.2877 for "the" and "storm", log⁡2=0.6931\log 2 = 0.6931 for "coast", "roads", "flooded" and "schools", and log⁡4=1.3863\log 4 = 1.3863 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 t=0.1t = 0.1 the graph is the path 1 - 2 - 3 - 4 with self loops, so the degrees are 2, 3, 3, 2, and the rows of BB are (12,12,0,0)(\frac12, \frac12, 0, 0), (13,13,13,0)(\frac13, \frac13, \frac13, 0), (0,13,13,13)(0, \frac13, \frac13, \frac13) and (0,0,12,12)(0, 0, \frac12, \frac12). With d=0.15d = 0.15:

step p1p_1 p2p_2 p3p_3 p4p_4
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 (x,y,y,x)(x, y, y, x) with 2x+2y=12x + 2y = 1 and x=0.0375+0.85 (x/2+y/3)x = 0.0375 + 0.85\,(x/2 + y/3), which gives x=43/206x = 43/206. Without jumps (d=0d = 0) the limit is the degree vector over its sum, (0.2,0.3,0.3,0.2)(0.2, 0.3, 0.3, 0.2). Sentences 2 and 3 tie; with k=1k = 1 the tie rule picks sentence 2. Continuous LexRank breaks the tie: it gives (0.2387,0.2905,0.2452,0.2255)(0.2387, 0.2905, 0.2452, 0.2255).

Correctness

The matrix M=dnU+(1−d)BM = \frac{d}{n} U + (1 - d) B is row stochastic, and for d>0d > 0 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 pp equal to 1, and the difference to the limit is multiplied by (1−d)BT(1 - d)B^{\mathsf T}, whose 1-norm is at most 1−d1 - d. So the error falls at least by the factor 1−d1 - d per step, and when line L9 stops with change δ\delta, the error is at most (1−d)δ/d(1 - d)\delta / d. For a symmetric AA and d=0d = 0, 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 AA be the n×nn \times n matrix of lines L1 to L3, with Aij≥0A_{ij} \ge 0 and Aii=1A_{ii} = 1, and let BB be AA with each row divided by its sum (line L4). The rows of BB are probability vectors, because each row sum of AA is at least Aii=1>0A_{ii} = 1 > 0. Fix 0<d≤10 < d \le 1, let UU be the matrix of ones and M=dnU+(1−d)BM = \frac{d}{n}U + (1 - d)B. Line L7 computes q=MTpq = M^{\mathsf T} p when ∑ipi=1\sum_i p_i = 1, since (dnUTp)j=dn∑ipi=dn(\frac{d}{n}U^{\mathsf T} p)_j = \frac{d}{n}\sum_i p_i = \frac{d}{n}. The norm is ∥x∥1=∑i∣xi∣\|x\|_1 = \sum_i |x_i|, and Δ={p≥0:∑ipi=1}\Delta = \{p \ge 0 : \sum_i p_i = 1\}.

Lemma 1. If p∈Δp \in \Delta then MTp∈ΔM^{\mathsf T} p \in \Delta.

Proof. M≥0M \ge 0, so MTp≥0M^{\mathsf T}p \ge 0. Its sum is ∑j∑iMijpi=∑ipi∑jMij=∑ipi=1\sum_j \sum_i M_{ij} p_i = \sum_i p_i \sum_j M_{ij} = \sum_i p_i = 1, because each row of MM sums to dn⋅n+(1−d)⋅1=1\frac{d}{n} \cdot n + (1 - d) \cdot 1 = 1. □\square

Lemma 2. For every yy with ∑iyi=0\sum_i y_i = 0, MTy=(1−d)BTyM^{\mathsf T} y = (1 - d) B^{\mathsf T} y and ∥MTy∥1≤(1−d)∥y∥1\|M^{\mathsf T} y\|_1 \le (1 - d)\|y\|_1.

Proof. UTyU^{\mathsf T} y has every entry equal to ∑iyi=0\sum_i y_i = 0, which gives the first claim. For the second, ∥BTy∥1=∑j∣∑iBijyi∣≤∑i∣yi∣∑jBij=∥y∥1\|B^{\mathsf T}y\|_1 = \sum_j |\sum_i B_{ij} y_i| \le \sum_i |y_i| \sum_j B_{ij} = \|y\|_1. □\square

Theorem 1 (existence and uniqueness). There is exactly one p∗∈Δp^* \in \Delta with MTp∗=p∗M^{\mathsf T} p^* = p^*.

Proof. Let T(p)=MTpT(p) = M^{\mathsf T}p. By Lemma 1, TT maps Δ\Delta into itself. For p,p′∈Δp, p' \in \Delta, y=p−p′y = p - p' has sum 0, so by Lemma 2 ∥T(p)−T(p′)∥1≤(1−d)∥p−p′∥1\|T(p) - T(p')\|_1 \le (1 - d)\|p - p'\|_1. Since d>0d > 0, TT is a contraction of the closed set Δ\Delta, and the Banach fixed point theorem gives exactly one fixed point. (Equivalently: all entries of MM 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.) □\square

Theorem 2 (rate and stopping rule). Let p0=(1/n,…,1/n)p_0 = (1/n, \ldots, 1/n) and pt+1=MTptp_{t+1} = M^{\mathsf T}p_t. Then ∥pt−p∗∥1≤(1−d)t∥p0−p∗∥1≤2(1−d)t\|p_t - p^*\|_1 \le (1 - d)^t \|p_0 - p^*\|_1 \le 2(1 - d)^t. If line L9 stops with δ=∥pt+1−pt∥1\delta = \|p_{t+1} - p_t\|_1, then ∥pt+1−p∗∥1≤1−dd δ\|p_{t+1} - p^*\|_1 \le \frac{1 - d}{d}\,\delta.

Proof. Each pt∈Δp_t \in \Delta by Lemma 1, so pt−p∗p_t - p^* has sum 0, and Lemma 2 gives ∥pt+1−p∗∥1=∥MT(pt−p∗)∥1≤(1−d)∥pt−p∗∥1\|p_{t+1} - p^*\|_1 = \|M^{\mathsf T}(p_t - p^*)\|_1 \le (1 - d)\|p_t - p^*\|_1. Induction gives the first bound, and two distributions are at distance at most 2. For the second, let e=∥pt+1−p∗∥1e = \|p_{t+1} - p^*\|_1; then e≤(1−d)∥pt−p∗∥1≤(1−d)(δ+e)e \le (1 - d)\|p_t - p^*\|_1 \le (1 - d)(\delta + e), so e d≤(1−d)δe\,d \le (1 - d)\delta. □\square

Theorem 3 (degree centrality). Let AA be symmetric and d=0d = 0. Then πi=deg⁡i/∑kdeg⁡k\pi_i = \deg_i / \sum_k \deg_k, with deg⁡i=∑jAij\deg_i = \sum_j A_{ij}, satisfies BTπ=πB^{\mathsf T}\pi = \pi. If the graph of the nonzero entries of AA is connected, π\pi is the only stationary distribution, and the power method converges to it.

Proof. Let D=∑kdeg⁡kD = \sum_k \deg_k. Then (BTπ)j=∑iAijdeg⁡i⋅deg⁡iD=1D∑iAji=deg⁡jD=πj(B^{\mathsf T}\pi)_j = \sum_i \frac{A_{ij}}{\deg_i}\cdot\frac{\deg_i}{D} = \frac{1}{D}\sum_i A_{ji} = \frac{\deg_j}{D} = \pi_j, using Aij=AjiA_{ij} = A_{ji}. If the graph is connected, the chain BB is irreducible, and it is aperiodic because Bii>0B_{ii} > 0. A finite irreducible aperiodic chain has a unique stationary distribution, and BTB^{\mathsf T} applied tt times to any distribution tends to it as t→∞t \to \infty. ■\blacksquare

Remark (isolated vertex). If row ii of AA has only its diagonal entry and column ii has only its diagonal entry, the fixed point equation gives pi∗=dn+(1−d)pi∗p^*_i = \frac{d}{n} + (1 - d)p^*_i, so pi∗=1/np^*_i = 1/n for any d>0d > 0.

Remark (output). By Theorem 2 the returned vector is within (1−d)δ/d(1 - d)\delta/d of p∗p^* 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 O(N)O(N) expected time with hash tables. One cosine takes O(∣Si∣+∣Sj∣)O(|S_i| + |S_j|) expected time, so all pairs take O(nN)O(nN) time, and the matrices take O(n2)O(n^2) space. Each power step costs O(n2)O(n^2) on the dense matrix, or O(n+E)O(n + E) with the EE edges of the threshold graph, since the jump term adds the same d/nd/n to every entry. Reaching error η\eta takes at most log⁡(2/η)/log⁡(1/(1−d))\log(2/\eta) / \log(1/(1 - d)) steps, about 14 steps per factor of 10 for d=0.15d = 0.15. In total: O(nN+In2)O(nN + I n^2) 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 1/n1/n. 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 pi=d/n+(1−d)pip_i = d/n + (1 - d)p_i and pi=1/np_i = 1/n 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 d=0d = 0 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 d=0d = 0 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, dd 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 d=0.85d = 0.85 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 cij>tc_{ij} > t for the diagonal too would remove every self loop when t≥1t \ge 1. Line L3 keeps i=ji = j separate.
  • Column or row. BB is row stochastic, and line L7 sums over the rows ii. Using BB in place of BTB^{\mathsf T} 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 ε\varepsilon, 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.

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

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

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