nist_score.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. # -*- coding: utf-8 -*-
  2. # Natural Language Toolkit: NIST Score
  3. #
  4. # Copyright (C) 2001-2020 NLTK Project
  5. # Authors:
  6. # Contributors:
  7. # URL: <http://nltk.org/>
  8. # For license information, see LICENSE.TXT
  9. """NIST score implementation."""
  10. import math
  11. import fractions
  12. from collections import Counter
  13. from nltk.util import ngrams
  14. def sentence_nist(references, hypothesis, n=5):
  15. """
  16. Calculate NIST score from
  17. George Doddington. 2002. "Automatic evaluation of machine translation quality
  18. using n-gram co-occurrence statistics." Proceedings of HLT.
  19. Morgan Kaufmann Publishers Inc. http://dl.acm.org/citation.cfm?id=1289189.1289273
  20. DARPA commissioned NIST to develop an MT evaluation facility based on the BLEU
  21. score. The official script used by NIST to compute BLEU and NIST score is
  22. mteval-14.pl. The main differences are:
  23. - BLEU uses geometric mean of the ngram overlaps, NIST uses arithmetic mean.
  24. - NIST has a different brevity penalty
  25. - NIST score from mteval-14.pl has a self-contained tokenizer
  26. Note: The mteval-14.pl includes a smoothing function for BLEU score that is NOT
  27. used in the NIST score computation.
  28. >>> hypothesis1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',
  29. ... 'ensures', 'that', 'the', 'military', 'always',
  30. ... 'obeys', 'the', 'commands', 'of', 'the', 'party']
  31. >>> hypothesis2 = ['It', 'is', 'to', 'insure', 'the', 'troops',
  32. ... 'forever', 'hearing', 'the', 'activity', 'guidebook',
  33. ... 'that', 'party', 'direct']
  34. >>> reference1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'that',
  35. ... 'ensures', 'that', 'the', 'military', 'will', 'forever',
  36. ... 'heed', 'Party', 'commands']
  37. >>> reference2 = ['It', 'is', 'the', 'guiding', 'principle', 'which',
  38. ... 'guarantees', 'the', 'military', 'forces', 'always',
  39. ... 'being', 'under', 'the', 'command', 'of', 'the',
  40. ... 'Party']
  41. >>> reference3 = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the',
  42. ... 'army', 'always', 'to', 'heed', 'the', 'directions',
  43. ... 'of', 'the', 'party']
  44. >>> sentence_nist([reference1, reference2, reference3], hypothesis1) # doctest: +ELLIPSIS
  45. 3.3709...
  46. >>> sentence_nist([reference1, reference2, reference3], hypothesis2) # doctest: +ELLIPSIS
  47. 1.4619...
  48. :param references: reference sentences
  49. :type references: list(list(str))
  50. :param hypothesis: a hypothesis sentence
  51. :type hypothesis: list(str)
  52. :param n: highest n-gram order
  53. :type n: int
  54. """
  55. return corpus_nist([references], [hypothesis], n)
  56. def corpus_nist(list_of_references, hypotheses, n=5):
  57. """
  58. Calculate a single corpus-level NIST score (aka. system-level BLEU) for all
  59. the hypotheses and their respective references.
  60. :param references: a corpus of lists of reference sentences, w.r.t. hypotheses
  61. :type references: list(list(list(str)))
  62. :param hypotheses: a list of hypothesis sentences
  63. :type hypotheses: list(list(str))
  64. :param n: highest n-gram order
  65. :type n: int
  66. """
  67. # Before proceeding to compute NIST, perform sanity checks.
  68. assert len(list_of_references) == len(
  69. hypotheses
  70. ), "The number of hypotheses and their reference(s) should be the same"
  71. # Collect the ngram coounts from the reference sentences.
  72. ngram_freq = Counter()
  73. total_reference_words = 0
  74. for (
  75. references
  76. ) in list_of_references: # For each source sent, there's a list of reference sents.
  77. for reference in references:
  78. # For each order of ngram, count the ngram occurrences.
  79. for i in range(1, n + 1):
  80. ngram_freq.update(ngrams(reference, i))
  81. total_reference_words += len(reference)
  82. # Compute the information weights based on the reference sentences.
  83. # Eqn 2 in Doddington (2002):
  84. # Info(w_1 ... w_n) = log_2 [ (# of occurrences of w_1 ... w_n-1) / (# of occurrences of w_1 ... w_n) ]
  85. information_weights = {}
  86. for _ngram in ngram_freq: # w_1 ... w_n
  87. _mgram = _ngram[:-1] # w_1 ... w_n-1
  88. # From https://github.com/moses-smt/mosesdecoder/blob/master/scripts/generic/mteval-v13a.pl#L546
  89. # it's computed as such:
  90. # denominator = ngram_freq[_mgram] if _mgram and _mgram in ngram_freq else denominator = total_reference_words
  91. # information_weights[_ngram] = -1 * math.log(ngram_freq[_ngram]/denominator) / math.log(2)
  92. #
  93. # Mathematically, it's equivalent to the our implementation:
  94. if _mgram and _mgram in ngram_freq:
  95. numerator = ngram_freq[_mgram]
  96. else:
  97. numerator = total_reference_words
  98. information_weights[_ngram] = math.log(numerator / ngram_freq[_ngram], 2)
  99. # Micro-average.
  100. nist_precision_numerator_per_ngram = Counter()
  101. nist_precision_denominator_per_ngram = Counter()
  102. l_ref, l_sys = 0, 0
  103. # For each order of ngram.
  104. for i in range(1, n + 1):
  105. # Iterate through each hypothesis and their corresponding references.
  106. for references, hypothesis in zip(list_of_references, hypotheses):
  107. hyp_len = len(hypothesis)
  108. # Find reference with the best NIST score.
  109. nist_score_per_ref = []
  110. for reference in references:
  111. _ref_len = len(reference)
  112. # Counter of ngrams in hypothesis.
  113. hyp_ngrams = (
  114. Counter(ngrams(hypothesis, i))
  115. if len(hypothesis) >= i
  116. else Counter()
  117. )
  118. ref_ngrams = (
  119. Counter(ngrams(reference, i)) if len(reference) >= i else Counter()
  120. )
  121. ngram_overlaps = hyp_ngrams & ref_ngrams
  122. # Precision part of the score in Eqn 3
  123. _numerator = sum(
  124. information_weights[_ngram] * count
  125. for _ngram, count in ngram_overlaps.items()
  126. )
  127. _denominator = sum(hyp_ngrams.values())
  128. _precision = 0 if _denominator == 0 else _numerator / _denominator
  129. nist_score_per_ref.append(
  130. (_precision, _numerator, _denominator, _ref_len)
  131. )
  132. # Best reference.
  133. precision, numerator, denominator, ref_len = max(nist_score_per_ref)
  134. nist_precision_numerator_per_ngram[i] += numerator
  135. nist_precision_denominator_per_ngram[i] += denominator
  136. l_ref += ref_len
  137. l_sys += hyp_len
  138. # Final NIST micro-average mean aggregation.
  139. nist_precision = 0
  140. for i in nist_precision_numerator_per_ngram:
  141. precision = (
  142. nist_precision_numerator_per_ngram[i]
  143. / nist_precision_denominator_per_ngram[i]
  144. )
  145. nist_precision += precision
  146. # Eqn 3 in Doddington(2002)
  147. return nist_precision * nist_length_penalty(l_ref, l_sys)
  148. def nist_length_penalty(ref_len, hyp_len):
  149. """
  150. Calculates the NIST length penalty, from Eq. 3 in Doddington (2002)
  151. penalty = exp( beta * log( min( len(hyp)/len(ref) , 1.0 )))
  152. where,
  153. `beta` is chosen to make the brevity penalty factor = 0.5 when the
  154. no. of words in the system output (hyp) is 2/3 of the average
  155. no. of words in the reference translation (ref)
  156. The NIST penalty is different from BLEU's such that it minimize the impact
  157. of the score of small variations in the length of a translation.
  158. See Fig. 4 in Doddington (2002)
  159. """
  160. ratio = hyp_len / ref_len
  161. if 0 < ratio < 1:
  162. ratio_x, score_x = 1.5, 0.5
  163. beta = math.log(score_x) / math.log(ratio_x) ** 2
  164. return math.exp(beta * math.log(ratio) ** 2)
  165. else: # ratio <= 0 or ratio >= 1
  166. return max(min(ratio, 1.0), 0.0)