nonprojectivedependencyparser.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773
  1. # Natural Language Toolkit: Dependency Grammars
  2. #
  3. # Copyright (C) 2001-2020 NLTK Project
  4. # Author: Jason Narad <jason.narad@gmail.com>
  5. #
  6. # URL: <http://nltk.org/>
  7. # For license information, see LICENSE.TXT
  8. #
  9. import math
  10. import logging
  11. from nltk.parse.dependencygraph import DependencyGraph
  12. logger = logging.getLogger(__name__)
  13. #################################################################
  14. # DependencyScorerI - Interface for Graph-Edge Weight Calculation
  15. #################################################################
  16. class DependencyScorerI(object):
  17. """
  18. A scorer for calculated the weights on the edges of a weighted
  19. dependency graph. This is used by a
  20. ``ProbabilisticNonprojectiveParser`` to initialize the edge
  21. weights of a ``DependencyGraph``. While typically this would be done
  22. by training a binary classifier, any class that can return a
  23. multidimensional list representation of the edge weights can
  24. implement this interface. As such, it has no necessary
  25. fields.
  26. """
  27. def __init__(self):
  28. if self.__class__ == DependencyScorerI:
  29. raise TypeError("DependencyScorerI is an abstract interface")
  30. def train(self, graphs):
  31. """
  32. :type graphs: list(DependencyGraph)
  33. :param graphs: A list of dependency graphs to train the scorer.
  34. Typically the edges present in the graphs can be used as
  35. positive training examples, and the edges not present as negative
  36. examples.
  37. """
  38. raise NotImplementedError()
  39. def score(self, graph):
  40. """
  41. :type graph: DependencyGraph
  42. :param graph: A dependency graph whose set of edges need to be
  43. scored.
  44. :rtype: A three-dimensional list of numbers.
  45. :return: The score is returned in a multidimensional(3) list, such
  46. that the outer-dimension refers to the head, and the
  47. inner-dimension refers to the dependencies. For instance,
  48. scores[0][1] would reference the list of scores corresponding to
  49. arcs from node 0 to node 1. The node's 'address' field can be used
  50. to determine its number identification.
  51. For further illustration, a score list corresponding to Fig.2 of
  52. Keith Hall's 'K-best Spanning Tree Parsing' paper:
  53. scores = [[[], [5], [1], [1]],
  54. [[], [], [11], [4]],
  55. [[], [10], [], [5]],
  56. [[], [8], [8], []]]
  57. When used in conjunction with a MaxEntClassifier, each score would
  58. correspond to the confidence of a particular edge being classified
  59. with the positive training examples.
  60. """
  61. raise NotImplementedError()
  62. #################################################################
  63. # NaiveBayesDependencyScorer
  64. #################################################################
  65. class NaiveBayesDependencyScorer(DependencyScorerI):
  66. """
  67. A dependency scorer built around a MaxEnt classifier. In this
  68. particular class that classifier is a ``NaiveBayesClassifier``.
  69. It uses head-word, head-tag, child-word, and child-tag features
  70. for classification.
  71. >>> from nltk.parse.dependencygraph import DependencyGraph, conll_data2
  72. >>> graphs = [DependencyGraph(entry) for entry in conll_data2.split('\\n\\n') if entry]
  73. >>> npp = ProbabilisticNonprojectiveParser()
  74. >>> npp.train(graphs, NaiveBayesDependencyScorer())
  75. >>> parses = npp.parse(['Cathy', 'zag', 'hen', 'zwaaien', '.'], ['N', 'V', 'Pron', 'Adj', 'N', 'Punc'])
  76. >>> len(list(parses))
  77. 1
  78. """
  79. def __init__(self):
  80. pass # Do nothing without throwing error
  81. def train(self, graphs):
  82. """
  83. Trains a ``NaiveBayesClassifier`` using the edges present in
  84. graphs list as positive examples, the edges not present as
  85. negative examples. Uses a feature vector of head-word,
  86. head-tag, child-word, and child-tag.
  87. :type graphs: list(DependencyGraph)
  88. :param graphs: A list of dependency graphs to train the scorer.
  89. """
  90. from nltk.classify import NaiveBayesClassifier
  91. # Create training labeled training examples
  92. labeled_examples = []
  93. for graph in graphs:
  94. for head_node in graph.nodes.values():
  95. for child_index, child_node in graph.nodes.items():
  96. if child_index in head_node["deps"]:
  97. label = "T"
  98. else:
  99. label = "F"
  100. labeled_examples.append(
  101. (
  102. dict(
  103. a=head_node["word"],
  104. b=head_node["tag"],
  105. c=child_node["word"],
  106. d=child_node["tag"],
  107. ),
  108. label,
  109. )
  110. )
  111. self.classifier = NaiveBayesClassifier.train(labeled_examples)
  112. def score(self, graph):
  113. """
  114. Converts the graph into a feature-based representation of
  115. each edge, and then assigns a score to each based on the
  116. confidence of the classifier in assigning it to the
  117. positive label. Scores are returned in a multidimensional list.
  118. :type graph: DependencyGraph
  119. :param graph: A dependency graph to score.
  120. :rtype: 3 dimensional list
  121. :return: Edge scores for the graph parameter.
  122. """
  123. # Convert graph to feature representation
  124. edges = []
  125. for head_node in graph.nodes.values():
  126. for child_node in graph.nodes.values():
  127. edges.append(
  128. (
  129. dict(
  130. a=head_node["word"],
  131. b=head_node["tag"],
  132. c=child_node["word"],
  133. d=child_node["tag"],
  134. )
  135. )
  136. )
  137. # Score edges
  138. edge_scores = []
  139. row = []
  140. count = 0
  141. for pdist in self.classifier.prob_classify_many(edges):
  142. logger.debug("%.4f %.4f", pdist.prob("T"), pdist.prob("F"))
  143. # smoothing in case the probability = 0
  144. row.append([math.log(pdist.prob("T") + 0.00000000001)])
  145. count += 1
  146. if count == len(graph.nodes):
  147. edge_scores.append(row)
  148. row = []
  149. count = 0
  150. return edge_scores
  151. #################################################################
  152. # A Scorer for Demo Purposes
  153. #################################################################
  154. # A short class necessary to show parsing example from paper
  155. class DemoScorer(DependencyScorerI):
  156. def train(self, graphs):
  157. print("Training...")
  158. def score(self, graph):
  159. # scores for Keith Hall 'K-best Spanning Tree Parsing' paper
  160. return [
  161. [[], [5], [1], [1]],
  162. [[], [], [11], [4]],
  163. [[], [10], [], [5]],
  164. [[], [8], [8], []],
  165. ]
  166. #################################################################
  167. # Non-Projective Probabilistic Parsing
  168. #################################################################
  169. class ProbabilisticNonprojectiveParser(object):
  170. """A probabilistic non-projective dependency parser.
  171. Nonprojective dependencies allows for "crossing branches" in the parse tree
  172. which is necessary for representing particular linguistic phenomena, or even
  173. typical parses in some languages. This parser follows the MST parsing
  174. algorithm, outlined in McDonald(2005), which likens the search for the best
  175. non-projective parse to finding the maximum spanning tree in a weighted
  176. directed graph.
  177. >>> class Scorer(DependencyScorerI):
  178. ... def train(self, graphs):
  179. ... pass
  180. ...
  181. ... def score(self, graph):
  182. ... return [
  183. ... [[], [5], [1], [1]],
  184. ... [[], [], [11], [4]],
  185. ... [[], [10], [], [5]],
  186. ... [[], [8], [8], []],
  187. ... ]
  188. >>> npp = ProbabilisticNonprojectiveParser()
  189. >>> npp.train([], Scorer())
  190. >>> parses = npp.parse(['v1', 'v2', 'v3'], [None, None, None])
  191. >>> len(list(parses))
  192. 1
  193. Rule based example
  194. ------------------
  195. >>> from nltk.grammar import DependencyGrammar
  196. >>> grammar = DependencyGrammar.fromstring('''
  197. ... 'taught' -> 'play' | 'man'
  198. ... 'man' -> 'the' | 'in'
  199. ... 'in' -> 'corner'
  200. ... 'corner' -> 'the'
  201. ... 'play' -> 'golf' | 'dachshund' | 'to'
  202. ... 'dachshund' -> 'his'
  203. ... ''')
  204. >>> ndp = NonprojectiveDependencyParser(grammar)
  205. >>> parses = ndp.parse(['the', 'man', 'in', 'the', 'corner', 'taught', 'his', 'dachshund', 'to', 'play', 'golf'])
  206. >>> len(list(parses))
  207. 4
  208. """
  209. def __init__(self):
  210. """
  211. Creates a new non-projective parser.
  212. """
  213. logging.debug("initializing prob. nonprojective...")
  214. def train(self, graphs, dependency_scorer):
  215. """
  216. Trains a ``DependencyScorerI`` from a set of ``DependencyGraph`` objects,
  217. and establishes this as the parser's scorer. This is used to
  218. initialize the scores on a ``DependencyGraph`` during the parsing
  219. procedure.
  220. :type graphs: list(DependencyGraph)
  221. :param graphs: A list of dependency graphs to train the scorer.
  222. :type dependency_scorer: DependencyScorerI
  223. :param dependency_scorer: A scorer which implements the
  224. ``DependencyScorerI`` interface.
  225. """
  226. self._scorer = dependency_scorer
  227. self._scorer.train(graphs)
  228. def initialize_edge_scores(self, graph):
  229. """
  230. Assigns a score to every edge in the ``DependencyGraph`` graph.
  231. These scores are generated via the parser's scorer which
  232. was assigned during the training process.
  233. :type graph: DependencyGraph
  234. :param graph: A dependency graph to assign scores to.
  235. """
  236. self.scores = self._scorer.score(graph)
  237. def collapse_nodes(self, new_node, cycle_path, g_graph, b_graph, c_graph):
  238. """
  239. Takes a list of nodes that have been identified to belong to a cycle,
  240. and collapses them into on larger node. The arcs of all nodes in
  241. the graph must be updated to account for this.
  242. :type new_node: Node.
  243. :param new_node: A Node (Dictionary) to collapse the cycle nodes into.
  244. :type cycle_path: A list of integers.
  245. :param cycle_path: A list of node addresses, each of which is in the cycle.
  246. :type g_graph, b_graph, c_graph: DependencyGraph
  247. :param g_graph, b_graph, c_graph: Graphs which need to be updated.
  248. """
  249. logger.debug("Collapsing nodes...")
  250. # Collapse all cycle nodes into v_n+1 in G_Graph
  251. for cycle_node_index in cycle_path:
  252. g_graph.remove_by_address(cycle_node_index)
  253. g_graph.add_node(new_node)
  254. g_graph.redirect_arcs(cycle_path, new_node["address"])
  255. def update_edge_scores(self, new_node, cycle_path):
  256. """
  257. Updates the edge scores to reflect a collapse operation into
  258. new_node.
  259. :type new_node: A Node.
  260. :param new_node: The node which cycle nodes are collapsed into.
  261. :type cycle_path: A list of integers.
  262. :param cycle_path: A list of node addresses that belong to the cycle.
  263. """
  264. logger.debug("cycle %s", cycle_path)
  265. cycle_path = self.compute_original_indexes(cycle_path)
  266. logger.debug("old cycle %s", cycle_path)
  267. logger.debug("Prior to update: %s", self.scores)
  268. for i, row in enumerate(self.scores):
  269. for j, column in enumerate(self.scores[i]):
  270. logger.debug(self.scores[i][j])
  271. if j in cycle_path and i not in cycle_path and self.scores[i][j]:
  272. subtract_val = self.compute_max_subtract_score(j, cycle_path)
  273. logger.debug("%s - %s", self.scores[i][j], subtract_val)
  274. new_vals = []
  275. for cur_val in self.scores[i][j]:
  276. new_vals.append(cur_val - subtract_val)
  277. self.scores[i][j] = new_vals
  278. for i, row in enumerate(self.scores):
  279. for j, cell in enumerate(self.scores[i]):
  280. if i in cycle_path and j in cycle_path:
  281. self.scores[i][j] = []
  282. logger.debug("After update: %s", self.scores)
  283. def compute_original_indexes(self, new_indexes):
  284. """
  285. As nodes are collapsed into others, they are replaced
  286. by the new node in the graph, but it's still necessary
  287. to keep track of what these original nodes were. This
  288. takes a list of node addresses and replaces any collapsed
  289. node addresses with their original addresses.
  290. :type new_indexes: A list of integers.
  291. :param new_indexes: A list of node addresses to check for
  292. subsumed nodes.
  293. """
  294. swapped = True
  295. while swapped:
  296. originals = []
  297. swapped = False
  298. for new_index in new_indexes:
  299. if new_index in self.inner_nodes:
  300. for old_val in self.inner_nodes[new_index]:
  301. if old_val not in originals:
  302. originals.append(old_val)
  303. swapped = True
  304. else:
  305. originals.append(new_index)
  306. new_indexes = originals
  307. return new_indexes
  308. def compute_max_subtract_score(self, column_index, cycle_indexes):
  309. """
  310. When updating scores the score of the highest-weighted incoming
  311. arc is subtracted upon collapse. This returns the correct
  312. amount to subtract from that edge.
  313. :type column_index: integer.
  314. :param column_index: A index representing the column of incoming arcs
  315. to a particular node being updated
  316. :type cycle_indexes: A list of integers.
  317. :param cycle_indexes: Only arcs from cycle nodes are considered. This
  318. is a list of such nodes addresses.
  319. """
  320. max_score = -100000
  321. for row_index in cycle_indexes:
  322. for subtract_val in self.scores[row_index][column_index]:
  323. if subtract_val > max_score:
  324. max_score = subtract_val
  325. return max_score
  326. def best_incoming_arc(self, node_index):
  327. """
  328. Returns the source of the best incoming arc to the
  329. node with address: node_index
  330. :type node_index: integer.
  331. :param node_index: The address of the 'destination' node,
  332. the node that is arced to.
  333. """
  334. originals = self.compute_original_indexes([node_index])
  335. logger.debug("originals: %s", originals)
  336. max_arc = None
  337. max_score = None
  338. for row_index in range(len(self.scores)):
  339. for col_index in range(len(self.scores[row_index])):
  340. if col_index in originals and (
  341. max_score is None or self.scores[row_index][col_index] > max_score
  342. ):
  343. max_score = self.scores[row_index][col_index]
  344. max_arc = row_index
  345. logger.debug("%s, %s", row_index, col_index)
  346. logger.debug(max_score)
  347. for key in self.inner_nodes:
  348. replaced_nodes = self.inner_nodes[key]
  349. if max_arc in replaced_nodes:
  350. return key
  351. return max_arc
  352. def original_best_arc(self, node_index):
  353. originals = self.compute_original_indexes([node_index])
  354. max_arc = None
  355. max_score = None
  356. max_orig = None
  357. for row_index in range(len(self.scores)):
  358. for col_index in range(len(self.scores[row_index])):
  359. if col_index in originals and (
  360. max_score is None or self.scores[row_index][col_index] > max_score
  361. ):
  362. max_score = self.scores[row_index][col_index]
  363. max_arc = row_index
  364. max_orig = col_index
  365. return [max_arc, max_orig]
  366. def parse(self, tokens, tags):
  367. """
  368. Parses a list of tokens in accordance to the MST parsing algorithm
  369. for non-projective dependency parses. Assumes that the tokens to
  370. be parsed have already been tagged and those tags are provided. Various
  371. scoring methods can be used by implementing the ``DependencyScorerI``
  372. interface and passing it to the training algorithm.
  373. :type tokens: list(str)
  374. :param tokens: A list of words or punctuation to be parsed.
  375. :type tags: list(str)
  376. :param tags: A list of tags corresponding by index to the words in the tokens list.
  377. :return: An iterator of non-projective parses.
  378. :rtype: iter(DependencyGraph)
  379. """
  380. self.inner_nodes = {}
  381. # Initialize g_graph
  382. g_graph = DependencyGraph()
  383. for index, token in enumerate(tokens):
  384. g_graph.nodes[index + 1].update(
  385. {"word": token, "tag": tags[index], "rel": "NTOP", "address": index + 1}
  386. )
  387. # Fully connect non-root nodes in g_graph
  388. g_graph.connect_graph()
  389. original_graph = DependencyGraph()
  390. for index, token in enumerate(tokens):
  391. original_graph.nodes[index + 1].update(
  392. {"word": token, "tag": tags[index], "rel": "NTOP", "address": index + 1}
  393. )
  394. b_graph = DependencyGraph()
  395. c_graph = DependencyGraph()
  396. for index, token in enumerate(tokens):
  397. c_graph.nodes[index + 1].update(
  398. {"word": token, "tag": tags[index], "rel": "NTOP", "address": index + 1}
  399. )
  400. # Assign initial scores to g_graph edges
  401. self.initialize_edge_scores(g_graph)
  402. logger.debug(self.scores)
  403. # Initialize a list of unvisited vertices (by node address)
  404. unvisited_vertices = [vertex["address"] for vertex in c_graph.nodes.values()]
  405. # Iterate over unvisited vertices
  406. nr_vertices = len(tokens)
  407. betas = {}
  408. while unvisited_vertices:
  409. # Mark current node as visited
  410. current_vertex = unvisited_vertices.pop(0)
  411. logger.debug("current_vertex: %s", current_vertex)
  412. # Get corresponding node n_i to vertex v_i
  413. current_node = g_graph.get_by_address(current_vertex)
  414. logger.debug("current_node: %s", current_node)
  415. # Get best in-edge node b for current node
  416. best_in_edge = self.best_incoming_arc(current_vertex)
  417. betas[current_vertex] = self.original_best_arc(current_vertex)
  418. logger.debug("best in arc: %s --> %s", best_in_edge, current_vertex)
  419. # b_graph = Union(b_graph, b)
  420. for new_vertex in [current_vertex, best_in_edge]:
  421. b_graph.nodes[new_vertex].update(
  422. {"word": "TEMP", "rel": "NTOP", "address": new_vertex}
  423. )
  424. b_graph.add_arc(best_in_edge, current_vertex)
  425. # Beta(current node) = b - stored for parse recovery
  426. # If b_graph contains a cycle, collapse it
  427. cycle_path = b_graph.contains_cycle()
  428. if cycle_path:
  429. # Create a new node v_n+1 with address = len(nodes) + 1
  430. new_node = {"word": "NONE", "rel": "NTOP", "address": nr_vertices + 1}
  431. # c_graph = Union(c_graph, v_n+1)
  432. c_graph.add_node(new_node)
  433. # Collapse all nodes in cycle C into v_n+1
  434. self.update_edge_scores(new_node, cycle_path)
  435. self.collapse_nodes(new_node, cycle_path, g_graph, b_graph, c_graph)
  436. for cycle_index in cycle_path:
  437. c_graph.add_arc(new_node["address"], cycle_index)
  438. # self.replaced_by[cycle_index] = new_node['address']
  439. self.inner_nodes[new_node["address"]] = cycle_path
  440. # Add v_n+1 to list of unvisited vertices
  441. unvisited_vertices.insert(0, nr_vertices + 1)
  442. # increment # of nodes counter
  443. nr_vertices += 1
  444. # Remove cycle nodes from b_graph; B = B - cycle c
  445. for cycle_node_address in cycle_path:
  446. b_graph.remove_by_address(cycle_node_address)
  447. logger.debug("g_graph: %s", g_graph)
  448. logger.debug("b_graph: %s", b_graph)
  449. logger.debug("c_graph: %s", c_graph)
  450. logger.debug("Betas: %s", betas)
  451. logger.debug("replaced nodes %s", self.inner_nodes)
  452. # Recover parse tree
  453. logger.debug("Final scores: %s", self.scores)
  454. logger.debug("Recovering parse...")
  455. for i in range(len(tokens) + 1, nr_vertices + 1):
  456. betas[betas[i][1]] = betas[i]
  457. logger.debug("Betas: %s", betas)
  458. for node in original_graph.nodes.values():
  459. # TODO: It's dangerous to assume that deps it a dictionary
  460. # because it's a default dictionary. Ideally, here we should not
  461. # be concerned how dependencies are stored inside of a dependency
  462. # graph.
  463. node["deps"] = {}
  464. for i in range(1, len(tokens) + 1):
  465. original_graph.add_arc(betas[i][0], betas[i][1])
  466. logger.debug("Done.")
  467. yield original_graph
  468. #################################################################
  469. # Rule-based Non-Projective Parser
  470. #################################################################
  471. class NonprojectiveDependencyParser(object):
  472. """
  473. A non-projective, rule-based, dependency parser. This parser
  474. will return the set of all possible non-projective parses based on
  475. the word-to-word relations defined in the parser's dependency
  476. grammar, and will allow the branches of the parse tree to cross
  477. in order to capture a variety of linguistic phenomena that a
  478. projective parser will not.
  479. """
  480. def __init__(self, dependency_grammar):
  481. """
  482. Creates a new ``NonprojectiveDependencyParser``.
  483. :param dependency_grammar: a grammar of word-to-word relations.
  484. :type dependency_grammar: DependencyGrammar
  485. """
  486. self._grammar = dependency_grammar
  487. def parse(self, tokens):
  488. """
  489. Parses the input tokens with respect to the parser's grammar. Parsing
  490. is accomplished by representing the search-space of possible parses as
  491. a fully-connected directed graph. Arcs that would lead to ungrammatical
  492. parses are removed and a lattice is constructed of length n, where n is
  493. the number of input tokens, to represent all possible grammatical
  494. traversals. All possible paths through the lattice are then enumerated
  495. to produce the set of non-projective parses.
  496. param tokens: A list of tokens to parse.
  497. type tokens: list(str)
  498. return: An iterator of non-projective parses.
  499. rtype: iter(DependencyGraph)
  500. """
  501. # Create graph representation of tokens
  502. self._graph = DependencyGraph()
  503. for index, token in enumerate(tokens):
  504. self._graph.nodes[index] = {
  505. "word": token,
  506. "deps": [],
  507. "rel": "NTOP",
  508. "address": index,
  509. }
  510. for head_node in self._graph.nodes.values():
  511. deps = []
  512. for dep_node in self._graph.nodes.values():
  513. if (
  514. self._grammar.contains(head_node["word"], dep_node["word"])
  515. and head_node["word"] != dep_node["word"]
  516. ):
  517. deps.append(dep_node["address"])
  518. head_node["deps"] = deps
  519. # Create lattice of possible heads
  520. roots = []
  521. possible_heads = []
  522. for i, word in enumerate(tokens):
  523. heads = []
  524. for j, head in enumerate(tokens):
  525. if (i != j) and self._grammar.contains(head, word):
  526. heads.append(j)
  527. if len(heads) == 0:
  528. roots.append(i)
  529. possible_heads.append(heads)
  530. # Set roots to attempt
  531. if len(roots) < 2:
  532. if len(roots) == 0:
  533. for i in range(len(tokens)):
  534. roots.append(i)
  535. # Traverse lattice
  536. analyses = []
  537. for root in roots:
  538. stack = []
  539. analysis = [[] for i in range(len(possible_heads))]
  540. i = 0
  541. forward = True
  542. while i >= 0:
  543. if forward:
  544. if len(possible_heads[i]) == 1:
  545. analysis[i] = possible_heads[i][0]
  546. elif len(possible_heads[i]) == 0:
  547. analysis[i] = -1
  548. else:
  549. head = possible_heads[i].pop()
  550. analysis[i] = head
  551. stack.append([i, head])
  552. if not forward:
  553. index_on_stack = False
  554. for stack_item in stack:
  555. if stack_item[0] == i:
  556. index_on_stack = True
  557. orig_length = len(possible_heads[i])
  558. if index_on_stack and orig_length == 0:
  559. for j in range(len(stack) - 1, -1, -1):
  560. stack_item = stack[j]
  561. if stack_item[0] == i:
  562. possible_heads[i].append(stack.pop(j)[1])
  563. elif index_on_stack and orig_length > 0:
  564. head = possible_heads[i].pop()
  565. analysis[i] = head
  566. stack.append([i, head])
  567. forward = True
  568. if i + 1 == len(possible_heads):
  569. analyses.append(analysis[:])
  570. forward = False
  571. if forward:
  572. i += 1
  573. else:
  574. i -= 1
  575. # Filter parses
  576. # ensure 1 root, every thing has 1 head
  577. for analysis in analyses:
  578. if analysis.count(-1) > 1:
  579. # there are several root elements!
  580. continue
  581. graph = DependencyGraph()
  582. graph.root = graph.nodes[analysis.index(-1) + 1]
  583. for address, (token, head_index) in enumerate(
  584. zip(tokens, analysis), start=1
  585. ):
  586. head_address = head_index + 1
  587. node = graph.nodes[address]
  588. node.update({"word": token, "address": address})
  589. if head_address == 0:
  590. rel = "ROOT"
  591. else:
  592. rel = ""
  593. graph.nodes[head_index + 1]["deps"][rel].append(address)
  594. # TODO: check for cycles
  595. yield graph
  596. #################################################################
  597. # Demos
  598. #################################################################
  599. def demo():
  600. # hall_demo()
  601. nonprojective_conll_parse_demo()
  602. rule_based_demo()
  603. def hall_demo():
  604. npp = ProbabilisticNonprojectiveParser()
  605. npp.train([], DemoScorer())
  606. for parse_graph in npp.parse(["v1", "v2", "v3"], [None, None, None]):
  607. print(parse_graph)
  608. def nonprojective_conll_parse_demo():
  609. from nltk.parse.dependencygraph import conll_data2
  610. graphs = [DependencyGraph(entry) for entry in conll_data2.split("\n\n") if entry]
  611. npp = ProbabilisticNonprojectiveParser()
  612. npp.train(graphs, NaiveBayesDependencyScorer())
  613. for parse_graph in npp.parse(
  614. ["Cathy", "zag", "hen", "zwaaien", "."], ["N", "V", "Pron", "Adj", "N", "Punc"]
  615. ):
  616. print(parse_graph)
  617. def rule_based_demo():
  618. from nltk.grammar import DependencyGrammar
  619. grammar = DependencyGrammar.fromstring(
  620. """
  621. 'taught' -> 'play' | 'man'
  622. 'man' -> 'the' | 'in'
  623. 'in' -> 'corner'
  624. 'corner' -> 'the'
  625. 'play' -> 'golf' | 'dachshund' | 'to'
  626. 'dachshund' -> 'his'
  627. """
  628. )
  629. print(grammar)
  630. ndp = NonprojectiveDependencyParser(grammar)
  631. graphs = ndp.parse(
  632. [
  633. "the",
  634. "man",
  635. "in",
  636. "the",
  637. "corner",
  638. "taught",
  639. "his",
  640. "dachshund",
  641. "to",
  642. "play",
  643. "golf",
  644. ]
  645. )
  646. print("Graphs:")
  647. for graph in graphs:
  648. print(graph)
  649. if __name__ == "__main__":
  650. demo()