meteor_score.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. # -*- coding: utf-8 -*-
  2. # Natural Language Toolkit: Machine Translation
  3. #
  4. # Copyright (C) 2001-2020 NLTK Project
  5. # Author: Uday Krishna <udaykrishna5@gmail.com>
  6. # URL: <http://nltk.org/>
  7. # For license information, see LICENSE.TXT
  8. from nltk.stem.porter import PorterStemmer
  9. from nltk.corpus import wordnet
  10. from itertools import chain, product
  11. def _generate_enums(hypothesis, reference, preprocess=str.lower):
  12. """
  13. Takes in string inputs for hypothesis and reference and returns
  14. enumerated word lists for each of them
  15. :param hypothesis: hypothesis string
  16. :type hypothesis: str
  17. :param reference: reference string
  18. :type reference: str
  19. :preprocess: preprocessing method (default str.lower)
  20. :type preprocess: method
  21. :return: enumerated words list
  22. :rtype: list of 2D tuples, list of 2D tuples
  23. """
  24. hypothesis_list = list(enumerate(preprocess(hypothesis).split()))
  25. reference_list = list(enumerate(preprocess(reference).split()))
  26. return hypothesis_list, reference_list
  27. def exact_match(hypothesis, reference):
  28. """
  29. matches exact words in hypothesis and reference
  30. and returns a word mapping based on the enumerated
  31. word id between hypothesis and reference
  32. :param hypothesis: hypothesis string
  33. :type hypothesis: str
  34. :param reference: reference string
  35. :type reference: str
  36. :return: enumerated matched tuples, enumerated unmatched hypothesis tuples,
  37. enumerated unmatched reference tuples
  38. :rtype: list of 2D tuples, list of 2D tuples, list of 2D tuples
  39. """
  40. hypothesis_list, reference_list = _generate_enums(hypothesis, reference)
  41. return _match_enums(hypothesis_list, reference_list)
  42. def _match_enums(enum_hypothesis_list, enum_reference_list):
  43. """
  44. matches exact words in hypothesis and reference and returns
  45. a word mapping between enum_hypothesis_list and enum_reference_list
  46. based on the enumerated word id.
  47. :param enum_hypothesis_list: enumerated hypothesis list
  48. :type enum_hypothesis_list: list of tuples
  49. :param enum_reference_list: enumerated reference list
  50. :type enum_reference_list: list of 2D tuples
  51. :return: enumerated matched tuples, enumerated unmatched hypothesis tuples,
  52. enumerated unmatched reference tuples
  53. :rtype: list of 2D tuples, list of 2D tuples, list of 2D tuples
  54. """
  55. word_match = []
  56. for i in range(len(enum_hypothesis_list))[::-1]:
  57. for j in range(len(enum_reference_list))[::-1]:
  58. if enum_hypothesis_list[i][1] == enum_reference_list[j][1]:
  59. word_match.append(
  60. (enum_hypothesis_list[i][0], enum_reference_list[j][0])
  61. )
  62. (enum_hypothesis_list.pop(i)[1], enum_reference_list.pop(j)[1])
  63. break
  64. return word_match, enum_hypothesis_list, enum_reference_list
  65. def _enum_stem_match(
  66. enum_hypothesis_list, enum_reference_list, stemmer=PorterStemmer()
  67. ):
  68. """
  69. Stems each word and matches them in hypothesis and reference
  70. and returns a word mapping between enum_hypothesis_list and
  71. enum_reference_list based on the enumerated word id. The function also
  72. returns a enumerated list of unmatched words for hypothesis and reference.
  73. :param enum_hypothesis_list:
  74. :type enum_hypothesis_list:
  75. :param enum_reference_list:
  76. :type enum_reference_list:
  77. :param stemmer: nltk.stem.api.StemmerI object (default PorterStemmer())
  78. :type stemmer: nltk.stem.api.StemmerI or any class that implements a stem method
  79. :return: enumerated matched tuples, enumerated unmatched hypothesis tuples,
  80. enumerated unmatched reference tuples
  81. :rtype: list of 2D tuples, list of 2D tuples, list of 2D tuples
  82. """
  83. stemmed_enum_list1 = [
  84. (word_pair[0], stemmer.stem(word_pair[1])) for word_pair in enum_hypothesis_list
  85. ]
  86. stemmed_enum_list2 = [
  87. (word_pair[0], stemmer.stem(word_pair[1])) for word_pair in enum_reference_list
  88. ]
  89. word_match, enum_unmat_hypo_list, enum_unmat_ref_list = _match_enums(
  90. stemmed_enum_list1, stemmed_enum_list2
  91. )
  92. enum_unmat_hypo_list = (
  93. list(zip(*enum_unmat_hypo_list)) if len(enum_unmat_hypo_list) > 0 else []
  94. )
  95. enum_unmat_ref_list = (
  96. list(zip(*enum_unmat_ref_list)) if len(enum_unmat_ref_list) > 0 else []
  97. )
  98. enum_hypothesis_list = list(
  99. filter(lambda x: x[0] not in enum_unmat_hypo_list, enum_hypothesis_list)
  100. )
  101. enum_reference_list = list(
  102. filter(lambda x: x[0] not in enum_unmat_ref_list, enum_reference_list)
  103. )
  104. return word_match, enum_hypothesis_list, enum_reference_list
  105. def stem_match(hypothesis, reference, stemmer=PorterStemmer()):
  106. """
  107. Stems each word and matches them in hypothesis and reference
  108. and returns a word mapping between hypothesis and reference
  109. :param hypothesis:
  110. :type hypothesis:
  111. :param reference:
  112. :type reference:
  113. :param stemmer: nltk.stem.api.StemmerI object (default PorterStemmer())
  114. :type stemmer: nltk.stem.api.StemmerI or any class that
  115. implements a stem method
  116. :return: enumerated matched tuples, enumerated unmatched hypothesis tuples,
  117. enumerated unmatched reference tuples
  118. :rtype: list of 2D tuples, list of 2D tuples, list of 2D tuples
  119. """
  120. enum_hypothesis_list, enum_reference_list = _generate_enums(hypothesis, reference)
  121. return _enum_stem_match(enum_hypothesis_list, enum_reference_list, stemmer=stemmer)
  122. def _enum_wordnetsyn_match(enum_hypothesis_list, enum_reference_list, wordnet=wordnet):
  123. """
  124. Matches each word in reference to a word in hypothesis
  125. if any synonym of a hypothesis word is the exact match
  126. to the reference word.
  127. :param enum_hypothesis_list: enumerated hypothesis list
  128. :param enum_reference_list: enumerated reference list
  129. :param wordnet: a wordnet corpus reader object (default nltk.corpus.wordnet)
  130. :type wordnet: WordNetCorpusReader
  131. :return: list of matched tuples, unmatched hypothesis list, unmatched reference list
  132. :rtype: list of tuples, list of tuples, list of tuples
  133. """
  134. word_match = []
  135. for i in range(len(enum_hypothesis_list))[::-1]:
  136. hypothesis_syns = set(
  137. chain(
  138. *[
  139. [
  140. lemma.name()
  141. for lemma in synset.lemmas()
  142. if lemma.name().find("_") < 0
  143. ]
  144. for synset in wordnet.synsets(enum_hypothesis_list[i][1])
  145. ]
  146. )
  147. ).union({enum_hypothesis_list[i][1]})
  148. for j in range(len(enum_reference_list))[::-1]:
  149. if enum_reference_list[j][1] in hypothesis_syns:
  150. word_match.append(
  151. (enum_hypothesis_list[i][0], enum_reference_list[j][0])
  152. )
  153. enum_hypothesis_list.pop(i), enum_reference_list.pop(j)
  154. break
  155. return word_match, enum_hypothesis_list, enum_reference_list
  156. def wordnetsyn_match(hypothesis, reference, wordnet=wordnet):
  157. """
  158. Matches each word in reference to a word in hypothesis if any synonym
  159. of a hypothesis word is the exact match to the reference word.
  160. :param hypothesis: hypothesis string
  161. :param reference: reference string
  162. :param wordnet: a wordnet corpus reader object (default nltk.corpus.wordnet)
  163. :type wordnet: WordNetCorpusReader
  164. :return: list of mapped tuples
  165. :rtype: list of tuples
  166. """
  167. enum_hypothesis_list, enum_reference_list = _generate_enums(hypothesis, reference)
  168. return _enum_wordnetsyn_match(
  169. enum_hypothesis_list, enum_reference_list, wordnet=wordnet
  170. )
  171. def _enum_allign_words(
  172. enum_hypothesis_list, enum_reference_list, stemmer=PorterStemmer(), wordnet=wordnet
  173. ):
  174. """
  175. Aligns/matches words in the hypothesis to reference by sequentially
  176. applying exact match, stemmed match and wordnet based synonym match.
  177. in case there are multiple matches the match which has the least number
  178. of crossing is chosen. Takes enumerated list as input instead of
  179. string input
  180. :param enum_hypothesis_list: enumerated hypothesis list
  181. :param enum_reference_list: enumerated reference list
  182. :param stemmer: nltk.stem.api.StemmerI object (default PorterStemmer())
  183. :type stemmer: nltk.stem.api.StemmerI or any class that implements a stem method
  184. :param wordnet: a wordnet corpus reader object (default nltk.corpus.wordnet)
  185. :type wordnet: WordNetCorpusReader
  186. :return: sorted list of matched tuples, unmatched hypothesis list,
  187. unmatched reference list
  188. :rtype: list of tuples, list of tuples, list of tuples
  189. """
  190. exact_matches, enum_hypothesis_list, enum_reference_list = _match_enums(
  191. enum_hypothesis_list, enum_reference_list
  192. )
  193. stem_matches, enum_hypothesis_list, enum_reference_list = _enum_stem_match(
  194. enum_hypothesis_list, enum_reference_list, stemmer=stemmer
  195. )
  196. wns_matches, enum_hypothesis_list, enum_reference_list = _enum_wordnetsyn_match(
  197. enum_hypothesis_list, enum_reference_list, wordnet=wordnet
  198. )
  199. return (
  200. sorted(
  201. exact_matches + stem_matches + wns_matches, key=lambda wordpair: wordpair[0]
  202. ),
  203. enum_hypothesis_list,
  204. enum_reference_list,
  205. )
  206. def allign_words(hypothesis, reference, stemmer=PorterStemmer(), wordnet=wordnet):
  207. """
  208. Aligns/matches words in the hypothesis to reference by sequentially
  209. applying exact match, stemmed match and wordnet based synonym match.
  210. In case there are multiple matches the match which has the least number
  211. of crossing is chosen.
  212. :param hypothesis: hypothesis string
  213. :param reference: reference string
  214. :param stemmer: nltk.stem.api.StemmerI object (default PorterStemmer())
  215. :type stemmer: nltk.stem.api.StemmerI or any class that implements a stem method
  216. :param wordnet: a wordnet corpus reader object (default nltk.corpus.wordnet)
  217. :type wordnet: WordNetCorpusReader
  218. :return: sorted list of matched tuples, unmatched hypothesis list, unmatched reference list
  219. :rtype: list of tuples, list of tuples, list of tuples
  220. """
  221. enum_hypothesis_list, enum_reference_list = _generate_enums(hypothesis, reference)
  222. return _enum_allign_words(
  223. enum_hypothesis_list, enum_reference_list, stemmer=stemmer, wordnet=wordnet
  224. )
  225. def _count_chunks(matches):
  226. """
  227. Counts the fewest possible number of chunks such that matched unigrams
  228. of each chunk are adjacent to each other. This is used to caluclate the
  229. fragmentation part of the metric.
  230. :param matches: list containing a mapping of matched words (output of allign_words)
  231. :return: Number of chunks a sentence is divided into post allignment
  232. :rtype: int
  233. """
  234. i = 0
  235. chunks = 1
  236. while i < len(matches) - 1:
  237. if (matches[i + 1][0] == matches[i][0] + 1) and (
  238. matches[i + 1][1] == matches[i][1] + 1
  239. ):
  240. i += 1
  241. continue
  242. i += 1
  243. chunks += 1
  244. return chunks
  245. def single_meteor_score(
  246. reference,
  247. hypothesis,
  248. preprocess=str.lower,
  249. stemmer=PorterStemmer(),
  250. wordnet=wordnet,
  251. alpha=0.9,
  252. beta=3,
  253. gamma=0.5,
  254. ):
  255. """
  256. Calculates METEOR score for single hypothesis and reference as per
  257. "Meteor: An Automatic Metric for MT Evaluation with HighLevels of
  258. Correlation with Human Judgments" by Alon Lavie and Abhaya Agarwal,
  259. in Proceedings of ACL.
  260. http://www.cs.cmu.edu/~alavie/METEOR/pdf/Lavie-Agarwal-2007-METEOR.pdf
  261. >>> hypothesis1 = 'It is a guide to action which ensures that the military always obeys the commands of the party'
  262. >>> reference1 = 'It is a guide to action that ensures that the military will forever heed Party commands'
  263. >>> round(single_meteor_score(reference1, hypothesis1),4)
  264. 0.7398
  265. If there is no words match during the alignment the method returns the
  266. score as 0. We can safely return a zero instead of raising a
  267. division by zero error as no match usually implies a bad translation.
  268. >>> round(meteor_score('this is a cat', 'non matching hypothesis'),4)
  269. 0.0
  270. :param references: reference sentences
  271. :type references: list(str)
  272. :param hypothesis: a hypothesis sentence
  273. :type hypothesis: str
  274. :param preprocess: preprocessing function (default str.lower)
  275. :type preprocess: method
  276. :param stemmer: nltk.stem.api.StemmerI object (default PorterStemmer())
  277. :type stemmer: nltk.stem.api.StemmerI or any class that implements a stem method
  278. :param wordnet: a wordnet corpus reader object (default nltk.corpus.wordnet)
  279. :type wordnet: WordNetCorpusReader
  280. :param alpha: parameter for controlling relative weights of precision and recall.
  281. :type alpha: float
  282. :param beta: parameter for controlling shape of penalty as a
  283. function of as a function of fragmentation.
  284. :type beta: float
  285. :param gamma: relative weight assigned to fragmentation penality.
  286. :type gamma: float
  287. :return: The sentence-level METEOR score.
  288. :rtype: float
  289. """
  290. enum_hypothesis, enum_reference = _generate_enums(
  291. hypothesis, reference, preprocess=preprocess
  292. )
  293. translation_length = len(enum_hypothesis)
  294. reference_length = len(enum_reference)
  295. matches, _, _ = _enum_allign_words(enum_hypothesis, enum_reference, stemmer=stemmer)
  296. matches_count = len(matches)
  297. try:
  298. precision = float(matches_count) / translation_length
  299. recall = float(matches_count) / reference_length
  300. fmean = (precision * recall) / (alpha * precision + (1 - alpha) * recall)
  301. chunk_count = float(_count_chunks(matches))
  302. frag_frac = chunk_count / matches_count
  303. except ZeroDivisionError:
  304. return 0.0
  305. penalty = gamma * frag_frac ** beta
  306. return (1 - penalty) * fmean
  307. def meteor_score(
  308. references,
  309. hypothesis,
  310. preprocess=str.lower,
  311. stemmer=PorterStemmer(),
  312. wordnet=wordnet,
  313. alpha=0.9,
  314. beta=3,
  315. gamma=0.5,
  316. ):
  317. """
  318. Calculates METEOR score for hypothesis with multiple references as
  319. described in "Meteor: An Automatic Metric for MT Evaluation with
  320. HighLevels of Correlation with Human Judgments" by Alon Lavie and
  321. Abhaya Agarwal, in Proceedings of ACL.
  322. http://www.cs.cmu.edu/~alavie/METEOR/pdf/Lavie-Agarwal-2007-METEOR.pdf
  323. In case of multiple references the best score is chosen. This method
  324. iterates over single_meteor_score and picks the best pair among all
  325. the references for a given hypothesis
  326. >>> hypothesis1 = 'It is a guide to action which ensures that the military always obeys the commands of the party'
  327. >>> hypothesis2 = 'It is to insure the troops forever hearing the activity guidebook that party direct'
  328. >>> reference1 = 'It is a guide to action that ensures that the military will forever heed Party commands'
  329. >>> reference2 = 'It is the guiding principle which guarantees the military forces always being under the command of the Party'
  330. >>> reference3 = 'It is the practical guide for the army always to heed the directions of the party'
  331. >>> round(meteor_score([reference1, reference2, reference3], hypothesis1),4)
  332. 0.7398
  333. If there is no words match during the alignment the method returns the
  334. score as 0. We can safely return a zero instead of raising a
  335. division by zero error as no match usually implies a bad translation.
  336. >>> round(meteor_score(['this is a cat'], 'non matching hypothesis'),4)
  337. 0.0
  338. :param references: reference sentences
  339. :type references: list(str)
  340. :param hypothesis: a hypothesis sentence
  341. :type hypothesis: str
  342. :param preprocess: preprocessing function (default str.lower)
  343. :type preprocess: method
  344. :param stemmer: nltk.stem.api.StemmerI object (default PorterStemmer())
  345. :type stemmer: nltk.stem.api.StemmerI or any class that implements a stem method
  346. :param wordnet: a wordnet corpus reader object (default nltk.corpus.wordnet)
  347. :type wordnet: WordNetCorpusReader
  348. :param alpha: parameter for controlling relative weights of precision and recall.
  349. :type alpha: float
  350. :param beta: parameter for controlling shape of penalty as a function
  351. of as a function of fragmentation.
  352. :type beta: float
  353. :param gamma: relative weight assigned to fragmentation penality.
  354. :type gamma: float
  355. :return: The sentence-level METEOR score.
  356. :rtype: float
  357. """
  358. return max(
  359. [
  360. single_meteor_score(
  361. reference,
  362. hypothesis,
  363. stemmer=stemmer,
  364. wordnet=wordnet,
  365. alpha=alpha,
  366. beta=beta,
  367. gamma=gamma,
  368. )
  369. for reference in references
  370. ]
  371. )