Sub topic 9
ROUGE-L: longest common subsequence
This chapter assumes you know precision, recall, and F1, and that you have read the ROUGE-N chapter. You should also be comfortable with basic Python lists and loops. ROUGE-N counts n-grams that sit side by side. ROUGE-L relaxes that rule by asking how much of the reference appears in the candidate in the same order, even when other words sit between the matches.
Why contiguity is a limitation
ROUGE-2 only credits two words that appear next to each other in both texts. Consider this pair:
- Reference:
the cat is on the mat - Candidate:
the cat sat on the mat
The word "sat" breaks the match for "cat is" and "is on". Yet the candidate still follows the reference's word order closely. ROUGE-L captures this. It does not require matched words to be adjacent. It only requires that they appear in the same relative order.
Subsequences versus substrings
A subsequence of a token list is obtained by deleting zero or more tokens without reordering the rest. A substring (a contiguous n-gram) must keep the tokens adjacent. Every substring is a subsequence, but not the other way around.
For the reference the cat is on the mat, the list the cat on mat is a subsequence. It is not a substring, because "is" and the second "the" were skipped.
The longest common subsequence (LCS) of two token lists is the longest list that is a subsequence of both. In the example above, the LCS is the cat on the mat, which has length 5. A pair of texts can have more than one LCS of the same length. The length is always well defined, and ROUGE-L only uses the length.
From LCS length to precision, recall, and F1
Let m be the reference length, n the candidate length, and LCS the LCS length. ROUGE-L defines:
- Recall = LCS / m
- Precision = LCS / n
- F1 = 2 · P · R / (P + R)
For the example, LCS = 5, m = 6, and n = 6. Precision is 5/6, recall is 5/6, and F1 is 5/6, about 0.833. ROUGE-2 on the same pair is lower, because only "on the" and "the mat" match as bigrams (2 of 5 bigrams, or 0.4).
The original ROUGE paper defines the F-measure with a weight beta that favors recall. The common Python packages report the plain balanced F1 by default, so the formulas above are what you will usually see.
Computing the LCS with dynamic programming
Finding the LCS by trying all subsequences would take exponential time. Dynamic programming solves it in O(m · n) time.
Build a table where table[i][j] holds the LCS length of the first i candidate tokens and the first j reference tokens. The rule for each cell:
- If token
a[i-1]equals tokenb[j-1], the match extends the best result for both shorter prefixes:table[i][j] = table[i-1][j-1] + 1. - Otherwise, take the better of dropping one token from either side:
table[i][j] = max(table[i-1][j], table[i][j-1]).
The bottom-right cell is the answer.
def lcs_length(a, b):
table = [[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]:
table[i][j] = table[i - 1][j - 1] + 1
else:
table[i][j] = max(table[i - 1][j], table[i][j - 1])
return table[-1][-1]
def rouge_l(candidate, reference):
lcs = lcs_length(candidate, reference)
if lcs == 0:
return 0.0, 0.0, 0.0
precision = lcs / len(candidate)
recall = lcs / len(reference)
f1 = 2 * precision * recall / (precision + recall)
return precision, recall, f1
print(rouge_l("the cat sat on the mat".split(), "the cat is on the mat".split()))The output is (0.8333333333333334, 0.8333333333333334, 0.8333333333333334).
The function returns zeros when the LCS is empty, which also avoids dividing by zero when precision and recall are both 0. An empty candidate would raise a division error at len(candidate), but only if the LCS is nonzero, and an empty list always has an LCS of 0, so it returns zeros first.
Tracing the table
Here is a smaller case to follow by hand. The candidate is a b c d and the reference is a c b d.
| Row | (empty) | a | c | b | d |
|---|---|---|---|---|---|
| (empty) | 0 | 0 | 0 | 0 | 0 |
| a | 0 | 1 | 1 | 1 | 1 |
| b | 0 | 1 | 1 | 2 | 2 |
| c | 0 | 1 | 2 | 2 | 2 |
| d | 0 | 1 | 2 | 2 | 3 |
Rows are candidate tokens and columns are reference tokens. The LCS length is 3. One valid LCS is a b d, and another is a c d. Both candidate and reference have 4 tokens, so precision, recall, and F1 are all 3/4 = 0.75.
Notice that the swap of "b" and "c" costs one token, because a subsequence cannot reorder words. ROUGE-L therefore penalizes reordering, while ROUGE-1 would score this pair at 1.0.
Using the rouge_score package
In practice you will use the rouge_score package. Note that the first argument is the reference (called the target) and the second is the generated text (the prediction).
from rouge_score import rouge_scorer
scorer = rouge_scorer.RougeScorer(["rouge1", "rouge2", "rougeL"], use_stemmer=True)
target = "The cat is on the mat."
prediction = "The cat sat on the mat."
scores = scorer.score(target, prediction) # argument order is (target, prediction)
for name, result in scores.items():
print(name, result.precision, result.recall, result.fmeasure)The package lowercases the text, replaces non-alphanumeric characters with spaces, and splits on whitespace. This is why punctuation does not affect the result here. For rougeL it should print 5/6 for all three values, matching the hand calculation. It also stems tokens when use_stemmer=True, which only affects English.
Swapping the arguments flips precision and recall. For ROUGE-L the F1 is unchanged by a swap, since F1 is symmetric, but precision and recall trade places. Many bugs in reported results come from passing the arguments in the wrong order, so check this first when recall looks suspiciously like precision.
Sentence-level and summary-level LCS
The basic ROUGE-L treats the input as one token sequence. For a multi-sentence summary, this has a known weakness: the LCS can chain matches across sentence boundaries, so a sentence from the end of the candidate can pair with one from the start of the reference.
The package offers rougeLsum for this case. It splits both texts into sentences on newline characters, computes an LCS between each reference sentence and the full candidate, and takes the union of the matched tokens. This is a summary-level score. If you use rougeLsum you must put a newline between sentences yourself, because the package does not split sentences for you. If the text has no newlines, rougeLsum behaves as one long sentence.
| Variant | Unit of comparison | Typical use |
|---|---|---|
| `rougeL` | The whole text as one token sequence | Single-sentence outputs |
| `rougeLsum` | Sentences split on newlines, union of LCS matches | Multi-sentence summaries |
Strengths and weaknesses
ROUGE-L has real advantages over ROUGE-N:
- It needs no fixed
n, so you do not choose between unigrams and bigrams. - It rewards correct word order and long shared phrasing, even with insertions.
- It gives credit to near-matches such as "cat sat on" versus "cat is on".
It also has failure modes you should know:
- Stopword inflation. Common words like "the", "of", and "to" often make up much of an LCS, so a candidate can score well on function words alone.
- Order sensitivity. A valid paraphrase that moves a clause scores poorly, as the table above shows.
- Single chain. Only one subsequence is counted. Two separate matching phrases in swapped order contribute only the longer one.
- No meaning. "The dog bit the man" and "The man bit the dog" share an LCS of 4 of 5... after counting, "the", "bit", "the" plus one noun gives 4 of 5 tokens, so the score is high although the meaning flips.
Because of these issues, ROUGE-L is best reported next to ROUGE-1 and ROUGE-2, and not alone.
Multiple references
When you have several references, the package scores the candidate against each one and keeps the best score for each metric in its multi-reference helper. Each metric takes the maximum over references, so precision and recall could come from different references. Decide in advance whether you want this behavior and report it.
Exercise
A candidate is a b c d e and the reference is a c e b d. Compute the LCS length, then ROUGE-L precision, recall, and F1.
Show answer
The LCS is a c e or a b d, with length 3. Both texts have 5 tokens, so precision = 3/5 = 0.6, recall = 3/5 = 0.6, and F1 = 0.6.
Exercise
Why can ROUGE-L give a higher score than ROUGE-2 for the pair "the cat sat on the mat" and "the cat is on the mat"?
Show answer
ROUGE-2 only counts adjacent word pairs, so the single changed word breaks several bigrams, leaving 2 of 5 matching (0.4). ROUGE-L counts words in the same order even with gaps, so it finds an LCS of 5 of 6 tokens (about 0.833).
Exercise
You call scorer.score(prediction, target) by mistake, with the arguments reversed. What changes in the ROUGE-L output, and what stays the same?
Show answer
Precision and recall swap values, because they use the candidate and reference lengths as denominators. The F1 stays the same because it is symmetric in precision and recall.