diff --git a/metrics/nist_mt/nist_mt.py b/metrics/nist_mt/nist_mt.py index 5aeab0c08..372b5d658 100644 --- a/metrics/nist_mt/nist_mt.py +++ b/metrics/nist_mt/nist_mt.py @@ -62,7 +62,7 @@ Args: predictions: predictions to score (list of str) references: potentially multiple references for each prediction (list of str or list of list of str) - n: highest n-gram order + n: highest n-gram order. Orders longer than every tokenized prediction are skipped. lowercase: whether to lowercase the data (only applicable if 'western_lang' is True) western_lang: whether the current language is a Western language, which will enable some specific tokenization rules with respect to, e.g., punctuation @@ -129,4 +129,12 @@ def _compute(self, predictions, references, n: int = 5, lowercase=False, western ] for ref_sentences in references ] - return {"nist_mt": corpus_nist(list_of_references=references, hypotheses=predictions, n=n)} + # NLTK divides by the corpus count of candidate n-grams for every order. + max_prediction_tokens = max(map(len, predictions)) + if max_prediction_tokens == 0: + return {"nist_mt": 0.0} + return { + "nist_mt": corpus_nist( + list_of_references=references, hypotheses=predictions, n=min(n, max_prediction_tokens) + ) + } diff --git a/tests/test_nist_short_predictions.py b/tests/test_nist_short_predictions.py new file mode 100644 index 000000000..5948e368d --- /dev/null +++ b/tests/test_nist_short_predictions.py @@ -0,0 +1,28 @@ +from pathlib import Path + +import pytest + +import evaluate + + +@pytest.fixture +def nist(tmp_path): + nltk = pytest.importorskip("nltk") + try: + nltk.data.find("misc/perluniprops") + except LookupError: + pytest.skip("NLTK perluniprops data is required") + path = Path(__file__).resolve().parents[1] / "metrics" / "nist_mt" + return evaluate.load(str(path), cache_dir=str(tmp_path), keep_in_memory=True) + + +def test_nist_short_predictions_use_available_ngram_orders(nist): + values = {"predictions": ["sunny here"], "references": [["it is sunny here", "it is quite sunny here"]]} + + expected = nist.compute(**values, n=2) + assert expected["nist_mt"] > 0 + assert nist.compute(**values) == expected + + +def test_nist_empty_predictions_have_zero_score(nist): + assert nist.compute(predictions=["", " "], references=["sunny here", "it is raining"]) == {"nist_mt": 0.0}