v9.1.1
Menu

ROUGE Score

mediumPROText Generation & AdvancedNLP 3: Advanced

Implement the ROUGE-N metric for evaluating text summarization.

ROUGE-N measures n-gram overlap between a generated summary and a reference summary.

ROUGE-N=∑n-gram∈refmin⁡(countgen(n-gram),countref(n-gram))∑n-gram∈refcountref(n-gram)\text{ROUGE-N} = \frac{\sum_{\text{n-gram} \in \text{ref}} \min(\text{count}_{\text{gen}}(\text{n-gram}), \text{count}_{\text{ref}}(\text{n-gram}))}{\sum_{\text{n-gram} \in \text{ref}} \text{count}_{\text{ref}}(\text{n-gram})}

In simpler terms: sum of clipped overlapping n-gram counts divided by total reference n-gram count.

Function: rouge_n(n, generated, reference)

  • n: n-gram size (integer)
  • generated: generated summary (string of space-separated lowercase words)
  • reference: reference summary (string of space-separated lowercase words)

Returns: the ROUGE-N recall score as a float rounded to 4 decimal places.

Example

Input
1
the cat sat on the mat
the cat sat on a rug
Output
0.6667
Reasoning
  • Inputs: n is 1, so the units being compared are single words. The generated summary is "the cat sat on the mat" and the reference is "the cat sat on a rug", each six words long.
  • Reference counts: the, cat, sat, on, a and rug each appear once, so the reference holds 66 unigrams. This total is the denominator.
  • Generated counts: "the" appears twice, while cat, sat, on and mat appear once each.
  • Clipping: for each reference word, credit is min⁡(countgen,countref)\min(\text{count}_{\text{gen}}, \text{count}_{\text{ref}}). "the" earns min⁡(2,1)=1\min(2, 1) = 1, not 2, because the reference only contains one "the". cat, sat and on earn 1 each, while a and rug earn 0. "mat" is not in the reference, so it never enters the sum.
  • Score: 1+1+1+1+0+06=46≈0.6667\frac{1+1+1+1+0+0}{6} = \frac{4}{6} \approx 0.6667, rounded to 4 decimal places, giving 0.6667.
  • Notice: with n=2n = 2 the same pair scores 35=0.6\frac{3}{5} = 0.6. Only "the cat", "cat sat" and "sat on" match among the reference's 5 bigrams, so longer n-grams punish word-order changes harder.

Constraints

  • N-grams are word-level
  • Clip generated counts to reference counts
  • ROUGE is recall-oriented (denominator = reference n-gram count)
  • If reference has no n-grams (too short), output 0.0
  • Round to 4 decimal places

Learn this in

More from NLP 3: Advanced

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.