Skip to content

Commit 326867c

Browse files
committed
added code to do bracketed viterbi parse.
1 parent 73c970f commit 326867c

File tree

1 file changed

+43
-1
lines changed

1 file changed

+43
-1
lines changed

syntheticpcfg/inside.py

+43-1
Original file line numberDiff line numberDiff line change
@@ -258,7 +258,7 @@ def __init__(self, pcfg):
258258
def _bracketed_log_probability(self, tree):
259259
"""
260260
Compute log prob of all derivations with this bracketed tree.
261-
Return a dict mapping nontermials to lof probs
261+
Return a dict mapping nontermials to log probs
262262
"""
263263
if len(tree) == 2:
264264
return { prod[0]: lp for prod,lp in self.lprod_index[tree[1]]}
@@ -277,6 +277,48 @@ def _bracketed_log_probability(self, tree):
277277
answer[a] = score
278278
return answer
279279

280+
def _bracketed_viterbi_probability(self, tree, mapping):
281+
"""
282+
Compute log prob of maximum derivations with this bracketed tree.
283+
Return a dict mapping nontermials to log probs, prod pairs
284+
"""
285+
if len(tree) == 2:
286+
localt = { prod[0]: (lp,prod) for prod,lp in self.lprod_index[tree[1]]}
287+
mapping[tree] = localt
288+
return localt
289+
else:
290+
left = self._bracketed_viterbi_probability(tree[1],mapping)
291+
right = self._bracketed_viterbi_probability(tree[2],mapping)
292+
answer = {}
293+
for leftcat in left:
294+
for prod, prod_lp in self.bprod_index[leftcat]:
295+
a,b,c = prod
296+
if c in right:
297+
score = prod_lp + left[leftcat][0] + right[c][0]
298+
if a in answer:
299+
if score > answer[a][0]:
300+
answer[a] = (score, prod)
301+
else:
302+
answer[a] = (score,prod)
303+
mapping[tree] = answer
304+
return answer
305+
306+
def bracketed_viterbi_parse(self,tree):
307+
mapping = {}
308+
root = self._bracketed_viterbi_probability(tree,mapping)
309+
def reconstruct_tree(label, tree, mapping):
310+
lp, prod = mapping[tree][label]
311+
assert label == prod[0]
312+
if len(tree) == 2:
313+
return prod
314+
else:
315+
a,b,c = prod
316+
left_subtree = reconstruct_tree(b, tree[1], mapping)
317+
right_subtree = reconstruct_tree(c, tree[2], mapping)
318+
return (a, left_subtree, right_subtree)
319+
return reconstruct_tree(self.start,tree,mapping)
320+
321+
280322

281323

282324
def inside_log_probability(self, sentence):

0 commit comments

Comments
 (0)