Algorithmadvanced
chrF
Also called character n-gram F-score.
An F-score of character n-gram precision and recall between a translation and a reference, weighting recall more. Higher is better, from 0 to 1, at the corpus level.
- Time
- O(N² L log L) worst
- Space
- O(N L) extra
- Where
- L = the number of characters in all hypotheses and references; N = the largest n-gram order
- Model
- Word RAM
- Properties
- deterministicexactonlineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Maja Popović, 2015
chrF scores a machine translation output against a reference by its character n-grams. It averages the precision and the recall of the character n-grams of orders 1 to 6, with white space removed, and combines them into an F-score that weights recall times as much as precision. The score goes from 0 to 1 (sacreBLEU prints it times 100), higher is better, and sacreBLEU computes it at the corpus level from summed counts. It needs no word tokenizer, so it is less sensitive than BLEU to tokenization and to word endings.
In plain words
Remove the spaces from the machine output and from the human translation. Then look at every piece of 1 character, 2 characters, and so on up to 6 characters.
Precision asks what share of the pieces of the output also appear in the reference. Recall asks what share of the pieces of the reference also appear in the output. A piece counts at most as often as it appears on the other side.
chrF averages the precision over the six piece lengths, and the recall too, and then combines the two numbers. With the usual setting the recall counts more, so missing content costs more than extra content.
Because the pieces are short, "read" and "reads" share most of their pieces, and a wrong word ending loses only a little.
The problem
A hypothesis and a reference are strings. Let and be the same strings with all white space removed. For a string , is the number of times the character -gram occurs in . Summed over the corpus, the matches, the hypothesis -grams and the reference -grams of order are
Let be the set of orders with and . Then
and the score is 0 if is empty or . Popović (2015) wrote the formula with the averages over the orders as in her Equation 1. The settings here are those of sacreBLEU: , , the case kept, and white space removed. Higher is better.
Tokenization. There is no word tokenization. The only step is to delete every white-space character, so "the cat" and "thecat" give the same n-grams. The text is not lowercased.
The algorithm
The input is a list of hypotheses, each with its references, the order and . With several references, each sentence uses the reference that gives it the highest sentence chrF.
CHRF(Y, X, N, β) ▷ Y: hypotheses, X_y: the chosen reference of y- 1
M_n ← 0, H_n ← 0, E_n ← 0 for n = 1 .. N - 2
for each hypothesis y with its reference x do - 3
h ← y without white space; r ← x without white space - 4
for n ← 1 to N do - 5
M_n ← M_n + Σ over distinct n-grams g of h of min(count_h(g), count_r(g)) - 6
H_n ← H_n + max(|h| - n + 1, 0); E_n ← E_n + max(|r| - n + 1, 0) - 7
K ← the orders n with H_n > 0 and E_n > 0 - 8
if K is empty then return 0 - 9
P ← (1/|K|) Σ_{n in K} M_n / H_n; R ← (1/|K|) Σ_{n in K} M_n / E_n - 10
if P + R = 0 then return 0 - 11
return (1 + β²) P R / (β² P + R)
Lines L1 to L6 collect integers. Line L5 takes the size of the multiset intersection of the two sets of -grams, which is the clipped match count of BLEU with one reference. Line L7 is the effective order of sacreBLEU: an order where one side has no -gram at all (a text shorter than characters) is left out of both averages, instead of adding a precision of 0. Line L11 is the weighted harmonic mean of and .
chrF++. Popović (2017) adds word -grams of orders 1 and 2. Their statistics are computed in the same way, on words, and lines L7 to L11 average over all 8 orders together. sacreBLEU splits words on white space and then splits one punctuation mark off the end of a word, or else off its start.
Example
The hypothesis "the cats" has the reference "the cat". Without spaces, = "thecats" (7 characters) and = "thecat" (6 characters). Every -gram of occurs in .
| precision | recall | ||||
|---|---|---|---|---|---|
| 1 | 6 | 7 | 6 | 6/7 | 1 |
| 2 | 5 | 6 | 5 | 5/6 | 1 |
| 3 | 4 | 5 | 4 | 4/5 | 1 |
| 4 | 3 | 4 | 3 | 3/4 | 1 |
| 5 | 2 | 3 | 2 | 2/3 | 1 |
| 6 | 1 | 2 | 1 | 1/2 | 1 |
So and . With , . With it is . The extra "s" costs little under , because it lowers only the precision.
A short check: the hypothesis "ab" against "abc" with gives , and .
Correctness
The claim is that the procedure returns the value of the formula and that it is in . Line L5 sums over the distinct -grams of , which equals the sum over all -grams because the others add 0. Each match count is at most both totals, so and are in . When both are positive, , so the score is a weighted harmonic mean and lies between and . With it is symmetric in the hypothesis and the reference. These are theorems; the full proof is in the proofs file.
How well the score agrees with human judgments is measured, not proved.
Proof: chrF computes the F-score of the averaged character n-gram precision and recall, a value in [0, 1]full
Fix the maximum order , the weight and a corpus of pairs of a hypothesis and the reference chosen for it, each a string. Let and be the strings with all white space removed. For a string and a string of characters, is the number of positions where occurs in . The definition is
the set , the averages and , and
with when is empty or .
Lemma 1 (the counts). After lines L1 to L6, the statistics hold , and .
Proof. Line L1 sets them to 0. For each pair, line L3 removes the white space, and for each order line L5 adds over the distinct -grams of . An -gram that does not occur in adds 0 to the definition, so this is the sum over all . A string of length has positions where an -gram starts, which line L6 adds. The sums over follow because addition is commutative.
Lemma 2 (precision and recall). For each , and . Hence and .
Proof. Each term of is at most and at most . Summing over gives and for each pair, and so for the sums. An average of numbers in is in .
Theorem. The procedure returns of the definition, and . Moreover, when and ,
so the score is a weighted harmonic mean of and with weight on the recall, and .
Proof. By Lemma 1, line L7 computes . Lines L8 and L10 return 0 in the two cases where the definition gives 0. Otherwise line L9 computes and and line L11 returns the formula. The denominator is positive because and .
If or (but not both), the numerator is 0 and the score is 0, which is in and equal to . If both are positive, dividing by gives the displayed identity. A weighted harmonic mean with positive weights that sum to 1 lies between the smallest and the largest of the values, so the score is between and , which are in by Lemma 2.
Corollary (recall weight). For fixed , the score tends to as and to as . With the score is symmetric: exchanging the hypotheses and the references exchanges and , which keeps and exchanges and , and does not change.
Proof. The weights of the identity are and , which tend to and . The symmetry follows because is symmetric in the two strings and the condition for is symmetric.
Remark (several references). For a sentence with several references, the implementation computes the sentence score against each and keeps the statistics of the best one, the first on a tie. The theorem holds for any choice of one reference per sentence, so it holds for this one.
Remark (chrF++). With word -grams of orders , the statistics of the word orders are appended to those of the character orders, and lines L7 to L11 average over all of them. Lemma 1 and Lemma 2 hold for each order with words in place of characters, so the theorem holds unchanged.
Remark (complexity). For a hypothesis of characters and a reference of , order needs the counts of strings of characters, which takes expected time with hashing. Over , all references and the whole corpus with characters, this is expected time.
Complexity
Let be the number of characters in all hypotheses and references. Order counts -grams of characters, so the counting costs expected time with a hash table, or in the worst case with sorting. With references per sentence, each reference is scored once, and includes all of them. One sentence at a time needs space for its counts, and the corpus needs only numbers.
Properties
- Range and direction. From 0 to 1, higher is better (a theorem). sacreBLEU prints it times 100.
- Corpus level. sacreBLEU sums the counts over the corpus and computes the score once. The sentence score is the same formula on one sentence.
- Recall weighted. With the recall has four times the weight of the precision in the harmonic mean (a theorem about the formula). In Popović (2015), chrF3 agreed better with human judgments than chrF1 (a measurement).
- No tokenizer. Without word orders, the score does not change if spaces are added or removed. It does change with the case and with punctuation.
- Morphology. Words with the same stem share most of their n-grams, so a wrong inflection is only a small error. This helps for languages with rich morphology.
- Symmetric for beta 1. chrF1 does not change if the hypothesis and the reference change places.
Variants and improvements
- The beta. Popović (2015) found chrF3 the most promising on the WMT14 data, with chosen without tuning. sacreBLEU and the WMT tasks use .
- chrF++. Word unigrams and bigrams in the average. Popović (2017) found that this agrees better with human judgments in many language pairs (a measurement).
- White space as a character. sacreBLEU can keep the spaces. Popović (2015) found no gain from this.
- Per-order averaging of F. sacreBLEU has an option that computes an F-score per order and averages the F-scores, to match older scripts. It gives other numbers from the same counts.
- Other scores. BLEU uses word n-grams and only precision. TER counts edits. COMET is a trained model.
When to use it
Use chrF next to BLEU when the target language has rich morphology or no spaces between words, and when you do not want to depend on a word tokenizer. It is cheap and needs no model. Report the sacreBLEU signature, because , , the word order and the white-space setting all change the number. For final claims about quality, a trained metric or a human evaluation is better.
Pitfalls
- Settings not stated. chrF1, chrF2, chrF3 and chrF++ are different scores. State and the word order.
- Mean of sentence scores. The mean of sentence chrF is not corpus chrF. Use one of the two and say which.
- Short texts. For a text shorter than six characters, the effective order leaves out the higher orders. Without this rule the precision of those orders would be 0 and the score would drop.
- Case and punctuation. They count as characters. Lowercasing or removing punctuation gives another score.
- Spaces are lost. "a part" and "apart" give the same n-grams, so an error in word boundaries is not seen.
Implementations
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/chrf/. The authors are listed in prov/TFBFZV.jsonl.
"""chrF of Popovic (2015), with the settings of sacreBLEU, at the corpus level.
The input is plain text: a hypothesis is a str, and each hypothesis has a list
of one or more reference strs. White space is removed before the character
n-grams are counted, and the case is kept. With word_order > 0 the score is
chrF++ (Popovic 2017): word n-grams of order 1 .. word_order are added to the
average, and a punctuation mark at the start or the end of a word is split off,
as sacreBLEU does.
Effective order: an order counts in the average only if both the hypothesis
side and the reference side have at least one n-gram of that order (summed over
the corpus). With several references, each sentence uses the statistics of the
reference with the highest sentence-level F, the first one on a tie.
The statistics and the averages are exact Fractions. The scores are floats on
the 0 to 1 scale; sacreBLEU prints them times 100.
"""
import string
from collections import Counter
from fractions import Fraction
from typing import List, Sequence, Tuple
Stats = List[Tuple[int, int, int]] # per order: (matches, hypothesis n-grams, reference n-grams)
PUNCTUATION = frozenset(string.punctuation)
def ngram_counts(units: Sequence, n: int) -> Counter:
"""Return the multiset of the n-grams of a str or a list of words."""
return Counter(tuple(units[i:i + n]) for i in range(len(units) - n + 1))
def split_words(text: str) -> List[str]:
"""Split on white space, then split one punctuation mark off the end or the start of a word."""
out = []
for w in text.split():
if len(w) > 1 and w[-1] in PUNCTUATION:
out += [w[:-1], w[-1]]
elif len(w) > 1 and w[0] in PUNCTUATION:
out += [w[0], w[1:]]
else:
out.append(w)
return out
def sentence_stats(hyp: str, ref: str, char_order: int = 6, word_order: int = 0,
whitespace: bool = False) -> Stats:
"""Return (matches, hypothesis total, reference total) for each order, characters first."""
h, r = (hyp, ref) if whitespace else ("".join(hyp.split()), "".join(ref.split())) # @line L3
stats = []
units = [(h, r, n) for n in range(1, char_order + 1)]
hw, rw = split_words(hyp), split_words(ref)
units += [(hw, rw, n) for n in range(1, word_order + 1)]
for a, b, n in units: # @line L4
ca, cb = ngram_counts(a, n), ngram_counts(b, n)
m = sum(min(k, cb[g]) for g, k in ca.items()) # @line L5
stats.append((m, max(len(a) - n + 1, 0), max(len(b) - n + 1, 0))) # @line L6
return stats
def f_score(stats: Stats, beta: float = 2) -> Fraction:
"""Return the chrF of summed statistics as a Fraction in [0, 1]."""
used = [(m, th, tr) for m, th, tr in stats if th > 0 and tr > 0] # @line L7
if not used: # @line L8
return Fraction(0)
k = len(used)
p = sum(Fraction(m, th) for m, th, _ in used) / k # @line L9
r = sum(Fraction(m, tr) for m, _, tr in used) / k
if p + r == 0: # @line L10
return Fraction(0)
b2 = Fraction(beta) ** 2
return (1 + b2) * p * r / (b2 * p + r) # @line L11
def best_stats(hyp: str, refs: Sequence[str], char_order: int = 6, word_order: int = 0,
beta: float = 2, whitespace: bool = False) -> Stats:
"""Return the statistics against the reference with the highest sentence F."""
if not refs:
raise ValueError("each hypothesis needs at least one reference")
best, best_f = None, None
for ref in refs:
st = sentence_stats(hyp, ref, char_order, word_order, whitespace)
f = f_score(st, beta)
if best is None or f > best_f:
best, best_f = st, f
return best
def corpus_stats(hyps: Sequence[str], refs: Sequence[Sequence[str]], char_order: int = 6,
word_order: int = 0, beta: float = 2, whitespace: bool = False) -> Stats:
"""Return the statistics summed over the corpus."""
if len(hyps) != len(refs):
raise ValueError("one list of references per hypothesis")
total = [(0, 0, 0)] * (char_order + word_order) # @line L1
for hyp, rs in zip(hyps, refs): # @line L2
st = best_stats(hyp, rs, char_order, word_order, beta, whitespace)
total = [(a + x, b + y, c + z) for (a, b, c), (x, y, z) in zip(total, st)]
return total
def corpus_chrf(hyps: Sequence[str], refs: Sequence[Sequence[str]], char_order: int = 6,
word_order: int = 0, beta: float = 2, whitespace: bool = False) -> float:
"""Return corpus chrF (chrF++ with word_order = 2) on the 0 to 1 scale."""
st = corpus_stats(hyps, refs, char_order, word_order, beta, whitespace)
return float(f_score(st, beta))
def sentence_chrf(hyp: str, refs: Sequence[str], char_order: int = 6, word_order: int = 0,
beta: float = 2, whitespace: bool = False) -> float:
"""Return the chrF of one sentence on the 0 to 1 scale."""
return corpus_chrf([hyp], [refs], char_order, word_order, beta, whitespace)
test_chrf.py 105 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/chrf/. The authors are listed in prov/TFBFZV.jsonl.
import random
from fractions import Fraction
from chrf import corpus_chrf, corpus_stats, f_score, sentence_chrf, sentence_stats, split_words
def brute_matches(a, b, n):
"""Size of the multiset intersection of the n-grams, by removing items from a list."""
rest = [tuple(b[i:i + n]) for i in range(len(b) - n + 1)]
m = 0
for i in range(len(a) - n + 1):
g = tuple(a[i:i + n])
if g in rest:
rest.remove(g)
m += 1
return m
def brute_chrf(hyp, ref, order, beta):
h, r = "".join(hyp.split()), "".join(ref.split())
ps, rs = [], []
for n in range(1, order + 1):
th, tr = len(h) - n + 1, len(r) - n + 1
if th > 0 and tr > 0:
m = brute_matches(h, r, n)
ps.append(m / th)
rs.append(m / tr)
if not ps:
return 0.0
p, rc = sum(ps) / len(ps), sum(rs) / len(rs)
if p + rc == 0:
return 0.0
return (1 + beta * beta) * p * rc / (beta * beta * p + rc)
def test_hand_value():
assert f_score(sentence_stats("ab", "abc", 2)) == Fraction(7, 11)
def test_page_example():
st = sentence_stats("the cats", "the cat")
assert st == [(6, 7, 6), (5, 6, 5), (4, 5, 4), (3, 4, 3), (2, 3, 2), (1, 2, 1)]
assert abs(sentence_chrf("the cats", ["the cat"]) - 0.932588) < 1e-6
assert abs(sentence_chrf("the cats", ["the cat"], beta=1) - 0.846946) < 1e-6
def test_edges():
assert sentence_chrf("a cat", ["a cat"]) == 1.0
assert sentence_chrf("xyz", ["abc"]) == 0.0
assert sentence_chrf("", ["abc"]) == 0.0
assert sentence_chrf("", [""]) == 0.0
# white space does not count, so these are equal
assert sentence_chrf("thecat", ["the cat"]) == 1.0
def test_symmetry_of_chrf1():
rng = random.Random(5)
for _ in range(100):
a = "".join(rng.choice("ab c") for _ in range(rng.randint(0, 10)))
b = "".join(rng.choice("ab c") for _ in range(rng.randint(0, 10)))
assert sentence_chrf(a, [b], beta=1) == sentence_chrf(b, [a], beta=1)
def test_random_against_brute_force():
rng = random.Random(2015)
for _ in range(300):
hyp = "".join(rng.choice("abc ") for _ in range(rng.randint(0, 12)))
ref = "".join(rng.choice("abc ") for _ in range(rng.randint(0, 12)))
beta = rng.choice([1, 2, 3])
order = rng.randint(1, 6)
st = sentence_stats(hyp, ref, order)
h, r = "".join(hyp.split()), "".join(ref.split())
for n in range(1, order + 1):
assert st[n - 1][0] == brute_matches(h, r, n)
got = sentence_chrf(hyp, [ref], order, beta=beta)
assert abs(got - brute_chrf(hyp, ref, order, beta)) < 1e-12
assert 0.0 <= got <= 1.0
def test_large_beta_tends_to_recall():
st = sentence_stats("the cats", "the cat")
assert abs(float(f_score(st, 1000)) - 1.0) < 1e-5
st2 = sentence_stats("the cat", "the cats")
assert float(f_score(st2, 1000)) < 0.74
def test_best_reference_and_corpus():
one = corpus_stats(["the cat"], [["a dog", "the cat"]])
assert one == sentence_stats("the cat", "the cat")
hyps, refs = ["the cats", "a dog ran"], [["the cat"], ["a dog runs"]]
c = corpus_chrf(hyps, refs)
mean = (sentence_chrf(hyps[0], refs[0]) + sentence_chrf(hyps[1], refs[1])) / 2
assert abs(c - mean) > 1e-4
def test_chrf_plus_plus_words():
assert split_words("Hello, world!") == ["Hello", ",", "world", "!"]
assert split_words("(hi) a .") == ["(hi", ")", "a", "."]
assert split_words("'tis") == ["'", "tis"]
st = sentence_stats("the cats", "the cat", 6, 2)
assert st[6:] == [(1, 2, 2), (0, 1, 1)]
assert sentence_chrf("a b", ["a b"], word_order=2) == 1.0
History
Maja Popović proposed chrF at the WMT 2015 metrics task. She tested n-grams of up to 6 characters and several values of , and found that six-grams worked best and that looked most promising on the WMT14 data. She added word n-grams as chrF++ in 2017. Matt Post included chrF in sacreBLEU in 2018 with , and since then many papers report chrF next to BLEU.
References
- Maja Popović, chrF, character n-gram F-score for automatic MT evaluation, Tenth Workshop on Statistical Machine Translation, 2015, pages 392 to 395, Equation 1 (the F-score of the averaged precision and recall), and the experiments on WMT12 to WMT14 (six-grams best, spaces ignored, beta 3 the most promising)
- Popović 2017, the word n-grams of order 1 and 2 added to the average
- Matt Post, A Call for Clarity in Reporting BLEU Scores, Third Conference on Machine Translation (WMT), 2018, pages 186 to 191, sacreBLEU, which provides the reference implementation of chrF used here
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 | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag TFBFZV Edit this page History Report an error Markdown