viterbi.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. # Natural Language Toolkit: Viterbi Probabilistic Parser
  2. #
  3. # Copyright (C) 2001-2020 NLTK Project
  4. # Author: Edward Loper <edloper@gmail.com>
  5. # Steven Bird <stevenbird1@gmail.com>
  6. # URL: <http://nltk.org/>
  7. # For license information, see LICENSE.TXT
  8. from functools import reduce
  9. from nltk.tree import Tree, ProbabilisticTree
  10. from nltk.parse.api import ParserI
  11. ##//////////////////////////////////////////////////////
  12. ## Viterbi PCFG Parser
  13. ##//////////////////////////////////////////////////////
  14. class ViterbiParser(ParserI):
  15. """
  16. A bottom-up ``PCFG`` parser that uses dynamic programming to find
  17. the single most likely parse for a text. The ``ViterbiParser`` parser
  18. parses texts by filling in a "most likely constituent table".
  19. This table records the most probable tree representation for any
  20. given span and node value. In particular, it has an entry for
  21. every start index, end index, and node value, recording the most
  22. likely subtree that spans from the start index to the end index,
  23. and has the given node value.
  24. The ``ViterbiParser`` parser fills in this table incrementally. It starts
  25. by filling in all entries for constituents that span one element
  26. of text (i.e., entries where the end index is one greater than the
  27. start index). After it has filled in all table entries for
  28. constituents that span one element of text, it fills in the
  29. entries for constitutants that span two elements of text. It
  30. continues filling in the entries for constituents spanning larger
  31. and larger portions of the text, until the entire table has been
  32. filled. Finally, it returns the table entry for a constituent
  33. spanning the entire text, whose node value is the grammar's start
  34. symbol.
  35. In order to find the most likely constituent with a given span and
  36. node value, the ``ViterbiParser`` parser considers all productions that
  37. could produce that node value. For each production, it finds all
  38. children that collectively cover the span and have the node values
  39. specified by the production's right hand side. If the probability
  40. of the tree formed by applying the production to the children is
  41. greater than the probability of the current entry in the table,
  42. then the table is updated with this new tree.
  43. A pseudo-code description of the algorithm used by
  44. ``ViterbiParser`` is:
  45. | Create an empty most likely constituent table, *MLC*.
  46. | For width in 1...len(text):
  47. | For start in 1...len(text)-width:
  48. | For prod in grammar.productions:
  49. | For each sequence of subtrees [t[1], t[2], ..., t[n]] in MLC,
  50. | where t[i].label()==prod.rhs[i],
  51. | and the sequence covers [start:start+width]:
  52. | old_p = MLC[start, start+width, prod.lhs]
  53. | new_p = P(t[1])P(t[1])...P(t[n])P(prod)
  54. | if new_p > old_p:
  55. | new_tree = Tree(prod.lhs, t[1], t[2], ..., t[n])
  56. | MLC[start, start+width, prod.lhs] = new_tree
  57. | Return MLC[0, len(text), start_symbol]
  58. :type _grammar: PCFG
  59. :ivar _grammar: The grammar used to parse sentences.
  60. :type _trace: int
  61. :ivar _trace: The level of tracing output that should be generated
  62. when parsing a text.
  63. """
  64. def __init__(self, grammar, trace=0):
  65. """
  66. Create a new ``ViterbiParser`` parser, that uses ``grammar`` to
  67. parse texts.
  68. :type grammar: PCFG
  69. :param grammar: The grammar used to parse texts.
  70. :type trace: int
  71. :param trace: The level of tracing that should be used when
  72. parsing a text. ``0`` will generate no tracing output;
  73. and higher numbers will produce more verbose tracing
  74. output.
  75. """
  76. self._grammar = grammar
  77. self._trace = trace
  78. def grammar(self):
  79. return self._grammar
  80. def trace(self, trace=2):
  81. """
  82. Set the level of tracing output that should be generated when
  83. parsing a text.
  84. :type trace: int
  85. :param trace: The trace level. A trace level of ``0`` will
  86. generate no tracing output; and higher trace levels will
  87. produce more verbose tracing output.
  88. :rtype: None
  89. """
  90. self._trace = trace
  91. def parse(self, tokens):
  92. # Inherit docs from ParserI
  93. tokens = list(tokens)
  94. self._grammar.check_coverage(tokens)
  95. # The most likely constituent table. This table specifies the
  96. # most likely constituent for a given span and type.
  97. # Constituents can be either Trees or tokens. For Trees,
  98. # the "type" is the Nonterminal for the tree's root node
  99. # value. For Tokens, the "type" is the token's type.
  100. # The table is stored as a dictionary, since it is sparse.
  101. constituents = {}
  102. # Initialize the constituents dictionary with the words from
  103. # the text.
  104. if self._trace:
  105. print(("Inserting tokens into the most likely" + " constituents table..."))
  106. for index in range(len(tokens)):
  107. token = tokens[index]
  108. constituents[index, index + 1, token] = token
  109. if self._trace > 1:
  110. self._trace_lexical_insertion(token, index, len(tokens))
  111. # Consider each span of length 1, 2, ..., n; and add any trees
  112. # that might cover that span to the constituents dictionary.
  113. for length in range(1, len(tokens) + 1):
  114. if self._trace:
  115. print(
  116. (
  117. "Finding the most likely constituents"
  118. + " spanning %d text elements..." % length
  119. )
  120. )
  121. for start in range(len(tokens) - length + 1):
  122. span = (start, start + length)
  123. self._add_constituents_spanning(span, constituents, tokens)
  124. # Return the tree that spans the entire text & have the right cat
  125. tree = constituents.get((0, len(tokens), self._grammar.start()))
  126. if tree is not None:
  127. yield tree
  128. def _add_constituents_spanning(self, span, constituents, tokens):
  129. """
  130. Find any constituents that might cover ``span``, and add them
  131. to the most likely constituents table.
  132. :rtype: None
  133. :type span: tuple(int, int)
  134. :param span: The section of the text for which we are
  135. trying to find possible constituents. The span is
  136. specified as a pair of integers, where the first integer
  137. is the index of the first token that should be included in
  138. the constituent; and the second integer is the index of
  139. the first token that should not be included in the
  140. constituent. I.e., the constituent should cover
  141. ``text[span[0]:span[1]]``, where ``text`` is the text
  142. that we are parsing.
  143. :type constituents: dict(tuple(int,int,Nonterminal) -> ProbabilisticToken or ProbabilisticTree)
  144. :param constituents: The most likely constituents table. This
  145. table records the most probable tree representation for
  146. any given span and node value. In particular,
  147. ``constituents(s,e,nv)`` is the most likely
  148. ``ProbabilisticTree`` that covers ``text[s:e]``
  149. and has a node value ``nv.symbol()``, where ``text``
  150. is the text that we are parsing. When
  151. ``_add_constituents_spanning`` is called, ``constituents``
  152. should contain all possible constituents that are shorter
  153. than ``span``.
  154. :type tokens: list of tokens
  155. :param tokens: The text we are parsing. This is only used for
  156. trace output.
  157. """
  158. # Since some of the grammar productions may be unary, we need to
  159. # repeatedly try all of the productions until none of them add any
  160. # new constituents.
  161. changed = True
  162. while changed:
  163. changed = False
  164. # Find all ways instantiations of the grammar productions that
  165. # cover the span.
  166. instantiations = self._find_instantiations(span, constituents)
  167. # For each production instantiation, add a new
  168. # ProbabilisticTree whose probability is the product
  169. # of the childrens' probabilities and the production's
  170. # probability.
  171. for (production, children) in instantiations:
  172. subtrees = [c for c in children if isinstance(c, Tree)]
  173. p = reduce(lambda pr, t: pr * t.prob(), subtrees, production.prob())
  174. node = production.lhs().symbol()
  175. tree = ProbabilisticTree(node, children, prob=p)
  176. # If it's new a constituent, then add it to the
  177. # constituents dictionary.
  178. c = constituents.get((span[0], span[1], production.lhs()))
  179. if self._trace > 1:
  180. if c is None or c != tree:
  181. if c is None or c.prob() < tree.prob():
  182. print(" Insert:", end=" ")
  183. else:
  184. print(" Discard:", end=" ")
  185. self._trace_production(production, p, span, len(tokens))
  186. if c is None or c.prob() < tree.prob():
  187. constituents[span[0], span[1], production.lhs()] = tree
  188. changed = True
  189. def _find_instantiations(self, span, constituents):
  190. """
  191. :return: a list of the production instantiations that cover a
  192. given span of the text. A "production instantiation" is
  193. a tuple containing a production and a list of children,
  194. where the production's right hand side matches the list of
  195. children; and the children cover ``span``. :rtype: list
  196. of ``pair`` of ``Production``, (list of
  197. (``ProbabilisticTree`` or token.
  198. :type span: tuple(int, int)
  199. :param span: The section of the text for which we are
  200. trying to find production instantiations. The span is
  201. specified as a pair of integers, where the first integer
  202. is the index of the first token that should be covered by
  203. the production instantiation; and the second integer is
  204. the index of the first token that should not be covered by
  205. the production instantiation.
  206. :type constituents: dict(tuple(int,int,Nonterminal) -> ProbabilisticToken or ProbabilisticTree)
  207. :param constituents: The most likely constituents table. This
  208. table records the most probable tree representation for
  209. any given span and node value. See the module
  210. documentation for more information.
  211. """
  212. rv = []
  213. for production in self._grammar.productions():
  214. childlists = self._match_rhs(production.rhs(), span, constituents)
  215. for childlist in childlists:
  216. rv.append((production, childlist))
  217. return rv
  218. def _match_rhs(self, rhs, span, constituents):
  219. """
  220. :return: a set of all the lists of children that cover ``span``
  221. and that match ``rhs``.
  222. :rtype: list(list(ProbabilisticTree or token)
  223. :type rhs: list(Nonterminal or any)
  224. :param rhs: The list specifying what kinds of children need to
  225. cover ``span``. Each nonterminal in ``rhs`` specifies
  226. that the corresponding child should be a tree whose node
  227. value is that nonterminal's symbol. Each terminal in ``rhs``
  228. specifies that the corresponding child should be a token
  229. whose type is that terminal.
  230. :type span: tuple(int, int)
  231. :param span: The section of the text for which we are
  232. trying to find child lists. The span is specified as a
  233. pair of integers, where the first integer is the index of
  234. the first token that should be covered by the child list;
  235. and the second integer is the index of the first token
  236. that should not be covered by the child list.
  237. :type constituents: dict(tuple(int,int,Nonterminal) -> ProbabilisticToken or ProbabilisticTree)
  238. :param constituents: The most likely constituents table. This
  239. table records the most probable tree representation for
  240. any given span and node value. See the module
  241. documentation for more information.
  242. """
  243. (start, end) = span
  244. # Base case
  245. if start >= end and rhs == ():
  246. return [[]]
  247. if start >= end or rhs == ():
  248. return []
  249. # Find everything that matches the 1st symbol of the RHS
  250. childlists = []
  251. for split in range(start, end + 1):
  252. l = constituents.get((start, split, rhs[0]))
  253. if l is not None:
  254. rights = self._match_rhs(rhs[1:], (split, end), constituents)
  255. childlists += [[l] + r for r in rights]
  256. return childlists
  257. def _trace_production(self, production, p, span, width):
  258. """
  259. Print trace output indicating that a given production has been
  260. applied at a given location.
  261. :param production: The production that has been applied
  262. :type production: Production
  263. :param p: The probability of the tree produced by the production.
  264. :type p: float
  265. :param span: The span of the production
  266. :type span: tuple
  267. :rtype: None
  268. """
  269. str = "|" + "." * span[0]
  270. str += "=" * (span[1] - span[0])
  271. str += "." * (width - span[1]) + "| "
  272. str += "%s" % production
  273. if self._trace > 2:
  274. str = "%-40s %12.10f " % (str, p)
  275. print(str)
  276. def _trace_lexical_insertion(self, token, index, width):
  277. str = " Insert: |" + "." * index + "=" + "." * (width - index - 1) + "| "
  278. str += "%s" % (token,)
  279. print(str)
  280. def __repr__(self):
  281. return "<ViterbiParser for %r>" % self._grammar
  282. ##//////////////////////////////////////////////////////
  283. ## Test Code
  284. ##//////////////////////////////////////////////////////
  285. def demo():
  286. """
  287. A demonstration of the probabilistic parsers. The user is
  288. prompted to select which demo to run, and how many parses should
  289. be found; and then each parser is run on the same demo, and a
  290. summary of the results are displayed.
  291. """
  292. import sys, time
  293. from nltk import tokenize
  294. from nltk.parse import ViterbiParser
  295. from nltk.grammar import toy_pcfg1, toy_pcfg2
  296. # Define two demos. Each demo has a sentence and a grammar.
  297. demos = [
  298. ("I saw the man with my telescope", toy_pcfg1),
  299. ("the boy saw Jack with Bob under the table with a telescope", toy_pcfg2),
  300. ]
  301. # Ask the user which demo they want to use.
  302. print()
  303. for i in range(len(demos)):
  304. print("%3s: %s" % (i + 1, demos[i][0]))
  305. print(" %r" % demos[i][1])
  306. print()
  307. print("Which demo (%d-%d)? " % (1, len(demos)), end=" ")
  308. try:
  309. snum = int(sys.stdin.readline().strip()) - 1
  310. sent, grammar = demos[snum]
  311. except:
  312. print("Bad sentence number")
  313. return
  314. # Tokenize the sentence.
  315. tokens = sent.split()
  316. parser = ViterbiParser(grammar)
  317. all_parses = {}
  318. print("\nsent: %s\nparser: %s\ngrammar: %s" % (sent, parser, grammar))
  319. parser.trace(3)
  320. t = time.time()
  321. parses = parser.parse_all(tokens)
  322. time = time.time() - t
  323. average = (
  324. reduce(lambda a, b: a + b.prob(), parses, 0) / len(parses) if parses else 0
  325. )
  326. num_parses = len(parses)
  327. for p in parses:
  328. all_parses[p.freeze()] = 1
  329. # Print some summary statistics
  330. print()
  331. print("Time (secs) # Parses Average P(parse)")
  332. print("-----------------------------------------")
  333. print("%11.4f%11d%19.14f" % (time, num_parses, average))
  334. parses = all_parses.keys()
  335. if parses:
  336. p = reduce(lambda a, b: a + b.prob(), parses, 0) / len(parses)
  337. else:
  338. p = 0
  339. print("------------------------------------------")
  340. print("%11s%11d%19.14f" % ("n/a", len(parses), p))
  341. # Ask the user if we should draw the parses.
  342. print()
  343. print("Draw parses (y/n)? ", end=" ")
  344. if sys.stdin.readline().strip().lower().startswith("y"):
  345. from nltk.draw.tree import draw_trees
  346. print(" please wait...")
  347. draw_trees(*parses)
  348. # Ask the user if we should print the parses.
  349. print()
  350. print("Print parses (y/n)? ", end=" ")
  351. if sys.stdin.readline().strip().lower().startswith("y"):
  352. for parse in parses:
  353. print(parse)
  354. if __name__ == "__main__":
  355. demo()