Sub topic 2
Tokens and n-grams: the raw material of overlap metrics
This chapter assumes you can read basic Python, including collections.Counter. It also assumes you know what precision and recall mean, though the next chapter applies them to text. BLEU and ROUGE compare a candidate text with a reference text by counting how many small pieces they share. Before you can trust those counts, you need to know what a "piece" is and how to count it. Those two choices, tokenization and n-gram counting, change every score you compute later.
From strings to tokens
A token is the unit your metric counts. Overlap metrics never see sentences or meaning. They see lists of tokens. The same sentence can become different lists depending on the tokenizer, and different lists give different scores.
The simplest tokenizer splits on whitespace. A slightly better one lowercases the text and separates punctuation from words.
import re
from collections import Counter
def ws_tokens(text):
return text.split()
def norm_tokens(text):
return re.findall(r"\w+|[^\w\s]", text.lower())
def unigram_overlap(cand, ref):
return sum((Counter(cand) & Counter(ref)).values())
candidate = "The cat sat on the mat."
reference = "the cat is on the mat."
for name, tok in [("whitespace", ws_tokens), ("normalized", norm_tokens)]:
c, r = tok(candidate), tok(reference)
print(name, unigram_overlap(c, r), "of", len(c))
# whitespace 4 of 6
# normalized 6 of 7The strings are identical in both runs. The whitespace tokenizer treats The and the as different tokens, and it treats mat. as a different token from mat. It finds 4 matches out of 6 candidate tokens. The normalized tokenizer finds 6 out of 7. The normalized tokenizer also adds a token, the period, which counts as a match.
The pipeline for every metric in this tutorial starts the same way.
Tokenization choices that change scores
- Case. Lowercasing makes
Theandthematch. Some evaluations keep case on purpose, for example when capitalization is part of translation quality. - Punctuation. Attached punctuation (
mat.) creates tokens that rarely match. Detaching it creates extra tokens that match easily and can inflate scores. - Contractions and hyphens.
didn'tcan stay whole, split intodidnandt, or split intodidandn't. Each choice gives different counts. - Languages without spaces. Chinese and Japanese text has no whitespace between words.
split()returns the whole sentence as one token. Such text needs a word segmenter or character-level tokens. - Subword tokens. Models split rare words into pieces such as
un,##believ,##able. BERTScore works on these pieces. BLEU and ROUGE normally work on words, so do not mix the two without saying so.
What an n-gram is
An n-gram is a run of n consecutive tokens. A 1-gram is a unigram (one word), a 2-gram is a bigram, and a 3-gram is a trigram. N-grams keep a little word order. The unigrams cat, the, sat say nothing about order. The bigram the cat says that the came directly before cat.
A token list of length L has L - n + 1 n-grams of size n. If n is larger than L, there are none.
from collections import Counter
def ngrams(tokens, n):
return Counter(tuple(tokens[i:i + n]) for i in range(len(tokens) - n + 1))
tokens = "the cat is on the mat".split()
print(ngrams(tokens, 1))
# Counter({('the',): 2, ('cat',): 1, ('is',): 1, ('on',): 1, ('mat',): 1})
print(ngrams(tokens, 2))
# Counter({('the', 'cat'): 1, ('cat', 'is'): 1, ('is', 'on'): 1, ('on', 'the'): 1, ('the', 'mat'): 1})
print(sum(ngrams(tokens, 3).values())) # 4
print(ngrams(tokens, 7)) # Counter()Three details in this function matter later.
- Tuples as keys. Lists cannot be dictionary keys because they are mutable. A tuple can be a key.
- Counts, not sets. The unigram
theappears twice, so its count is 2. A set would record only thattheoccurs. BLEU's clipping and ROUGE's recall both depend on how many times an n-gram occurs. - An empty result is valid. A short candidate has no 4-grams. The function returns an empty
Counter, and the metric code must handle the resulting zero total without dividing by it.
Overlap is a multiset intersection
Because the counts are multisets (collections where an item can appear more than once), the shared n-grams are the multiset intersection. Python's & operator on two Counter objects keeps each key with the smaller of its two counts. It drops keys whose result is zero.
def overlap_by_order(candidate, reference, max_n=4):
rows = []
for n in range(1, max_n + 1):
cand = ngrams(candidate, n)
ref = ngrams(reference, n)
shared = sum((cand & ref).values())
rows.append((n, sum(cand.values()), sum(ref.values()), shared))
return rows
cand = "the cat sat on the mat".split()
ref = "the cat is on the mat".split()
for n, c_total, r_total, shared in overlap_by_order(cand, ref):
print(n, c_total, r_total, shared)
# 1 6 6 5
# 2 5 5 3
# 3 4 4 1
# 4 3 3 0| n | Candidate n-grams | Reference n-grams | Shared (clipped) |
|---|---|---|---|
| 1 | 6 | 6 | 5 |
| 2 | 5 | 5 | 3 |
| 3 | 4 | 4 | 1 |
| 4 | 3 | 3 | 0 |
One substituted word, sat for is, removes 1 unigram match but 3 of the 5 bigrams. It removes every 4-gram. Matches fall quickly as n grows because a single wrong token breaks every n-gram that contains it. A token in the middle of the sentence breaks up to n n-grams.
This fast drop is why higher orders reward fluent, locally correct phrasing, and also why they are brittle. A candidate with no shared 4-grams gets a 4-gram precision of 0. A later chapter shows why that can make an unsmoothed BLEU score exactly 0.
Edge cases to check before you score
- Empty strings. An empty candidate gives an empty token list and zero n-grams. Any ratio that divides by the candidate total needs a guard, as in
clipped / total if total else 0.0. - Repeated tokens. A candidate that repeats
theseven times has one unigram type with count 7. Counting types instead of occurrences hides the repetition. Counting occurrences without clipping rewards it. - n-grams across sentence boundaries. If you join a whole document into one token list, you create n-grams that straddle two sentences. Decide whether your metric works per sentence or per document, and build n-grams within each unit.
- Reference tokenization. The reference must go through the same tokenizer as the candidate. Tokenizing one with
split()and the other with a regular expression produces mismatches that look like model errors. - Order inside a multiset. A
Counterignores where an n-gram occurred.the cat sat on the matandon the mat the cat satshare the same bigrams except at the join, and a unigram comparison cannot tell them apart at all. Overlap counts measure shared pieces, not correct arrangement.
A reusable preparation function
Put the tokenizer choice in one place and make every metric call it. This keeps candidate and reference consistent and makes the choice visible.
import re
from collections import Counter
def tokenize(text, lowercase=True):
if lowercase:
text = text.lower()
return re.findall(r"\w+|[^\w\s]", text)
def ngrams(tokens, n):
return Counter(tuple(tokens[i:i + n]) for i in range(len(tokens) - n + 1))
def prepare(candidate_text, reference_text, max_n=4):
cand = tokenize(candidate_text)
ref = tokenize(reference_text)
return (
[ngrams(cand, n) for n in range(1, max_n + 1)],
[ngrams(ref, n) for n in range(1, max_n + 1)],
)
cand_counts, ref_counts = prepare("The cat sat on the mat.", "The cat is on the mat.")
print([sum((c & r).values()) for c, r in zip(cand_counts, ref_counts)])
# [6, 4, 2, 1]Here the period is a token, so it matches in every order, and the mat . adds a shared trigram. The counts are higher than in the earlier table, but the sentences did not change. Only the tokenization did. Keep that in mind whenever someone quotes a score without describing the tokenizer.
Summary of what you now have
- Tokens are the unit of comparison. Your tokenizer is part of the metric.
- An n-gram is a tuple of
nconsecutive tokens. A list of lengthLhasL - n + 1of them. - Counting with
Counterpreserves repetition, which clipping and recall need. Counterintersection gives the shared n-gram counts, and matches fall sharply asnrises.
The next chapter turns these counts into precision, recall, and F1.
Exercise
A candidate has 9 tokens and a reference has 12 tokens. How many trigrams does each have? Then, if the candidate is "a b a b a b a b a" (tokens a and b alternating), what is the Counter of its bigrams, and what does the whitespace tokenizer do to the string "Great job!" compared with the regex tokenizer in this chapter?
Show answer
The candidate has 9 - 3 + 1 = 7 trigrams and the reference has 12 - 3 + 1 = 10. The bigrams of "a b a b a b a b a" are 8 in total, with ('a', 'b') appearing 4 times and ('b', 'a') appearing 4 times, so the Counter is {('a','b'): 4, ('b','a'): 4}. The whitespace tokenizer returns ["Great", "job!"], keeping the case and attaching the exclamation mark to "job!". The regex tokenizer with lowercasing returns ["great", "job", "!"], so the first matches only the exact string "job!" while the second can match "job" and "!" separately.
Exercise
Using the ngrams function from this chapter, write one expression that returns the number of shared bigrams (with clipping) between two token lists cand and ref. Why does it use & instead of set intersection?
Show answer
sum((ngrams(cand, 2) & ngrams(ref, 2)).values()). The & operator on Counter objects keeps each key with the minimum of its two counts, so repeated bigrams are counted as many times as they occur in both lists. Set intersection would count each distinct bigram once and lose repetition, which clipping and recall both depend on.