test_ibm1.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. # -*- coding: utf-8 -*-
  2. """
  3. Tests for IBM Model 1 training methods
  4. """
  5. import unittest
  6. from collections import defaultdict
  7. from nltk.translate import AlignedSent
  8. from nltk.translate import IBMModel
  9. from nltk.translate import IBMModel1
  10. from nltk.translate.ibm_model import AlignmentInfo
  11. class TestIBMModel1(unittest.TestCase):
  12. def test_set_uniform_translation_probabilities(self):
  13. # arrange
  14. corpus = [
  15. AlignedSent(['ham', 'eggs'], ['schinken', 'schinken', 'eier']),
  16. AlignedSent(['spam', 'spam', 'spam', 'spam'], ['spam', 'spam']),
  17. ]
  18. model1 = IBMModel1(corpus, 0)
  19. # act
  20. model1.set_uniform_probabilities(corpus)
  21. # assert
  22. # expected_prob = 1.0 / (target vocab size + 1)
  23. self.assertEqual(model1.translation_table['ham']['eier'], 1.0 / 3)
  24. self.assertEqual(model1.translation_table['eggs'][None], 1.0 / 3)
  25. def test_set_uniform_translation_probabilities_of_non_domain_values(self):
  26. # arrange
  27. corpus = [
  28. AlignedSent(['ham', 'eggs'], ['schinken', 'schinken', 'eier']),
  29. AlignedSent(['spam', 'spam', 'spam', 'spam'], ['spam', 'spam']),
  30. ]
  31. model1 = IBMModel1(corpus, 0)
  32. # act
  33. model1.set_uniform_probabilities(corpus)
  34. # assert
  35. # examine target words that are not in the training data domain
  36. self.assertEqual(model1.translation_table['parrot']['eier'], IBMModel.MIN_PROB)
  37. def test_prob_t_a_given_s(self):
  38. # arrange
  39. src_sentence = ["ich", 'esse', 'ja', 'gern', 'räucherschinken']
  40. trg_sentence = ['i', 'love', 'to', 'eat', 'smoked', 'ham']
  41. corpus = [AlignedSent(trg_sentence, src_sentence)]
  42. alignment_info = AlignmentInfo(
  43. (0, 1, 4, 0, 2, 5, 5),
  44. [None] + src_sentence,
  45. ['UNUSED'] + trg_sentence,
  46. None,
  47. )
  48. translation_table = defaultdict(lambda: defaultdict(float))
  49. translation_table['i']['ich'] = 0.98
  50. translation_table['love']['gern'] = 0.98
  51. translation_table['to'][None] = 0.98
  52. translation_table['eat']['esse'] = 0.98
  53. translation_table['smoked']['räucherschinken'] = 0.98
  54. translation_table['ham']['räucherschinken'] = 0.98
  55. model1 = IBMModel1(corpus, 0)
  56. model1.translation_table = translation_table
  57. # act
  58. probability = model1.prob_t_a_given_s(alignment_info)
  59. # assert
  60. lexical_translation = 0.98 * 0.98 * 0.98 * 0.98 * 0.98 * 0.98
  61. expected_probability = lexical_translation
  62. self.assertEqual(round(probability, 4), round(expected_probability, 4))