Sub topic 1
Why generated text is hard to score
Prerequisites
This chapter assumes you know the following:
- Basic Python, including lists, dictionaries, and
collections.Counter. - Precision, recall, and F1 score for classification or retrieval.
- A rough idea of what word embeddings and transformer language models are.
You do not need to know BLEU, ROUGE, or BERTScore yet. This chapter explains why those metrics exist and what problem they try to solve. Later chapters build each one step by step.
The task: grading text that has no single right answer
A classifier is easy to grade. The label is "spam" or it is not, and accuracy is a count of matches. Text generation breaks this model. Machine translation, summarization, captioning, dialogue, and question answering all produce sentences. Many different sentences can be equally good for the same input.
Consider one French sentence and three English translations:
- "The cat is on the mat."
- "There is a cat on the mat."
- "A cat sits on the mat."
All three are acceptable. A system that outputs any of them is correct, yet no two are identical strings. If you compared the system output to one reference with exact string equality, you would mark two of three correct answers as wrong.
This is the evaluation problem for generated text: the space of good outputs is large, and we usually hold only a few examples of it.
Human evaluation is the gold standard but is slow
The most trusted judgment comes from people. Raters read outputs and score them for qualities such as:
- Adequacy: does the output keep the meaning of the source?
- Fluency: is the output grammatical and natural?
- Faithfulness (factuality): does the output avoid claims the source does not support?
- Coherence and relevance: does the output stay on topic and read as a whole?
Human evaluation has three practical costs.
- Money and time. Each system change needs new ratings. A team that tests dozens of model variants per week cannot pay for dozens of rating rounds.
- Variance. Raters disagree with each other. You need clear guidelines, several raters per item, and a measure of agreement.
- No fast loop. Developers need a number in seconds, while training or tuning, not in days.
Automatic metrics fill this gap. They do not replace human judgment. They are cheap stand-ins that you hope track human judgment well enough to guide development.
The reference-based setup
The metrics in this tutorial share one setup. You have a candidate (also called a hypothesis), which is the text your system produced. You also have one or more references, which are texts written by humans for the same input. The metric compares the candidate to the references and returns a number.
The three metric families differ in how they compare the two texts:
| Family | Example | What it compares | Main idea |
|---|---|---|---|
| N-gram precision | BLEU | Word sequences | How much of the candidate appears in the references |
| N-gram recall | ROUGE | Word sequences | How much of the reference appears in the candidate |
| Embedding similarity | BERTScore | Contextual token vectors | How close the candidate tokens are in meaning to the reference tokens |
All of them need references. When you have no reference, these metrics do not apply, and you need other methods such as reference-free quality estimation or model-based judging.
Why exact match fails
Exact match is the simplest reference-based metric. It scores 1 if the candidate equals a reference and 0 otherwise. It fails for the reason shown above: it treats every deviation as total failure, even a harmless one.
references = ["the cat is on the mat"]
candidates = [
"the cat is on the mat", # identical
"the cat sat on the mat", # one word differs
"a dog runs in the park", # unrelated meaning
]
for c in candidates:
print(c in references, "<-", c)This prints True for the first candidate and False for the other two. The second candidate is nearly right and the third is wrong, but exact match cannot tell them apart. A useful metric must give partial credit and must give more credit to the second candidate than to the third.
Partial credit through overlap
The first idea for partial credit is to count how many words the two texts share. The tutorial builds on this idea in the next chapters, so a naive version is worth seeing now.
def naive_overlap(candidate, reference):
cand = candidate.split()
ref = set(reference.split())
hits = sum(1 for word in cand if word in ref)
return hits / len(cand)
reference = "the cat is on the mat"
for c in ["the cat is on the mat", "the cat sat on the mat", "a dog runs in the park"]:
print(round(naive_overlap(c, reference), 3), "<-", c)The output is 1.0, 0.833, and 0.333. The ordering now matches intuition. The nearly right candidate gets a high score, and the unrelated one gets a low score.
The score for the third candidate is not zero because "the" appears in both texts. This already shows a weakness: function words create overlap that says nothing about meaning.
Where naive overlap breaks
Naive overlap has several defects. The named metrics each exist to fix some of them.
Repetition games the score
Take the candidate "the the the the the the the". Every word is in the reference, so naive_overlap returns 1.0. The output is meaningless and gets a perfect score. BLEU fixes this with clipped counts, covered in a later chapter.
Short outputs look precise
The candidate "cat" scores 1.0, because its only word appears in the reference. The metric measures how much of the candidate is correct. It does not measure how much of the reference is covered. BLEU adds a brevity penalty for this. ROUGE instead measures recall, which asks how much of the reference the candidate covers.
Word order is ignored
A bag of words treats "the mat is on the cat" the same as "the cat is on the mat". Both contain the same words, but they describe different situations. N-grams, which are runs of adjacent words, add some sensitivity to order. ROUGE-L uses the longest common subsequence for the same purpose.
Meaning is invisible
The words "automobile" and "car" are different strings, so overlap treats them as unrelated. The same holds for any paraphrase.
reference = "the car is fast"
paraphrase = "the automobile is quick"
print(round(naive_overlap(paraphrase, reference.split() and reference), 3))This prints 0.5. Only "the" and "is" match, though a human would call the two sentences equivalent. This is the gap that BERTScore targets, by comparing contextual embeddings in place of surface strings.
Two ways a metric can be wrong
It helps to separate two kinds of error, because they call for different fixes.
- False negatives. The candidate is good, but the metric scores it low because it uses different words. Paraphrase causes this. Using more references reduces it. So does using embeddings.
- False positives. The candidate is bad, but the metric scores it high because it shares many words with a reference. A fluent sentence with one flipped fact, such as "the drug does not cause nausea" against "the drug causes nausea", loses little overlap yet reverses the meaning.
Keep this pair in mind. When the later chapters introduce each metric, ask which of the two errors it is prone to.
What "good metric" means
You judge an automatic metric by how well it agrees with humans. The standard method is:
- Collect outputs from several systems for the same inputs.
- Get human quality ratings for each output.
- Compute the metric for each output.
- Measure the correlation between metric scores and human ratings, using Pearson, Spearman, or Kendall rank correlation.
Correlation can be measured at two levels, and they give different answers.
- System level: average scores for each system. Metrics usually correlate well here, because averaging cancels noise across many sentences.
- Segment level: scores for single sentences. Correlation is usually much lower, so a single sentence score is a weak signal.
The practical lesson is that a metric may rank systems fairly well while being unreliable on any one output. Do not use a single-sentence BLEU score to decide whether one particular translation is good.
Reference quality and quantity
Because these metrics are reference-based, the references limit them.
- A single reference captures one of many valid outputs. Good candidates that differ from it are penalized.
- Multiple references raise the chance that a good candidate matches something. BLEU and ROUGE both support them, with different rules that later chapters cover.
- Poor references hurt. In summarization datasets, references are sometimes noisy or even unfaithful to the source. A candidate that copies a flawed reference scores well.
- Domain mismatch matters. A metric tuned or validated on news translation may behave differently on code comments, medical notes, or dialogue.
A roadmap for the rest of the tutorial
The chapters that follow solve the defects above one at a time.
- Tokens and n-grams define what is being counted.
- Precision, recall, and F1 define how overlap becomes a score.
- BLEU adds clipping, a brevity penalty, and a geometric mean over n-gram orders. SacreBLEU makes the result reproducible.
- ROUGE-N and ROUGE-L put the emphasis on recall and on word order through the longest common subsequence.
- BERTScore replaces string matching with contextual embedding similarity.
- The final chapters cover what all of these miss and how to choose and report metrics for your task.
Common mistakes to avoid from the start
- Treating the score as the goal. Optimizing a system directly against a metric tends to raise the score faster than real quality. This is a form of Goodhart's law: a measure that becomes a target stops being a good measure.
- Comparing numbers across setups. Scores depend on tokenization, number of references, and options. Two papers reporting "BLEU 30" may not be comparable.
- Reporting one number. A single score hides the failure modes described above. Pair it with examples and, where possible, a human check.
- Ignoring variance. Small test sets and small differences need a significance test or a bootstrap confidence interval.
Exercise
A summarizer outputs the single word "Paris" for a reference summary "The conference will be held in Paris in June." Using the naive_overlap function from this chapter (fraction of candidate words found in the reference), what score does it give, and which defect does this show? Then name a second defect that a different candidate, "Paris in June be held will conference the", would expose.
Show answer
The candidate has one word, "Paris", and it appears in the reference, so naiveoverlap returns 1/1 = 1.0. This shows that short outputs look perfectly precise while covering almost none of the reference; a recall-oriented measure (ROUGE) or a brevity penalty (BLEU) addresses it. The scrambled candidate "Paris in June be held will conference the" uses only words from the reference, so naiveoverlap also returns 1.0 even though it is ungrammatical. This exposes that a bag-of-words overlap ignores word order; n-grams and the longest common subsequence add some order sensitivity.
Exercise
Give one example of a false negative and one example of a false positive for a reference-based overlap metric, using the reference "The drug causes nausea."
Show answer
False negative: the candidate "The medication leads to feeling sick." is a faithful paraphrase but shares only "The" with the reference, so it scores low. False positive: the candidate "The drug does not cause nausea." shares most words with the reference but states the opposite, so it scores relatively high despite being wrong.
Exercise
A new translation system beats the old one by 0.4 BLEU on a test set of 50 sentences. Why should you hesitate to claim it is better, and what two steps would make the comparison more trustworthy?
Show answer
A 0.4 point difference on 50 sentences is likely within noise, and BLEU is a proxy that correlates better with humans at system level over large data than on small samples. Two steps: run a significance test or bootstrap confidence interval on the score difference, and confirm with a human evaluation or a larger test set, while also checking that both systems were scored with identical tokenization and references.