ibm_model.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  1. # -*- coding: utf-8 -*-
  2. # Natural Language Toolkit: IBM Model Core
  3. #
  4. # Copyright (C) 2001-2020 NLTK Project
  5. # Author: Tah Wei Hoon <hoon.tw@gmail.com>
  6. # URL: <http://nltk.org/>
  7. # For license information, see LICENSE.TXT
  8. """
  9. Common methods and classes for all IBM models. See ``IBMModel1``,
  10. ``IBMModel2``, ``IBMModel3``, ``IBMModel4``, and ``IBMModel5``
  11. for specific implementations.
  12. The IBM models are a series of generative models that learn lexical
  13. translation probabilities, p(target language word|source language word),
  14. given a sentence-aligned parallel corpus.
  15. The models increase in sophistication from model 1 to 5. Typically, the
  16. output of lower models is used to seed the higher models. All models
  17. use the Expectation-Maximization (EM) algorithm to learn various
  18. probability tables.
  19. Words in a sentence are one-indexed. The first word of a sentence has
  20. position 1, not 0. Index 0 is reserved in the source sentence for the
  21. NULL token. The concept of position does not apply to NULL, but it is
  22. indexed at 0 by convention.
  23. Each target word is aligned to exactly one source word or the NULL
  24. token.
  25. References:
  26. Philipp Koehn. 2010. Statistical Machine Translation.
  27. Cambridge University Press, New York.
  28. Peter E Brown, Stephen A. Della Pietra, Vincent J. Della Pietra, and
  29. Robert L. Mercer. 1993. The Mathematics of Statistical Machine
  30. Translation: Parameter Estimation. Computational Linguistics, 19 (2),
  31. 263-311.
  32. """
  33. from bisect import insort_left
  34. from collections import defaultdict
  35. from copy import deepcopy
  36. from math import ceil
  37. def longest_target_sentence_length(sentence_aligned_corpus):
  38. """
  39. :param sentence_aligned_corpus: Parallel corpus under consideration
  40. :type sentence_aligned_corpus: list(AlignedSent)
  41. :return: Number of words in the longest target language sentence
  42. of ``sentence_aligned_corpus``
  43. """
  44. max_m = 0
  45. for aligned_sentence in sentence_aligned_corpus:
  46. m = len(aligned_sentence.words)
  47. max_m = max(m, max_m)
  48. return max_m
  49. class IBMModel(object):
  50. """
  51. Abstract base class for all IBM models
  52. """
  53. # Avoid division by zero and precision errors by imposing a minimum
  54. # value for probabilities. Note that this approach is theoretically
  55. # incorrect, since it may create probabilities that sum to more
  56. # than 1. In practice, the contribution of probabilities with MIN_PROB
  57. # is tiny enough that the value of MIN_PROB can be treated as zero.
  58. MIN_PROB = 1.0e-12 # GIZA++ is more liberal and uses 1.0e-7
  59. def __init__(self, sentence_aligned_corpus):
  60. self.init_vocab(sentence_aligned_corpus)
  61. self.reset_probabilities()
  62. def reset_probabilities(self):
  63. self.translation_table = defaultdict(
  64. lambda: defaultdict(lambda: IBMModel.MIN_PROB)
  65. )
  66. """
  67. dict[str][str]: float. Probability(target word | source word).
  68. Values accessed as ``translation_table[target_word][source_word]``.
  69. """
  70. self.alignment_table = defaultdict(
  71. lambda: defaultdict(
  72. lambda: defaultdict(lambda: defaultdict(lambda: IBMModel.MIN_PROB))
  73. )
  74. )
  75. """
  76. dict[int][int][int][int]: float. Probability(i | j,l,m).
  77. Values accessed as ``alignment_table[i][j][l][m]``.
  78. Used in model 2 and hill climbing in models 3 and above
  79. """
  80. self.fertility_table = defaultdict(lambda: defaultdict(lambda: self.MIN_PROB))
  81. """
  82. dict[int][str]: float. Probability(fertility | source word).
  83. Values accessed as ``fertility_table[fertility][source_word]``.
  84. Used in model 3 and higher.
  85. """
  86. self.p1 = 0.5
  87. """
  88. Probability that a generated word requires another target word
  89. that is aligned to NULL.
  90. Used in model 3 and higher.
  91. """
  92. def set_uniform_probabilities(self, sentence_aligned_corpus):
  93. """
  94. Initialize probability tables to a uniform distribution
  95. Derived classes should implement this accordingly.
  96. """
  97. pass
  98. def init_vocab(self, sentence_aligned_corpus):
  99. src_vocab = set()
  100. trg_vocab = set()
  101. for aligned_sentence in sentence_aligned_corpus:
  102. trg_vocab.update(aligned_sentence.words)
  103. src_vocab.update(aligned_sentence.mots)
  104. # Add the NULL token
  105. src_vocab.add(None)
  106. self.src_vocab = src_vocab
  107. """
  108. set(str): All source language words used in training
  109. """
  110. self.trg_vocab = trg_vocab
  111. """
  112. set(str): All target language words used in training
  113. """
  114. def sample(self, sentence_pair):
  115. """
  116. Sample the most probable alignments from the entire alignment
  117. space
  118. First, determine the best alignment according to IBM Model 2.
  119. With this initial alignment, use hill climbing to determine the
  120. best alignment according to a higher IBM Model. Add this
  121. alignment and its neighbors to the sample set. Repeat this
  122. process with other initial alignments obtained by pegging an
  123. alignment point.
  124. Hill climbing may be stuck in a local maxima, hence the pegging
  125. and trying out of different alignments.
  126. :param sentence_pair: Source and target language sentence pair
  127. to generate a sample of alignments from
  128. :type sentence_pair: AlignedSent
  129. :return: A set of best alignments represented by their ``AlignmentInfo``
  130. and the best alignment of the set for convenience
  131. :rtype: set(AlignmentInfo), AlignmentInfo
  132. """
  133. sampled_alignments = set()
  134. l = len(sentence_pair.mots)
  135. m = len(sentence_pair.words)
  136. # Start from the best model 2 alignment
  137. initial_alignment = self.best_model2_alignment(sentence_pair)
  138. potential_alignment = self.hillclimb(initial_alignment)
  139. sampled_alignments.update(self.neighboring(potential_alignment))
  140. best_alignment = potential_alignment
  141. # Start from other model 2 alignments,
  142. # with the constraint that j is aligned (pegged) to i
  143. for j in range(1, m + 1):
  144. for i in range(0, l + 1):
  145. initial_alignment = self.best_model2_alignment(sentence_pair, j, i)
  146. potential_alignment = self.hillclimb(initial_alignment, j)
  147. neighbors = self.neighboring(potential_alignment, j)
  148. sampled_alignments.update(neighbors)
  149. if potential_alignment.score > best_alignment.score:
  150. best_alignment = potential_alignment
  151. return sampled_alignments, best_alignment
  152. def best_model2_alignment(self, sentence_pair, j_pegged=None, i_pegged=0):
  153. """
  154. Finds the best alignment according to IBM Model 2
  155. Used as a starting point for hill climbing in Models 3 and
  156. above, because it is easier to compute than the best alignments
  157. in higher models
  158. :param sentence_pair: Source and target language sentence pair
  159. to be word-aligned
  160. :type sentence_pair: AlignedSent
  161. :param j_pegged: If specified, the alignment point of j_pegged
  162. will be fixed to i_pegged
  163. :type j_pegged: int
  164. :param i_pegged: Alignment point to j_pegged
  165. :type i_pegged: int
  166. """
  167. src_sentence = [None] + sentence_pair.mots
  168. trg_sentence = ["UNUSED"] + sentence_pair.words # 1-indexed
  169. l = len(src_sentence) - 1 # exclude NULL
  170. m = len(trg_sentence) - 1
  171. alignment = [0] * (m + 1) # init all alignments to NULL
  172. cepts = [[] for i in range((l + 1))] # init all cepts to empty list
  173. for j in range(1, m + 1):
  174. if j == j_pegged:
  175. # use the pegged alignment instead of searching for best one
  176. best_i = i_pegged
  177. else:
  178. best_i = 0
  179. max_alignment_prob = IBMModel.MIN_PROB
  180. t = trg_sentence[j]
  181. for i in range(0, l + 1):
  182. s = src_sentence[i]
  183. alignment_prob = (
  184. self.translation_table[t][s] * self.alignment_table[i][j][l][m]
  185. )
  186. if alignment_prob >= max_alignment_prob:
  187. max_alignment_prob = alignment_prob
  188. best_i = i
  189. alignment[j] = best_i
  190. cepts[best_i].append(j)
  191. return AlignmentInfo(
  192. tuple(alignment), tuple(src_sentence), tuple(trg_sentence), cepts
  193. )
  194. def hillclimb(self, alignment_info, j_pegged=None):
  195. """
  196. Starting from the alignment in ``alignment_info``, look at
  197. neighboring alignments iteratively for the best one
  198. There is no guarantee that the best alignment in the alignment
  199. space will be found, because the algorithm might be stuck in a
  200. local maximum.
  201. :param j_pegged: If specified, the search will be constrained to
  202. alignments where ``j_pegged`` remains unchanged
  203. :type j_pegged: int
  204. :return: The best alignment found from hill climbing
  205. :rtype: AlignmentInfo
  206. """
  207. alignment = alignment_info # alias with shorter name
  208. max_probability = self.prob_t_a_given_s(alignment)
  209. while True:
  210. old_alignment = alignment
  211. for neighbor_alignment in self.neighboring(alignment, j_pegged):
  212. neighbor_probability = self.prob_t_a_given_s(neighbor_alignment)
  213. if neighbor_probability > max_probability:
  214. alignment = neighbor_alignment
  215. max_probability = neighbor_probability
  216. if alignment == old_alignment:
  217. # Until there are no better alignments
  218. break
  219. alignment.score = max_probability
  220. return alignment
  221. def neighboring(self, alignment_info, j_pegged=None):
  222. """
  223. Determine the neighbors of ``alignment_info``, obtained by
  224. moving or swapping one alignment point
  225. :param j_pegged: If specified, neighbors that have a different
  226. alignment point from j_pegged will not be considered
  227. :type j_pegged: int
  228. :return: A set neighboring alignments represented by their
  229. ``AlignmentInfo``
  230. :rtype: set(AlignmentInfo)
  231. """
  232. neighbors = set()
  233. l = len(alignment_info.src_sentence) - 1 # exclude NULL
  234. m = len(alignment_info.trg_sentence) - 1
  235. original_alignment = alignment_info.alignment
  236. original_cepts = alignment_info.cepts
  237. for j in range(1, m + 1):
  238. if j != j_pegged:
  239. # Add alignments that differ by one alignment point
  240. for i in range(0, l + 1):
  241. new_alignment = list(original_alignment)
  242. new_cepts = deepcopy(original_cepts)
  243. old_i = original_alignment[j]
  244. # update alignment
  245. new_alignment[j] = i
  246. # update cepts
  247. insort_left(new_cepts[i], j)
  248. new_cepts[old_i].remove(j)
  249. new_alignment_info = AlignmentInfo(
  250. tuple(new_alignment),
  251. alignment_info.src_sentence,
  252. alignment_info.trg_sentence,
  253. new_cepts,
  254. )
  255. neighbors.add(new_alignment_info)
  256. for j in range(1, m + 1):
  257. if j != j_pegged:
  258. # Add alignments that have two alignment points swapped
  259. for other_j in range(1, m + 1):
  260. if other_j != j_pegged and other_j != j:
  261. new_alignment = list(original_alignment)
  262. new_cepts = deepcopy(original_cepts)
  263. other_i = original_alignment[other_j]
  264. i = original_alignment[j]
  265. # update alignments
  266. new_alignment[j] = other_i
  267. new_alignment[other_j] = i
  268. # update cepts
  269. new_cepts[other_i].remove(other_j)
  270. insort_left(new_cepts[other_i], j)
  271. new_cepts[i].remove(j)
  272. insort_left(new_cepts[i], other_j)
  273. new_alignment_info = AlignmentInfo(
  274. tuple(new_alignment),
  275. alignment_info.src_sentence,
  276. alignment_info.trg_sentence,
  277. new_cepts,
  278. )
  279. neighbors.add(new_alignment_info)
  280. return neighbors
  281. def maximize_lexical_translation_probabilities(self, counts):
  282. for t, src_words in counts.t_given_s.items():
  283. for s in src_words:
  284. estimate = counts.t_given_s[t][s] / counts.any_t_given_s[s]
  285. self.translation_table[t][s] = max(estimate, IBMModel.MIN_PROB)
  286. def maximize_fertility_probabilities(self, counts):
  287. for phi, src_words in counts.fertility.items():
  288. for s in src_words:
  289. estimate = counts.fertility[phi][s] / counts.fertility_for_any_phi[s]
  290. self.fertility_table[phi][s] = max(estimate, IBMModel.MIN_PROB)
  291. def maximize_null_generation_probabilities(self, counts):
  292. p1_estimate = counts.p1 / (counts.p1 + counts.p0)
  293. p1_estimate = max(p1_estimate, IBMModel.MIN_PROB)
  294. # Clip p1 if it is too large, because p0 = 1 - p1 should not be
  295. # smaller than MIN_PROB
  296. self.p1 = min(p1_estimate, 1 - IBMModel.MIN_PROB)
  297. def prob_of_alignments(self, alignments):
  298. probability = 0
  299. for alignment_info in alignments:
  300. probability += self.prob_t_a_given_s(alignment_info)
  301. return probability
  302. def prob_t_a_given_s(self, alignment_info):
  303. """
  304. Probability of target sentence and an alignment given the
  305. source sentence
  306. All required information is assumed to be in ``alignment_info``
  307. and self.
  308. Derived classes should override this method
  309. """
  310. return 0.0
  311. class AlignmentInfo(object):
  312. """
  313. Helper data object for training IBM Models 3 and up
  314. Read-only. For a source sentence and its counterpart in the target
  315. language, this class holds information about the sentence pair's
  316. alignment, cepts, and fertility.
  317. Warning: Alignments are one-indexed here, in contrast to
  318. nltk.translate.Alignment and AlignedSent, which are zero-indexed
  319. This class is not meant to be used outside of IBM models.
  320. """
  321. def __init__(self, alignment, src_sentence, trg_sentence, cepts):
  322. if not isinstance(alignment, tuple):
  323. raise TypeError(
  324. "The alignment must be a tuple because it is used "
  325. "to uniquely identify AlignmentInfo objects."
  326. )
  327. self.alignment = alignment
  328. """
  329. tuple(int): Alignment function. ``alignment[j]`` is the position
  330. in the source sentence that is aligned to the position j in the
  331. target sentence.
  332. """
  333. self.src_sentence = src_sentence
  334. """
  335. tuple(str): Source sentence referred to by this object.
  336. Should include NULL token (None) in index 0.
  337. """
  338. self.trg_sentence = trg_sentence
  339. """
  340. tuple(str): Target sentence referred to by this object.
  341. Should have a dummy element in index 0 so that the first word
  342. starts from index 1.
  343. """
  344. self.cepts = cepts
  345. """
  346. list(list(int)): The positions of the target words, in
  347. ascending order, aligned to a source word position. For example,
  348. cepts[4] = (2, 3, 7) means that words in positions 2, 3 and 7
  349. of the target sentence are aligned to the word in position 4 of
  350. the source sentence
  351. """
  352. self.score = None
  353. """
  354. float: Optional. Probability of alignment, as defined by the
  355. IBM model that assesses this alignment
  356. """
  357. def fertility_of_i(self, i):
  358. """
  359. Fertility of word in position ``i`` of the source sentence
  360. """
  361. return len(self.cepts[i])
  362. def is_head_word(self, j):
  363. """
  364. :return: Whether the word in position ``j`` of the target
  365. sentence is a head word
  366. """
  367. i = self.alignment[j]
  368. return self.cepts[i][0] == j
  369. def center_of_cept(self, i):
  370. """
  371. :return: The ceiling of the average positions of the words in
  372. the tablet of cept ``i``, or 0 if ``i`` is None
  373. """
  374. if i is None:
  375. return 0
  376. average_position = sum(self.cepts[i]) / len(self.cepts[i])
  377. return int(ceil(average_position))
  378. def previous_cept(self, j):
  379. """
  380. :return: The previous cept of ``j``, or None if ``j`` belongs to
  381. the first cept
  382. """
  383. i = self.alignment[j]
  384. if i == 0:
  385. raise ValueError(
  386. "Words aligned to NULL cannot have a previous "
  387. "cept because NULL has no position"
  388. )
  389. previous_cept = i - 1
  390. while previous_cept > 0 and self.fertility_of_i(previous_cept) == 0:
  391. previous_cept -= 1
  392. if previous_cept <= 0:
  393. previous_cept = None
  394. return previous_cept
  395. def previous_in_tablet(self, j):
  396. """
  397. :return: The position of the previous word that is in the same
  398. tablet as ``j``, or None if ``j`` is the first word of the
  399. tablet
  400. """
  401. i = self.alignment[j]
  402. tablet_position = self.cepts[i].index(j)
  403. if tablet_position == 0:
  404. return None
  405. return self.cepts[i][tablet_position - 1]
  406. def zero_indexed_alignment(self):
  407. """
  408. :return: Zero-indexed alignment, suitable for use in external
  409. ``nltk.translate`` modules like ``nltk.translate.Alignment``
  410. :rtype: list(tuple)
  411. """
  412. zero_indexed_alignment = []
  413. for j in range(1, len(self.trg_sentence)):
  414. i = self.alignment[j] - 1
  415. if i < 0:
  416. i = None # alignment to NULL token
  417. zero_indexed_alignment.append((j - 1, i))
  418. return zero_indexed_alignment
  419. def __eq__(self, other):
  420. return self.alignment == other.alignment
  421. def __ne__(self, other):
  422. return not self == other
  423. def __hash__(self):
  424. return hash(self.alignment)
  425. class Counts(object):
  426. """
  427. Data object to store counts of various parameters during training
  428. """
  429. def __init__(self):
  430. self.t_given_s = defaultdict(lambda: defaultdict(lambda: 0.0))
  431. self.any_t_given_s = defaultdict(lambda: 0.0)
  432. self.p0 = 0.0
  433. self.p1 = 0.0
  434. self.fertility = defaultdict(lambda: defaultdict(lambda: 0.0))
  435. self.fertility_for_any_phi = defaultdict(lambda: 0.0)
  436. def update_lexical_translation(self, count, alignment_info, j):
  437. i = alignment_info.alignment[j]
  438. t = alignment_info.trg_sentence[j]
  439. s = alignment_info.src_sentence[i]
  440. self.t_given_s[t][s] += count
  441. self.any_t_given_s[s] += count
  442. def update_null_generation(self, count, alignment_info):
  443. m = len(alignment_info.trg_sentence) - 1
  444. fertility_of_null = alignment_info.fertility_of_i(0)
  445. self.p1 += fertility_of_null * count
  446. self.p0 += (m - 2 * fertility_of_null) * count
  447. def update_fertility(self, count, alignment_info):
  448. for i in range(0, len(alignment_info.src_sentence)):
  449. s = alignment_info.src_sentence[i]
  450. phi = alignment_info.fertility_of_i(i)
  451. self.fertility[phi][s] += count
  452. self.fertility_for_any_phi[s] += count