diff --git a/metrics/bleu/README.md b/metrics/bleu/README.md index 004d9011..0472cc1e 100644 --- a/metrics/bleu/README.md +++ b/metrics/bleu/README.md @@ -44,7 +44,7 @@ This metric takes as input a list of predicted sentences and a list of lists of >>> bleu = evaluate.load("bleu") >>> results = bleu.compute(predictions=predictions, references=references) >>> print(results) -{'bleu': 1.0, 'precisions': [1.0, 1.0, 1.0, 1.0], 'brevity_penalty': 1.0, 'length_ratio': 1.1666666666666667, 'translation_length': 7, 'reference_length': 6} +{'bleu': 1.0, 'precisions': [1.0, 1.0, 1.0, 1.0], 'brevity_penalty': 1.0, 'length_ratio': 1.0, 'translation_length': 7, 'reference_length': 7} ``` ### Inputs @@ -68,7 +68,7 @@ The default tokenizer is based on whitespace and regexes. It can be replaced by Output Example: ```python -{'bleu': 1.0, 'precisions': [1.0, 1.0, 1.0, 1.0], 'brevity_penalty': 1.0, 'length_ratio': 1.1666666666666667, 'translation_length': 7, 'reference_length': 6} +{'bleu': 1.0, 'precisions': [1.0, 1.0, 1.0, 1.0], 'brevity_penalty': 1.0, 'length_ratio': 1.0, 'translation_length': 7, 'reference_length': 7} ``` BLEU's output is always a number between 0 and 1. This value indicates how similar the candidate text is to the reference texts, with values closer to 1 representing more similar texts. Few human translations will attain a score of 1, since this would indicate that the candidate is identical to one of the reference translations. For this reason, it is not necessary to attain a score of 1. Because there are more opportunities to match, adding additional reference translations will increase the BLEU score. @@ -106,7 +106,7 @@ Example where the first prediction has 2 references: >>> bleu = evaluate.load("bleu") >>> results = bleu.compute(predictions=predictions, references=references) >>> print(results) -{'bleu': 1.0, 'precisions': [1.0, 1.0, 1.0, 1.0], 'brevity_penalty': 1.0, 'length_ratio': 1.1666666666666667, 'translation_length': 7, 'reference_length': 6} +{'bleu': 1.0, 'precisions': [1.0, 1.0, 1.0, 1.0], 'brevity_penalty': 1.0, 'length_ratio': 1.0, 'translation_length': 7, 'reference_length': 7} ``` Example with the word tokenizer from NLTK: @@ -123,7 +123,7 @@ Example with the word tokenizer from NLTK: ... ] >>> results = bleu.compute(predictions=predictions, references=references, tokenizer=word_tokenize) >>> print(results) -{'bleu': 1.0, 'precisions': [1.0, 1.0, 1.0, 1.0], 'brevity_penalty': 1.0, 'length_ratio': 1.1666666666666667, 'translation_length': 7, 'reference_length': 6} +{'bleu': 1.0, 'precisions': [1.0, 1.0, 1.0, 1.0], 'brevity_penalty': 1.0, 'length_ratio': 1.0, 'translation_length': 7, 'reference_length': 7} ``` ## Limitations and Bias diff --git a/metrics/bleu/bleu.py b/metrics/bleu/bleu.py index 38a10c3b..954ca91c 100644 --- a/metrics/bleu/bleu.py +++ b/metrics/bleu/bleu.py @@ -13,14 +13,40 @@ # limitations under the License. """ BLEU metric. """ +import collections +import math + import datasets import evaluate -from .nmt_bleu import compute_bleu # From: https://github.com/tensorflow/nmt/blob/master/nmt/scripts/bleu.py from .tokenizer_13a import Tokenizer13a +def _ngram_counts(segment, max_order): + return collections.Counter( + tuple(segment[i : i + order]) for order in range(1, max_order + 1) for i in range(len(segment) - order + 1) + ) + + +def _ngram_precisions(reference_corpus, translation_corpus, max_order=4, smooth=False): + """Clipped n-gram precisions, as in https://github.com/tensorflow/nmt/blob/master/nmt/scripts/bleu.py""" + matches_by_order = [0] * max_order + possible_matches_by_order = [0] * max_order + for references, translation in zip(reference_corpus, translation_corpus): + merged_ref_ngram_counts = collections.Counter() + for reference in references: + merged_ref_ngram_counts |= _ngram_counts(reference, max_order) + overlap = _ngram_counts(translation, max_order) & merged_ref_ngram_counts + for ngram, count in overlap.items(): + matches_by_order[len(ngram) - 1] += count + for order in range(1, max_order + 1): + possible_matches_by_order[order - 1] += max(len(translation) - order + 1, 0) + if smooth: + return [(m + 1.0) / (p + 1.0) for m, p in zip(matches_by_order, possible_matches_by_order)] + return [m / p if p > 0 else 0.0 for m, p in zip(matches_by_order, possible_matches_by_order)] + + _CITATION = """\ @INPROCEEDINGS{Papineni02bleu:a, author = {Kishore Papineni and Salim Roukos and Todd Ward and Wei-jing Zhu}, @@ -81,6 +107,22 @@ >>> results = bleu.compute(predictions=predictions, references=references) >>> print(results["bleu"]) 1.0 + + With several references, the brevity penalty uses the reference closest in length to the prediction: + + >>> predictions = ["the cat sat on the mat today"] + >>> references = [["the cat sat on the mat today in the sun", "the cat sat"]] + >>> results = bleu.compute(predictions=predictions, references=references) + >>> print(results["reference_length"], round(results["brevity_penalty"], 4)) + 10 0.6514 + + An empty alternate reference is allowed: + + >>> predictions = ["a valid four word answer"] + >>> references = [["a valid four word answer", ""]] + >>> results = bleu.compute(predictions=predictions, references=references) + >>> print(results["bleu"], results["reference_length"]) + 1.0 5 """ @@ -119,10 +161,19 @@ def _compute(self, predictions, references, tokenizer=Tokenizer13a(), max_order= references = [[tokenizer(r) for r in ref] for ref in references] predictions = [tokenizer(p) for p in predictions] - score = compute_bleu( - reference_corpus=references, translation_corpus=predictions, max_order=max_order, smooth=smooth + precisions = _ngram_precisions(references, predictions, max_order=max_order, smooth=smooth) + translation_length = sum(len(p) for p in predictions) + # The brevity penalty uses the reference whose length is closest to the prediction (ties go to + # the shorter one), as in Papineni et al. (2002), multi-bleu.perl, sacrebleu and NLTK. The TF + # nmt `compute_bleu` this metric used to call takes the *shortest* reference instead, and + # divides by its length before returning, so an empty alternate reference made it crash. + reference_length = sum( + min((abs(len(r) - len(p)), len(r)) for r in refs)[1] for refs, p in zip(references, predictions) ) - (bleu, precisions, bp, ratio, translation_length, reference_length) = score + geo_mean = math.exp(sum(math.log(p) for p in precisions) / max_order) if min(precisions) > 0 else 0.0 + ratio = translation_length / reference_length if reference_length > 0 else float("inf") + bp = 1.0 if ratio > 1.0 else (math.exp(1 - 1.0 / ratio) if ratio > 0 else 0.0) + bleu = geo_mean * bp return { "bleu": bleu, "precisions": precisions,