Definitioncore
ROUGE
Also called ROUGE-N, ROUGE-L.
Recall-oriented summary metrics based on the overlap of n-grams, or the longest common subsequence, between a candidate and reference summaries.
ROUGE (Recall-Oriented Understudy for Gisting Evaluation) is a family of scores that compare a candidate summary with one or more reference summaries written by people. ROUGE-N counts the n-grams of the references that also occur in the candidate. ROUGE-L uses the longest common subsequence of the two texts. Chin-Yew Lin defined them in 2004 and released them as the ROUGE package, which the Document Understanding Conferences used to evaluate summarizers. Higher is better, every score is between 0 and 1, and the score is computed per summary and averaged over the test set. All scores depend on the tokenization, the lower casing, the stemming and the stop word list, so these must be stated with the numbers.
Definition
Let the candidate and the references be lists of tokens. For a text and , let be the number of times the n-gram occurs in .
ROUGE-N. For one reference and a candidate , the clipped match count is , so each n-gram of the candidate matches at most as many times as it occurs in the reference. Then
and . Equation 1 of the paper is the recall with the numerator and the denominator summed over all references. ROUGE-N is a recall measure by design; reports today often give the F measure.
ROUGE-L, sentence level. Let , and the length of a longest common subsequence of and . Then
A common subsequence keeps the order of the words but allows gaps, so ROUGE-L rewards the same words in the same order without asking for consecutive n-grams. The paper sets to a very large number for DUC, so that only recall counts; most later work uses .
ROUGE-L, summary level. For reference sentences with tokens in total and candidate sentences with tokens in total, let be the number of tokens of that are in the union of the longest common subsequences of with each . Then and , with the same F. Google's rouge-score package calls this form ROUGE-Lsum; it splits the summaries into sentences at newlines.
Other members. ROUGE-W weights the common subsequence so that consecutive matches count more (Section 4). ROUGE-S counts skip-bigrams, pairs of words in order with any gap, and ROUGE-SU adds the unigrams (Section 5); the paper also limits the distance between the two words.
Several references. Section 2.1 takes the largest score over the references. The package uses a jackknife: with references, it takes the best score against each of the sets of references, and averages these values, so that system scores are comparable with the scores of a human summary scored against the other references.
Options of the package. ROUGE-1.5.5 does no stemming and keeps stop words by default. Option -m applies the Porter stemmer, -s removes the stop words of its list, -n sets the largest n, and -f chooses between the mean over references (A, the default) and the best reference (B).
Examples and non-examples
The reference is "the cat sat on the mat" and the candidate is "the cat on the mat", split at spaces.
| score | matches | recall | precision | F () |
|---|---|---|---|---|
| ROUGE-1 | the (2), cat, on, mat: 5 | 5/6 | 5/5 = 1 | 10/11 |
| ROUGE-2 | the cat, on the, the mat: 3 | 3/5 | 3/4 | 2/3 |
| ROUGE-L | the cat on the mat: | 5/6 | 1 | 10/11 |
Clipping: the candidate "the the the" against the reference "the cat the" has three unigrams "the", but the reference has only two, so it matches 2, and the recall and the precision are both 2/3.
Lin's example for ROUGE-L. The reference S1 is "police killed the gunman". S2, "police kill the gunman", has the common subsequence "police the gunman", and with . S3, "the gunman kill police", has only "the gunman", and scores 1/2. ROUGE-2 gives both 1/3, since each shares only the bigram "the gunman", but S2 keeps the order of the sentence and S3 reverses its meaning. S4, "the gunman police killed", also scores 1/2 with ROUGE-L, because only one of the two orders "the gunman" and "police killed" can be in a common subsequence. Skip-bigrams tell S4 from S3: ROUGE-S gives S2 1/2, S3 1/6 and S4 1/3.
Lin's example for the union LCS. A reference sentence and a candidate of two sentences and . The longest common subsequences are and , their union is , and the summary level recall is 4/5.
Several references. With references "the cat sat on the mat", "a cat sat on a mat" and "the dog sat", the candidate "the cat on the mat" has ROUGE-1 recall 5/6, 1/2 and 1/3. The largest is 5/6. Equation 1 pools the counts to . The jackknife averages the best of each pair, . Three rules give three numbers.
Non-examples. ROUGE is not a measure of factual correctness: the candidate "the cat never sat on the mat" has ROUGE-1 recall 1 against the reference above, and "the mat sat on the cat" has ROUGE-1 recall and precision 1. It is not symmetric: recall and precision exchange when the candidate and the reference are exchanged. And a ROUGE number without its package, options and tokenization is not comparable with another ROUGE number; Grusky (2023) found that most papers do not report enough to reproduce their scores.
Related definitions
- BLEU is the precision counterpart for translation, with clipped n-gram precisions, a geometric mean and a brevity penalty, computed at the corpus level.
- BERTScore replaces exact matches by the cosine of contextual token embeddings.
- chrF uses character n-grams and an F measure.
- Word error rate uses the edit distance instead of the longest common subsequence.
- The longest common subsequence is computed by the standard dynamic program in time, and the n-gram counts in expected time with hash tables.
- ROUGE is the usual metric for automatic summarization.
Code
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/rouge/. The authors are listed in prov/MTNGKQ.jsonl.
"""ROUGE-N, ROUGE-L and ROUGE-S (Lin 2004) with exact fractions.
Texts are lists of tokens; the caller does the tokenization, the lower
casing, the stemming and the removal of stop words. A summary for the
summary-level ROUGE-L is a list of sentences, each a list of tokens.
"""
from collections import Counter
from fractions import Fraction
from typing import Callable, Hashable, List, Optional, Sequence, Set, Tuple
Tokens = Sequence[Hashable]
Score = Tuple[Fraction, Fraction, Fraction]
def ngrams(tokens: Tokens, n: int) -> Counter:
"""The multiset of n-grams of a token list."""
return Counter(tuple(tokens[i:i + n]) for i in range(len(tokens) - n + 1))
def f_measure(r: Fraction, p: Fraction, beta: Fraction = Fraction(1)) -> Fraction:
"""F = (1 + beta^2) R P / (R + beta^2 P), and 0 when R = P = 0."""
den = r + beta * beta * p
if den == 0:
return Fraction(0)
return (1 + beta * beta) * r * p / den
def ratio(a: int, b: int) -> Fraction:
return Fraction(a, b) if b else Fraction(0)
def rouge_n(cand: Tokens, ref: Tokens, n: int) -> Score:
"""(R, P, F with beta = 1) of ROUGE-N for one reference, with clipped counts."""
c, r = ngrams(cand, n), ngrams(ref, n)
match = sum(min(k, c[g]) for g, k in r.items())
rec = ratio(match, sum(r.values()))
prec = ratio(match, sum(c.values()))
return rec, prec, f_measure(rec, prec)
def rouge_n_pooled(cand: Tokens, refs: Sequence[Tokens], n: int) -> Fraction:
"""Equation 1 of Lin (2004): matches and reference n-grams summed over all references."""
c = ngrams(cand, n)
match = total = 0
for ref in refs:
r = ngrams(ref, n)
match += sum(min(k, c[g]) for g, k in r.items())
total += sum(r.values())
return ratio(match, total)
def rouge_multi(
cand: Tokens, refs: Sequence[Tokens], score: Callable[[Tokens, Tokens], Fraction]
) -> Fraction:
"""Several references: the largest of the pairwise scores (Section 2.1)."""
return max(score(cand, ref) for ref in refs)
def jackknife(
cand: Tokens, refs: Sequence[Tokens], score: Callable[[Tokens, Tokens], Fraction]
) -> Fraction:
"""The mean over the M sets of M - 1 references of the best pairwise score."""
m = len(refs)
if m == 1:
return score(cand, refs[0])
total = Fraction(0)
for k in range(m):
total += rouge_multi(cand, [refs[i] for i in range(m) if i != k], score)
return total / m
def lcs_table(a: Tokens, b: Tokens) -> List[List[int]]:
"""t[i][j] = length of a longest common subsequence of a[:i] and b[:j]."""
t = [[0] * (len(b) + 1) for _ in range(len(a) + 1)]
for i in range(1, len(a) + 1):
for j in range(1, len(b) + 1):
if a[i - 1] == b[j - 1]:
t[i][j] = t[i - 1][j - 1] + 1
else:
t[i][j] = max(t[i - 1][j], t[i][j - 1])
return t
def lcs_length(a: Tokens, b: Tokens) -> int:
return lcs_table(a, b)[len(a)][len(b)]
def rouge_l(cand: Tokens, ref: Tokens, beta: Fraction = Fraction(1)) -> Score:
"""Sentence-level ROUGE-L: R = LCS / |ref|, P = LCS / |cand|, and F with beta."""
k = lcs_length(cand, ref)
rec, prec = ratio(k, len(ref)), ratio(k, len(cand))
return rec, prec, f_measure(rec, prec, beta)
def lcs_positions(ref: Tokens, cand: Tokens) -> Set[int]:
"""The positions in ref of one longest common subsequence, found by tracing back."""
t = lcs_table(ref, cand)
i, j, out = len(ref), len(cand), set()
while i > 0 and j > 0:
if ref[i - 1] == cand[j - 1]:
out.add(i - 1)
i -= 1
j -= 1
elif t[i - 1][j] >= t[i][j - 1]:
i -= 1
else:
j -= 1
return out
def union_lcs(ref_sentence: Tokens, cand_sentences: Sequence[Tokens]) -> int:
"""The number of reference positions in the union of the LCS with each candidate sentence."""
hit: Set[int] = set()
for c in cand_sentences:
hit |= lcs_positions(ref_sentence, c)
return len(hit)
def rouge_l_summary(
cand_sentences: Sequence[Tokens], ref_sentences: Sequence[Tokens], beta: Fraction = Fraction(1)
) -> Score:
"""Summary-level ROUGE-L (Section 3.2), as computed by ROUGE-Lsum.
The union LCS of each reference sentence is counted once per position;
the clipping of repeated words used by some packages is not applied.
"""
hits = sum(union_lcs(r, cand_sentences) for r in ref_sentences)
m = sum(len(r) for r in ref_sentences)
n = sum(len(c) for c in cand_sentences)
rec, prec = ratio(hits, m), ratio(hits, n)
return rec, prec, f_measure(rec, prec, beta)
def skip_bigrams(tokens: Tokens, max_gap: Optional[int] = None) -> Counter:
"""Pairs of tokens in order; with max_gap = k, at most k tokens between them."""
out: Counter = Counter()
for i in range(len(tokens)):
last = len(tokens) if max_gap is None else min(len(tokens), i + max_gap + 2)
for j in range(i + 1, last):
out[(tokens[i], tokens[j])] += 1
return out
def rouge_s(cand: Tokens, ref: Tokens, max_gap: Optional[int] = None,
beta: Fraction = Fraction(1)) -> Score:
"""ROUGE-S: skip-bigram recall, precision and F."""
c, r = skip_bigrams(cand, max_gap), skip_bigrams(ref, max_gap)
match = sum(min(k, c[g]) for g, k in r.items())
rec, prec = ratio(match, sum(r.values())), ratio(match, sum(c.values()))
return rec, prec, f_measure(rec, prec, beta)
test_rouge.py 131 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/rouge/. The authors are listed in prov/MTNGKQ.jsonl.
import random
from fractions import Fraction as Fr
from itertools import combinations
from rouge import (
jackknife,
lcs_length,
lcs_positions,
ngrams,
rouge_l,
rouge_l_summary,
rouge_multi,
rouge_n,
rouge_n_pooled,
rouge_s,
skip_bigrams,
union_lcs,
)
REF = "the cat sat on the mat".split()
CAND = "the cat on the mat".split()
def test_check_values():
assert rouge_n(CAND, REF, 1)[:2] == (Fr(5, 6), Fr(1))
assert rouge_n(CAND, REF, 2)[:2] == (Fr(3, 5), Fr(3, 4))
assert lcs_length(CAND, REF) == 5
assert rouge_l(CAND, REF) == (Fr(5, 6), Fr(1), Fr(10, 11))
assert rouge_n(CAND, REF, 1)[2] == Fr(10, 11)
def test_clipping():
# "the the the" against a reference with two "the": two matches, not three.
assert rouge_n("the the the".split(), "the cat the".split(), 1)[:2] == (Fr(2, 3), Fr(2, 3))
def test_lin_lcs_examples():
s1 = "police killed the gunman".split()
s2 = "police kill the gunman".split()
s3 = "the gunman kill police".split()
s4 = "the gunman police killed".split()
assert rouge_l(s2, s1)[2] == Fr(3, 4)
assert rouge_l(s3, s1)[2] == Fr(1, 2)
assert rouge_l(s4, s1)[2] == Fr(1, 2)
# Bigrams cannot tell S2 from S3 here, and skip-bigrams prefer S4 to S3.
assert rouge_n(s2, s1, 2)[2] == Fr(1, 3)
assert rouge_n(s3, s1, 2)[2] == Fr(1, 3)
assert rouge_s(s2, s1)[2] == Fr(1, 2)
assert rouge_s(s3, s1)[2] == Fr(1, 6)
assert rouge_s(s4, s1)[2] == Fr(1, 3)
def test_union_lcs_example():
r = ["w1", "w2", "w3", "w4", "w5"]
c1 = ["w1", "w2", "w6", "w7", "w8"]
c2 = ["w1", "w3", "w8", "w9", "w5"]
assert lcs_positions(r, c1) == {0, 1}
assert lcs_positions(r, c2) == {0, 2, 4}
assert union_lcs(r, [c1, c2]) == 4
rec, prec, _ = rouge_l_summary([c1, c2], [r])
assert rec == Fr(4, 5) and prec == Fr(4, 10)
def brute_lcs(a, b):
for k in range(min(len(a), len(b)), -1, -1):
subs = {tuple(a[i] for i in idx) for idx in combinations(range(len(a)), k)}
for idx in combinations(range(len(b)), k):
if tuple(b[i] for i in idx) in subs:
return k
return 0
def brute_ngram_match(cand, ref, n):
"""Count matches by pairing equal n-gram occurrences one to one."""
cg = [tuple(cand[i:i + n]) for i in range(len(cand) - n + 1)]
rg = [tuple(ref[i:i + n]) for i in range(len(ref) - n + 1)]
used, match = [False] * len(cg), 0
for g in rg:
for k, h in enumerate(cg):
if not used[k] and h == g:
used[k] = True
match += 1
break
return match, len(rg), len(cg)
def test_random_against_brute_force():
rng = random.Random(2004)
vocab = list("abcd")
for _ in range(400):
a = [rng.choice(vocab) for _ in range(rng.randint(0, 7))]
b = [rng.choice(vocab) for _ in range(rng.randint(0, 7))]
k = lcs_length(a, b)
assert k == brute_lcs(a, b)
pos = lcs_positions(a, b)
assert len(pos) == k
sub = [a[i] for i in sorted(pos)]
assert brute_lcs(sub, b) == k
for n in (1, 2, 3):
m, nr, nc = brute_ngram_match(b, a, n)
rec, prec, _ = rouge_n(b, a, n)
assert rec == (Fr(m, nr) if nr else 0)
assert prec == (Fr(m, nc) if nc else 0)
sb = skip_bigrams(a)
assert sum(sb.values()) == len(a) * (len(a) - 1) // 2
assert sum(skip_bigrams(a, 0).values()) == max(0, len(a) - 1)
assert skip_bigrams(a, 0) == ngrams(a, 2)
def test_multiple_references():
refs = [REF, "a cat sat on a mat".split(), "the dog sat".split()]
one = lambda c, r: rouge_n(c, r, 1)[0]
assert rouge_multi(CAND, refs, one) == Fr(5, 6)
# Equation 1 pools the counts: (5 + 3 + 1) matches of (6 + 6 + 3) reference unigrams.
assert rouge_n_pooled(CAND, refs, 1) == Fr(9, 15)
# Jackknife: the best of each pair of references, averaged.
want = (max(Fr(3, 6), Fr(1, 3)) + max(Fr(5, 6), Fr(1, 3)) + max(Fr(5, 6), Fr(3, 6))) / 3
assert jackknife(CAND, refs, one) == want == Fr(13, 18)
def test_edge_cases():
assert rouge_n([], REF, 1) == (0, 0, 0)
assert rouge_n(["a"], ["a"], 2) == (0, 0, 0)
assert rouge_l([], []) == (0, 0, 0)
assert rouge_l(REF, REF) == (1, 1, 1)
# A large beta weights recall: F tends to R.
r, p, f = rouge_l(CAND, REF, beta=Fr(1000))
assert abs(f - r) < Fr(1, 10 ** 5)
References
- Lin 2004, Section 2 (ROUGE-N, equation 1, and Section 2.1 on multiple references and the jackknife), Section 3 (ROUGE-L, the sentence level F measure in Section 3.1 and the union LCS in Section 3.2), Section 4 (ROUGE-W), Section 5 (ROUGE-S and ROUGE-SU)
- Max Grusky, Rogue Scores, ACL 2023, pages 1914 to 1934, the study of how papers compute and report ROUGE, and the differences between packages
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 | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag MTNGKQ Edit this page History Report an error Markdown