3 # dmv reestimation and inside-outside probabilities using loc_h, and
6 #import numpy # numpy provides Fast Arrays, for future optimization
8 from common_dmv
import *
10 ### todo: debug with @accepts once in a while, but it's SLOW
11 # from typecheck import accepts, Any
13 if __name__
== "__main__":
14 print "loc_h_dmv module tests:"
16 def adj(middle
, loc_h
):
17 "middle is eg. k when rewriting for i<k<j (inside probabilities)."
18 return middle
== loc_h
or middle
== loc_h
+1 # ADJ == True
20 def make_GO_AT(p_STOP
,p_ATTACH
):
22 for (a
,h
,dir), p_ah
in p_ATTACH
.iteritems():
23 p_GO_AT
[a
,h
,dir, NON
] = p_ah
* (1-p_STOP
[h
, dir, NON
])
24 p_GO_AT
[a
,h
,dir, ADJ
] = p_ah
* (1-p_STOP
[h
, dir, ADJ
])
27 class DMV_Grammar(io
.Grammar
):
30 return "%d=%s" % (n
, self
.numtag(n
))
37 p_L
= p(self
.p_ATTACH
,(a
,h
,LEFT
))
38 p_R
= p(self
.p_ATTACH
,(a
,h
,RIGHT
))
39 if p_L
== 0.0 and p_R
== 0.0:
43 str = "p_ATTACH[ %s|%s,L] = %.4f" % (t(a
), t(h
), p_L
)
48 str += "p_ATTACH[ %s|%s,R] = %.4f" % (t(a
), t(h
), p_R
)
51 root
, stop
, att
, ord = "","","",""
52 for h
in self
.headnums():
53 root
+= "p_ROOT[%s] = %.4f\n" % (t(h
), p(self
.p_ROOT
, (h
)))
54 stop
+= "p_STOP[stop|%s,L,adj] = %.4f\t" % (t(h
), p(self
.p_STOP
, (h
,LEFT
,ADJ
)))
55 stop
+= "p_STOP[stop|%s,R,adj] = %.4f\n" % (t(h
), p(self
.p_STOP
, (h
,RIGHT
,ADJ
)))
56 stop
+= "p_STOP[stop|%s,L,non] = %.4f\t" % (t(h
), p(self
.p_STOP
, (h
,LEFT
,NON
)))
57 stop
+= "p_STOP[stop|%s,R,non] = %.4f\n" % (t(h
), p(self
.p_STOP
, (h
,RIGHT
,NON
)))
58 att
+= ''.join([p_a(a
,h
) for a
in self
.headnums()])
59 ord += "p_ORDER[ left-first|%s ] = %.4f\t" % (t(h
), p(self
.p_ORDER
, (GOL
,h
)))
60 ord += "p_ORDER[right-first|%s ] = %.4f\n" % (t(h
), p(self
.p_ORDER
, (GOR
,h
)))
61 return root
+ stop
+ att
+ ord
63 def __init__(self
, numtag
, tagnum
, p_ROOT
, p_STOP
, p_ATTACH
, p_ORDER
):
64 io
.Grammar
.__init
__(self
, numtag
, tagnum
)
65 self
.p_ROOT
= p_ROOT
# p_ROOT[w] = p
66 self
.p_ORDER
= p_ORDER
# p_ORDER[seals, w] = p
67 self
.p_STOP
= p_STOP
# p_STOP[w, LEFT, NON] = p (etc. for LA,RN,RA)
68 self
.p_ATTACH
= p_ATTACH
# p_ATTACH[a, h, LEFT] = p (etc. for R)
69 # p_GO_AT[a, h, LEFT, NON] = p (etc. for LA,RN,RA)
70 self
.p_GO_AT
= make_GO_AT(self
.p_STOP
, self
.p_ATTACH
)
72 def p_GO_AT_or0(self
, a
, h
, dir, adj
):
74 return self
.p_GO_AT
[a
, h
, dir, adj
]
79 def locs(sent_nums
, start
, stop
):
80 '''Return the between-word locations of all words in some fragment of
81 sent. We make sure to offset the locations correctly so that for
82 any w in the returned list, sent[w]==loc_w.
84 start is inclusive, stop is exclusive, as in klein-thesis and
85 Python's list-slicing.'''
86 for i0
,w
in enumerate(sent_nums
[start
:stop
]):
90 ###################################################
91 # P_INSIDE (dmv-specific) #
92 ###################################################
94 #@accepts(int, int, (int, int), int, Any(), [str], {tuple:float}, IsOneOf(None,{}))
95 def inner(i
, j
, node
, loc_h
, g
, sent
, ichart
={}, mpptree
=None):
96 ''' The ichart is of this form:
97 ichart[i,j,LHS, loc_h]
98 where i and j are between-word positions.
100 loc_h gives adjacency (along with k for attachment rules), and is
101 needed in P_STOP reestimation.
103 sent_nums
= g
.sent_nums(sent
)
105 def terminal(i
,j
,node
, loc_h
, tabs
):
106 if not i
<= loc_h
< j
:
108 print "%s*= 0.0 (wrong loc_h)" % tabs
110 elif POS(node
) == sent_nums
[i
] and node
in g
.p_ORDER
:
111 # todo: add to ichart perhaps? Although, it _is_ simple lookup..
112 prob
= g
.p_ORDER
[node
]
115 print "%sLACKING TERMINAL:" % tabs
118 print "%s*= %.4f (terminal: %s -> %s_%d)" % (tabs
,prob
, node_str(node
), sent
[i
], loc_h
)
121 def e(i
,j
, (s_h
,h
), loc_h
, n_t
):
124 key
= (i
,j
, (s_h
,h
), loc_h
)
125 if key
not in mpptree
:
126 mpptree
[key
] = (p
, L
, R
)
127 elif mpptree
[key
][0] < p
:
128 mpptree
[key
] = (p
, L
, R
)
131 "Tabs for debug output"
134 if (i
, j
, (s_h
,h
), loc_h
) in ichart
:
136 print "%s*= %.4f in ichart: i:%d j:%d node:%s loc:%s" % (tab(),ichart
[i
, j
, (s_h
,h
), loc_h
], i
, j
,
137 node_str((s_h
,h
)), loc_h
)
138 return ichart
[i
, j
, (s_h
,h
), loc_h
]
140 # Either terminal rewrites, using p_ORDER:
141 if i
+1 == j
and (s_h
== GOR
or s_h
== GOL
):
142 return terminal(i
, j
, (s_h
,h
), loc_h
, tab())
143 else: # Or not at terminal level yet:
145 print "%s%s (%.1f) from %d to %d" % (tab(),node_str((s_h
,h
)),loc_h
,i
,j
)
147 p_RGOL
= g
.p_STOP
[h
, LEFT
, adj(i
,loc_h
)] * e(i
,j
,(RGOL
,h
),loc_h
,n_t
+1)
148 p_LGOR
= g
.p_STOP
[h
, RIGHT
, adj(j
,loc_h
)] * e(i
,j
,(LGOR
,h
),loc_h
,n_t
+1)
150 to_mpp(p_RGOL
, STOPKEY
, (i
,j
, (RGOL
,h
),loc_h
))
151 to_mpp(p_LGOR
, (i
,j
, (RGOL
,h
),loc_h
), STOPKEY
)
153 print "%sp= %.4f (STOP)" % (tab(), p
)
154 elif s_h
== RGOL
or s_h
== GOL
:
157 p
= g
.p_STOP
[h
, RIGHT
, adj(j
,loc_h
)] * e(i
,j
, (GOR
,h
),loc_h
,n_t
+1)
158 to_mpp(p
, (i
,j
, (GOR
,h
),loc_h
), STOPKEY
)
159 for k
in xgo_left(i
, loc_h
): # i < k <= loc_l(h)
160 p_R
= e(k
, j
, ( s_h
,h
), loc_h
, n_t
+1)
162 for loc_a
,a
in locs(sent_nums
, i
, k
):
163 p_ah
= g
.p_GO_AT_or0(a
, h
, LEFT
, adj(k
,loc_h
))
165 p_L
= e(i
, k
, (SEAL
,a
), loc_a
, n_t
+1)
166 p_add
= p_L
* p_ah
* p_R
169 (i
, k
, (SEAL
,a
), loc_a
),
170 (k
, j
, ( s_h
,h
), loc_h
))
172 print "%sp= %.4f (ATTACH)" % (tab(), p
)
173 elif s_h
== GOR
or s_h
== LGOR
:
176 p
= g
.p_STOP
[h
, LEFT
, adj(i
,loc_h
)] * e(i
,j
, (GOL
,h
),loc_h
,n_t
+1)
177 to_mpp(p
, (i
,j
, (GOL
,h
),loc_h
), STOPKEY
)
178 for k
in xgo_right(loc_h
, j
): # loc_l(h) < k < j
179 p_L
= e(i
, k
, ( s_h
,h
), loc_h
, n_t
+1)
181 for loc_a
,a
in locs(sent_nums
,k
,j
):
182 p_ah
= g
.p_GO_AT_or0(a
, h
, RIGHT
, adj(k
,loc_h
))
183 p_R
= e(k
, j
, (SEAL
,a
), loc_a
, n_t
+1)
184 p_add
= p_L
* p_ah
* p_R
187 (i
, k
, ( s_h
,h
), loc_h
),
188 (k
, j
, (SEAL
,a
), loc_a
))
191 print "%sp= %.4f (ATTACH)" % (tab(), p
)
192 # elif s_h == GOL: # todo
194 ichart
[i
, j
, (s_h
,h
), loc_h
] = p
198 inner_prob
= e(i
,j
,node
,loc_h
, 0)
200 print debug_ichart(g
,sent
,ichart
)
202 # end of dmv.inner(i, j, node, loc_h, g, sent, ichart={})
205 def debug_ichart(g
,sent
,ichart
):
206 str = "---ICHART:---\n"
207 for (s
,t
,LHS
,loc_h
),v
in ichart
.iteritems():
208 str += "%s -> %s_%d ... %s_%d (loc_h:%s):\t%.4f\n" % (node_str(LHS
,g
.numtag
),
209 sent
[s
], s
, sent
[s
], t
, loc_h
, v
)
210 str += "---ICHART:end---\n"
214 def inner_sent(g
, sent
, ichart
={}):
215 return sum([g
.p_ROOT
[w
] * inner(0, len(sent
), (SEAL
,w
), loc_w
, g
, sent
, ichart
)
216 for loc_w
,w
in locs(g
.sent_nums(sent
),0,len(sent
))])
222 ###################################################
223 # P_OUTSIDE (dmv-specific) #
224 ###################################################
226 #@accepts(int, int, (int, int), int, Any(), [str], {tuple:float}, {tuple:float})
227 def outer(i
,j
,w_node
,loc_w
, g
, sent
, ichart
={}, ochart
={}):
228 ''' http://www.student.uib.no/~kun041/dmvccm/DMVCCM.html#outer
230 w_node is a pair (seals,POS); the w in klein-thesis is made up of
233 sent_nums
= g
.sent_nums(sent
)
236 def e(i
,j
,LHS
,loc_h
): # P_{INSIDE}
238 return ichart
[i
,j
,LHS
,loc_h
]
240 return inner(i
,j
,LHS
,loc_h
,g
,sent
,ichart
)
242 def f(i
,j
,w_node
,loc_w
):
243 if (i
,j
,w_node
,loc_w
) in ochart
:
244 return ochart
[i
,j
, w_node
,loc_w
]
246 if i
== 0 and j
== len(sent
):
248 else: # ROOT may only be used on full sentence
250 # but we may have non-ROOTs (stops) over full sentence too:
254 # todo: try either if p_M > 0.0: or sum(), and speed-test them
256 if s_w
== SEAL
: # w == a
257 # todo: do the i<sent<j check here to save on calls?
258 p
= g
.p_ROOT
[w
] * f(i
,j
,ROOT
,loc_w
)
260 for k
in xgt(j
, sent
): # j<k<len(sent)+1
261 for loc_h
,h
in locs(sent_nums
,j
,k
):
262 p_wh
= g
.p_GO_AT_or0(w
, h
, LEFT
, adj(j
, loc_h
))
263 for s_h
in [RGOL
, GOL
]:
264 p
+= f(i
,k
,(s_h
,h
),loc_h
) * p_wh
* e(j
,k
,(s_h
,h
),loc_h
)
266 for k
in xlt(i
): # k<i
267 for loc_h
,h
in locs(sent_nums
,k
,i
):
268 p_wh
= g
.p_GO_AT_or0(w
, h
, RIGHT
, adj(i
, loc_h
))
269 for s_h
in [LGOR
, GOR
]:
270 p
+= e(k
,i
,(s_h
,h
), loc_h
) * p_wh
* f(k
,j
,(s_h
,h
), loc_h
)
272 elif s_w
== RGOL
or s_w
== GOL
: # w == h, left stop + left attach
277 p
= g
.p_STOP
[w
, LEFT
, adj(i
,loc_w
)] * f(i
,j
,( s_h
,w
),loc_w
)
278 for k
in xlt(i
): # k<i
279 for loc_a
,a
in locs(sent_nums
,k
,i
):
280 p_aw
= g
.p_GO_AT_or0(a
, w
, LEFT
, adj(i
, loc_w
))
281 p
+= e(k
,i
, (SEAL
,a
),loc_a
) * p_aw
* f(k
,j
,w_node
,loc_w
)
283 elif s_w
== GOR
or s_w
== LGOR
: # w == h, right stop + right attach
288 p
= g
.p_STOP
[w
, RIGHT
, adj(j
,loc_w
)] * f(i
,j
,( s_h
,w
),loc_w
)
289 for k
in xgt(j
, sent
): # j<k<len(sent)+1
290 for loc_a
,a
in locs(sent_nums
,j
,k
):
291 p_ah
= g
.p_GO_AT_or0(a
, w
, RIGHT
, adj(j
, loc_w
))
292 p
+= f(i
,k
,w_node
,loc_w
) * p_ah
* e(j
,k
,(SEAL
,a
),loc_a
)
294 ochart
[i
,j
,w_node
,loc_w
] = p
298 return f(i
,j
,w_node
,loc_w
)
299 # end outer(i,j,w_node,loc_w, g,sent, ichart,ochart)
304 ###################################################
306 ###################################################
308 def reest_zeros(h_nums
):
309 '''A dict to hold numerators and denominators for our 6+ reestimation
312 fr
= { ('ROOT','den'):0.0 } # holds sum over p_sent
314 fr
['ROOT','num',h
] = 0.0
315 for s_h
in [GOR
,GOL
,RGOL
,LGOR
]:
317 fr
['hat_a','den',x
] = 0.0 # = c()
318 # not all arguments are attached to, so we just initialize
319 # fr['hat_a','num',a,(s_h,h)] as they show up, in reest_freq
320 for adj
in [NON
, ADJ
]:
321 for nd
in ['num','den']:
322 fr
['STOP',nd
,x
,adj
] = 0.0
325 def reest_freq(g
, corpus
):
326 fr
= reest_zeros(g
.headnums())
329 p_sent
= None # 50 % speed increase on storing this locally
331 # local functions altogether 2x faster than global
332 def c(i
,j
,LHS
,loc_h
,sent
):
336 p_in
= e(i
,j
, LHS
,loc_h
,sent
)
340 p_out
= f(i
,j
, LHS
,loc_h
,sent
)
341 return p_in
* p_out
/ p_sent
344 def f(i
,j
,LHS
,loc_h
,sent
): # P_{OUTSIDE}
346 return ochart
[i
,j
,LHS
,loc_h
]
348 return outer(i
,j
,LHS
,loc_h
,g
,sent
,ichart
,ochart
)
351 def e(i
,j
,LHS
,loc_h
,sent
): # P_{INSIDE}
353 return ichart
[i
,j
,LHS
,loc_h
]
355 return inner(i
,j
,LHS
,loc_h
,g
,sent
,ichart
)
358 def w_left(i
,j
, x
,loc_h
,sent
,sent_nums
):
363 for k
in xtween(i
, j
):
364 p_out
= f(i
,j
, x
,loc_h
, sent
)
367 p_R
= e(k
,j
, x
,loc_h
, sent
)
371 for loc_a
,a
in locs(sent_nums
, i
,k
): # i<=loc_l(a)<k
372 p_rule
= g
.p_GO_AT_or0(a
, h
, LEFT
, adj(k
, loc_h
))
373 p_L
= e(i
,k
, (SEAL
,a
), loc_a
, sent
)
374 p
= p_L
* p_out
* p_R
* p_rule
/ p_sent
376 fr
['hat_a','num',a
,x
] += p
378 fr
['hat_a','num',a
,x
] = p
379 # end reest_freq.w_left()
381 def w_right(i
,j
, x
,loc_h
,sent
,sent_nums
):
386 for k
in xtween(i
, j
):
387 p_out
= f(i
,j
, x
,loc_h
, sent
)
390 p_L
= e(i
,k
, x
,loc_h
, sent
)
394 for loc_a
,a
in locs(sent_nums
, k
,j
): # k<=loc_l(a)<j
395 p_rule
= g
.p_GO_AT_or0(a
, h
, RIGHT
, adj(k
, loc_h
))
396 p_R
= e(k
,j
, (SEAL
,a
),loc_a
, sent
)
397 p
= p_L
* p_out
* p_R
* p_rule
/ p_sent
399 fr
['hat_a','num',a
,x
] += p
401 fr
['hat_a','num',a
,x
] = p
402 # end reest_freq.w_right()
410 p_sent
= inner_sent(g
, sent
, ichart
)
411 fr
['ROOT','den'] += p_sent
413 sent_nums
= g
.sent_nums(sent
)
415 for loc_h
,h
in locs(sent_nums
,0,len(sent
)+1): # locs-stop is exclusive, thus +1
417 fr
['ROOT','num',h
] += g
.p_ROOT
[h
] * e(0,len(sent
), (SEAL
,h
),loc_h
, sent
)
422 # left non-adjacent stop:
423 for i
in xlt(loc_l_h
):
424 fr
['STOP','num',(GOL
,h
),NON
] += c(loc_l_h
, j
, (LGOR
, h
),loc_h
, sent
)
425 fr
['STOP','den',(GOL
,h
),NON
] += c(loc_l_h
, j
, (GOL
, h
),loc_h
, sent
)
426 for j
in xgteq(loc_r_h
, sent
):
427 fr
['STOP','num',(RGOL
,h
),NON
] += c(i
, j
, (SEAL
, h
),loc_h
, sent
)
428 fr
['STOP','den',(RGOL
,h
),NON
] += c(i
, j
, (RGOL
, h
),loc_h
, sent
)
429 # left adjacent stop, i = loc_l_h
430 fr
['STOP','num',(GOL
,h
),ADJ
] += c(loc_l_h
, loc_r_h
, (LGOR
, h
),loc_h
, sent
)
431 fr
['STOP','den',(GOL
,h
),ADJ
] += c(loc_l_h
, loc_r_h
, (GOL
, h
),loc_h
, sent
)
432 for j
in xgteq(loc_r_h
, sent
):
433 fr
['STOP','num',(RGOL
,h
),ADJ
] += c(loc_l_h
, j
, (SEAL
, h
),loc_h
, sent
)
434 fr
['STOP','den',(RGOL
,h
),ADJ
] += c(loc_l_h
, j
, (RGOL
, h
),loc_h
, sent
)
435 # right non-adjacent stop:
436 for j
in xgt(loc_r_h
, sent
):
437 fr
['STOP','num',(GOR
,h
),NON
] += c(loc_l_h
, j
, (RGOL
, h
),loc_h
, sent
)
438 fr
['STOP','den',(GOR
,h
),NON
] += c(loc_l_h
, j
, (GOR
, h
),loc_h
, sent
)
439 for i
in xlteq(loc_l_h
):
440 fr
['STOP','num',(LGOR
,h
),NON
] += c(loc_l_h
, j
, (SEAL
, h
),loc_h
, sent
)
441 fr
['STOP','den',(LGOR
,h
),NON
] += c(loc_l_h
, j
, (LGOR
, h
),loc_h
, sent
)
442 # right adjacent stop, j = loc_r_h
443 fr
['STOP','num',(GOR
,h
),ADJ
] += c(loc_l_h
, loc_r_h
, (RGOL
, h
),loc_h
, sent
)
444 fr
['STOP','den',(GOR
,h
),ADJ
] += c(loc_l_h
, loc_r_h
, (GOR
, h
),loc_h
, sent
)
445 for i
in xlteq(loc_l_h
):
446 fr
['STOP','num',(LGOR
,h
),ADJ
] += c(loc_l_h
, j
, (SEAL
, h
),loc_h
, sent
)
447 fr
['STOP','den',(LGOR
,h
),ADJ
] += c(loc_l_h
, j
, (LGOR
, h
),loc_h
, sent
)
450 if 'REEST_ATTACH' in DEBUG
:
451 print "Lattach %s: for i < %s"%(g
.numtag(h
),sent
[0:loc_h
+1])
452 for s_h
in [RGOL
, GOL
]:
454 for i
in xlt(loc_l_h
): # i < loc_l(h)
455 if 'REEST_ATTACH' in DEBUG
:
456 print "\tfor j >= %s"%sent
[loc_h
:len(sent
)]
457 for j
in xgteq(loc_r_h
, sent
): # j >= loc_r(h)
458 fr
['hat_a','den',x
] += c(i
,j
, x
,loc_h
, sent
) # v_q in L&Y
459 if 'REEST_ATTACH' in DEBUG
:
460 print "\t\tc( %d , %d, %s, %s, sent)=%.4f"%(i
,j
,node_str(x
),loc_h
,fr
['hat_a','den',x
])
461 w_left(i
, j
, x
,loc_h
, sent
,sent_nums
) # compute w for all a in sent
464 if 'REEST_ATTACH' in DEBUG
:
465 print "Rattach %s: for i <= %s"%(g
.numtag(h
),sent
[0:loc_h
+1])
466 for s_h
in [GOR
, LGOR
]:
468 for i
in xlteq(loc_l_h
): # i <= loc_l(h)
469 if 'REEST_ATTACH' in DEBUG
:
470 print "\tfor j > %s"%sent
[loc_h
:len(sent
)]
471 for j
in xgt(loc_r_h
, sent
): # j > loc_r(h)
472 fr
['hat_a','den',x
] += c(i
,j
, x
,loc_h
, sent
) # v_q in L&Y
473 if 'REEST_ATTACH' in DEBUG
:
474 print "\t\tc( %d , %d, %s, %s, sent)=%.4f"%(loc_h
,j
,node_str(x
),loc_h
,fr
['hat_a','den',x
])
475 w_right(loc_l_h
,j
, x
,loc_h
, sent
,sent_nums
) # compute w for all a in sent
482 def reestimate(g
, corpus
):
483 fr
= reest_freq(g
, corpus
)
484 p_ROOT
, p_STOP
, p_ATTACH
= {},{},{}
486 for h
in g
.headnums():
487 reest_head(h
, fr
, g
, p_ROOT
, p_STOP
, p_ATTACH
)
490 g
.p_ATTACH
= p_ATTACH
491 g
.p_GO_AT
= make_GO_AT(p_STOP
,p_ATTACH
)
496 def reest_head(h
, fr
, g
, p_ROOT
, p_STOP
, p_ATTACH
):
497 "Given a single head, update g with the reestimated probability."
498 # remove 0-prob stuff? todo
500 p_ROOT
[h
] = fr
['ROOT','num',h
] / fr
['ROOT','den']
502 p_ROOT
[h
] = fr
['ROOT','den']
504 for dir in [LEFT
,RIGHT
]:
505 for adj
in [ADJ
, NON
]: # p_STOP
506 p_STOP
[h
, dir, adj
] = 0.0
507 for s_h
in dirseal(dir):
509 p
= fr
['STOP','den', x
, adj
]
511 p
= fr
['STOP', 'num', x
, adj
] / p
512 p_STOP
[h
, dir, adj
] += p
514 for s_h
in dirseal(dir): # make hat_a for p_ATTACH
518 p_c
= fr
['hat_a','den',x
]
519 for a
in g
.headnums():
521 hat_a
[a
,x
] = fr
['hat_a','num',a
,x
] / p_c
525 sum_hat_a
= sum([hat_a
[w
,x
] for w
in g
.headnums()
528 for a
in g
.headnums():
529 if (a
,h
,dir) not in p_ATTACH
:
530 p_ATTACH
[a
,h
,dir] = 0.0
531 try: # (a,x) might not be in hat_a
532 p_ATTACH
[a
,h
,dir] += hat_a
[a
,x
] / sum_hat_a
543 ###################################################
544 # Most Probable Parse: #
545 ###################################################
547 STOPKEY
= (-1,-1,STOP
,-1)
548 ROOTKEY
= (-1,-1,ROOT
,-1)
550 def make_mpptree(g
, sent
):
551 '''Tell inner() to make an mpptree, connect ROOT to this. (Logically,
552 this should be part of inner_sent though...)'''
554 mpptree
= { ROOTKEY
:(0.0, ROOTKEY
, None) }
555 for loc_w
,w
in locs(g
.sent_nums(sent
),0,len(sent
)):
556 p
= g
.p_ROOT
[w
] * inner(0, len(sent
), (SEAL
,w
), loc_w
, g
, sent
, ichart
, mpptree
)
558 R
= (0,len(sent
), (SEAL
,w
), loc_w
)
559 if mpptree
[ROOTKEY
][0] < p
:
560 mpptree
[ROOTKEY
] = (p
, L
, R
)
563 def parse_mpptree(mpptree
, sent
):
564 '''mpptree is a dict of the form {k:(p,L,R),...}; where k, L and R
565 are `keys' of the form (i,j,node,loc).
567 returns an mpp of the form [((head, loc_h),(arg, loc_a)), ...],
568 where head and arg are tags.'''
569 # local functions for clear access to mpptree:
573 return POS(k_node(key
))
575 return seals(k_node(key
))
577 return (k_node(key
),key
[3])
579 return (k_POS(key
),key
[3])
581 s_k
= k_seals(key
) # i+1 == j
582 return key
[0] + 1 == key
[1] and (s_k
== GOR
or s_k
== GOL
)
588 # arbitrarily, "ROOT attaches to right". We add it here to
589 # avoid further complications:
590 firstkey
= t_R(mpptree
[ROOTKEY
])
591 deps
= set([ (k_locPOS(ROOTKEY
), k_locPOS(firstkey
), RIGHT
) ])
599 L
= t_L( mpptree
[k
] )
600 R
= t_R( mpptree
[k
] )
601 if k_locnode( k
) == k_locnode( L
): # Rattach
602 deps
.add((k_locPOS( k
), k_locPOS( R
), LEFT
))
604 elif k_locnode( k
) == k_locnode( R
): # Lattach
605 deps
.add((k_locPOS( k
), k_locPOS( L
), RIGHT
))
614 tagf
= g
.numtag
# localized function, todo: speed-test
615 mpptree
= make_mpptree(g
, sent
)
616 return set([((tagf(h
), loc_h
), (tagf(a
), loc_a
))
617 for (h
, loc_h
),(a
,loc_a
),dir in parse_mpptree(mpptree
,sent
)])
620 ########################################################################
621 # testing functions: #
622 ########################################################################
624 testcorpus
= [s
.split() for s
in ['det nn vbd c vbd','vbd nn c vbd',
625 'det nn vbd', 'det nn vbd c pp',
626 'det nn vbd', 'det vbd vbd c pp',
627 'det nn vbd', 'det nn vbd c vbd',
628 'det nn vbd', 'det nn vbd c vbd',
629 'det nn vbd', 'det nn vbd c vbd',
630 'det nn vbd', 'det nn vbd c pp',
631 'det nn vbd pp', 'det nn vbd', ]]
634 import loc_h_harmonic
635 reload(loc_h_harmonic
)
636 return loc_h_harmonic
.initialize(testcorpus
)
638 def ig(s
,t
,LHS
,loc_h
):
639 return inner(s
,t
,LHS
,loc_h
,testgrammar(),'det nn vbd'.split(),{})
641 def testreestimation():
644 # DEBUG.add('REEST_ATTACH')
645 f
= reestimate(g
, testcorpus
)
647 testreestimation_regression(f
)
650 def testreestimation_regression(fr
):
651 f_stops
= {('STOP', 'den', (RGOL
,3),NON
): 12.212773236178391, ('STOP', 'den', (GOR
,2),ADJ
): 4.0, ('STOP', 'num', (GOR
,4),NON
): 2.5553487221351365, ('STOP', 'den', (RGOL
,2),NON
): 1.274904052793207, ('STOP', 'num', (RGOL
,1),ADJ
): 14.999999999999995, ('STOP', 'den', (GOR
,3),ADJ
): 15.0, ('STOP', 'num', (RGOL
,4),ADJ
): 16.65701084787457, ('STOP', 'num', (RGOL
,0),ADJ
): 4.1600647714443468, ('STOP', 'den', (RGOL
,4),NON
): 6.0170669155897105, ('STOP', 'num', (RGOL
,3),ADJ
): 2.7872267638216113, ('STOP', 'num', (RGOL
,2),ADJ
): 2.9723139990470515, ('STOP', 'den', (RGOL
,2),ADJ
): 4.0, ('STOP', 'den', (GOR
,3),NON
): 12.945787931730905, ('STOP', 'den', (RGOL
,3),ADJ
): 14.999999999999996, ('STOP', 'den', (GOR
,2),NON
): 0.0, ('STOP', 'den', (RGOL
,0),ADJ
): 8.0, ('STOP', 'num', (GOR
,4),ADJ
): 19.44465127786486, ('STOP', 'den', (GOR
,1),NON
): 3.1966410324085777, ('STOP', 'den', (RGOL
,1),ADJ
): 14.999999999999995, ('STOP', 'num', (GOR
,3),ADJ
): 4.1061665495365558, ('STOP', 'den', (GOR
,0),NON
): 4.8282499043902476, ('STOP', 'num', (RGOL
,4),NON
): 5.3429891521254289, ('STOP', 'num', (GOR
,2),ADJ
): 4.0, ('STOP', 'den', (RGOL
,4),ADJ
): 22.0, ('STOP', 'num', (GOR
,1),ADJ
): 12.400273895299103, ('STOP', 'num', (RGOL
,2),NON
): 1.0276860009529487, ('STOP', 'num', (GOR
,0),ADJ
): 3.1717500956097533, ('STOP', 'num', (RGOL
,3),NON
): 12.212773236178391, ('STOP', 'den', (GOR
,4),ADJ
): 22.0, ('STOP', 'den', (GOR
,4),NON
): 2.8705211946979836, ('STOP', 'num', (RGOL
,0),NON
): 3.8399352285556518, ('STOP', 'num', (RGOL
,1),NON
): 0.0, ('STOP', 'num', (GOR
,0),NON
): 4.8282499043902476, ('STOP', 'num', (GOR
,1),NON
): 2.5997261047008959, ('STOP', 'den', (RGOL
,1),NON
): 0.0, ('STOP', 'den', (GOR
,0),ADJ
): 8.0, ('STOP', 'num', (GOR
,2),NON
): 0.0, ('STOP', 'den', (RGOL
,0),NON
): 4.6540557322109795, ('STOP', 'den', (GOR
,1),ADJ
): 15.0, ('STOP', 'num', (GOR
,3),NON
): 10.893833450463443}
652 for k
,v
in f_stops
.iteritems():
654 print '''Regression in P_STOP reestimation, should be fr[%s]=%.4f,
655 but %s not in fr'''%(k
,v
,k
)
656 elif not "%.10f"%fr[k
] == "%.10f"%v
:
657 print '''Regression in P_STOP reestimation, should be fr[%s]=%.4f,
658 got fr[%s]=%.4f.'''%(k
,v
,k
,fr
[k
])
660 def testmpp_regression(mpptree
,k_n
):
661 mpp
= {ROOTKEY
: (2.877072116829971e-05, STOPKEY
, (0, 3, (2, 3), 1)),
662 (0, 1, (1, 1), 0): (0.1111111111111111, (0, 1, (0, 1), 0), STOPKEY
),
663 (0, 1, (2, 1), 0): (0.049382716049382713, STOPKEY
, (0, 1, (1, 1), 0)),
664 (0, 3, (1, 3), 1): (0.00027619892321567721,
667 (0, 3, (2, 3), 1): (0.00012275507698474543, STOPKEY
, (0, 3, (1, 3), 1)),
668 (1, 3, (0, 3), 1): (0.025280986819448362,
671 (1, 3, (1, 3), 1): (0.0067415964851862296, (1, 3, (0, 3), 1), STOPKEY
),
672 (2, 3, (1, 4), 2): (0.32692307692307693, (2, 3, (0, 4), 2), STOPKEY
),
673 (2, 3, (2, 4), 2): (0.037721893491124266, STOPKEY
, (2, 3, (1, 4), 2))}
674 for k
,(v
,L
,R
) in mpp
.iteritems():
675 k2
= k
[0:k_n
] # 3 if the new does not check loc_h
678 if k2
not in mpptree
:
679 print "mpp regression, %s missing"%(k2
,)
681 vnew
= mpptree
[k2
][0]
682 if not "%.10f"%vnew
== "%.10f"%v
:
683 print "mpp regression, wanted %s=%.5f, got %.5f"%(k2
,v
,vnew
)
686 def testgrammar_a2():
688 p_ROOT
, p_STOP
, p_ATTACH
, p_ORDER
= {},{},{},{}
691 p_STOP
[h
,LEFT
,NON
] = 1.0
692 p_STOP
[h
,LEFT
,ADJ
] = 1.0
693 p_STOP
[h
,RIGHT
,NON
] = 0.4 # RSTOP
694 p_STOP
[h
,RIGHT
,ADJ
] = 0.3 # RSTOP
695 p_STOP
[a
,LEFT
,NON
] = 1.0
696 p_STOP
[a
,LEFT
,ADJ
] = 1.0
697 p_STOP
[a
,RIGHT
,NON
] = 0.4 # RSTOP
698 p_STOP
[a
,RIGHT
,ADJ
] = 0.3 # RSTOP
699 p_ATTACH
[a
,h
,LEFT
] = 1.0 # not used
700 p_ATTACH
[a
,h
,RIGHT
] = 1.0 # not used
701 p_ATTACH
[h
,a
,LEFT
] = 1.0 # not used
702 p_ATTACH
[h
,a
,RIGHT
] = 1.0 # not used
703 p_ATTACH
[h
,h
,LEFT
] = 1.0 # not used
704 p_ATTACH
[h
,h
,RIGHT
] = 1.0 # not used
705 p_ORDER
[(GOR
, h
)] = 1.0
706 p_ORDER
[(GOL
, h
)] = 0.0
707 p_ORDER
[(GOR
, a
)] = 1.0
708 p_ORDER
[(GOL
, a
)] = 0.0
709 g
= DMV_Grammar({h
:'h',a
:'a'}, {'h':h
,'a':a
}, p_ROOT
, p_STOP
, p_ATTACH
, p_ORDER
)
710 # these probabilities are impossible so add them manually:
711 g
.p_GO_AT
[a
,a
,LEFT
,NON
] = 0.4 # Lattach
712 g
.p_GO_AT
[a
,a
,LEFT
,ADJ
] = 0.6 # Lattach
713 g
.p_GO_AT
[h
,a
,LEFT
,NON
] = 0.2 # Lattach to h
714 g
.p_GO_AT
[h
,a
,LEFT
,ADJ
] = 0.1 # Lattach to h
715 g
.p_GO_AT
[a
,a
,RIGHT
,NON
] = 1.0 # Rattach
716 g
.p_GO_AT
[a
,a
,RIGHT
,ADJ
] = 1.0 # Rattach
717 g
.p_GO_AT
[h
,a
,RIGHT
,NON
] = 1.0 # Rattach to h
718 g
.p_GO_AT
[h
,a
,RIGHT
,ADJ
] = 1.0 # Rattach to h
719 g
.p_GO_AT
[h
,h
,LEFT
,NON
] = 0.2 # Lattach
720 g
.p_GO_AT
[h
,h
,LEFT
,ADJ
] = 0.1 # Lattach
721 g
.p_GO_AT
[a
,h
,LEFT
,NON
] = 0.4 # Lattach to a
722 g
.p_GO_AT
[a
,h
,LEFT
,ADJ
] = 0.6 # Lattach to a
723 g
.p_GO_AT
[h
,h
,RIGHT
,NON
] = 1.0 # Rattach
724 g
.p_GO_AT
[h
,h
,RIGHT
,ADJ
] = 1.0 # Rattach
725 g
.p_GO_AT
[a
,h
,RIGHT
,NON
] = 1.0 # Rattach to a
726 g
.p_GO_AT
[a
,h
,RIGHT
,ADJ
] = 1.0 # Rattach to a
730 def testgrammar_h2():
732 p_ROOT
, p_STOP
, p_ATTACH
, p_ORDER
= {},{},{},{}
734 p_STOP
[h
,LEFT
,NON
] = 1.0
735 p_STOP
[h
,LEFT
,ADJ
] = 1.0
736 p_STOP
[h
,RIGHT
,NON
] = 0.4
737 p_STOP
[h
,RIGHT
,ADJ
] = 0.3
738 p_ATTACH
[h
,h
,LEFT
] = 1.0 # not used
739 p_ATTACH
[h
,h
,RIGHT
] = 1.0 # not used
740 p_ORDER
[(GOR
, h
)] = 1.0
741 p_ORDER
[(GOL
, h
)] = 0.0
742 g
= DMV_Grammar({h
:'h'}, {'h':h
}, p_ROOT
, p_STOP
, p_ATTACH
, p_ORDER
)
743 g
.p_GO_AT
[h
,h
,LEFT
,NON
] = 0.6 # these probabilities are impossible
744 g
.p_GO_AT
[h
,h
,LEFT
,ADJ
] = 0.7 # so add them manually...
745 g
.p_GO_AT
[h
,h
,RIGHT
,NON
] = 1.0
746 g
.p_GO_AT
[h
,h
,RIGHT
,ADJ
] = 1.0
751 def testreestimation_h():
754 reestimate(g
,['h h h'.split()])
757 def regression_tests():
758 testmpp_regression(make_mpptree(testgrammar(), testcorpus
[2]),4)
760 def test(wanted
, got
):
761 if not wanted
== got
:
762 print "Regression! Should be %s: %s" % (wanted
, got
)
764 g_dup2
= testgrammar_h2()
768 "%.3f" % inner(0, 2, (SEAL
,h
), 0, g_dup2
, 'h h'.split(),{}))
771 "%.3f" % inner(0, 2, (SEAL
,h
), 1, g_dup2
, 'h h'.split(),{}))
774 "%.4f" % inner(0, 3, (SEAL
,h
), 2, g_dup2
, 'h h h'.split(),{}))
777 "%.2f" % outer(1, 3, (RGOL
,h
), 2, g_dup2
,'h h h'.split(),{},{}))
780 "%.4f" % outer(0, 1, (GOR
,h
), 0,testgrammar_a2(),'h a'.split(),{},{}))
782 "%.4f" % outer(0, 2, (GOR
,h
), 0,testgrammar_a2(),'h a'.split(),{},{}))
784 "%.4f" % outer(0, 3, (GOR
,h
), 0,testgrammar_a2(),'h a'.split(),{},{}))
786 # todo: add more of these tests...
788 if __name__
== "__main__":
792 # profile.run('testreestimation()')
795 print timeit
.Timer("loc_h_dmv.testreestimation()",'''import loc_h_dmv
796 reload(loc_h_dmv)''').timeit(1)
803 print "sent:%s\nparse:set(\n%s)"%(s
,pprint
.pformat(list(mpp(testgrammar(), s
)),
808 # pprint.pprint( testreestimation())
814 inners
= [(sent
, inner_sent(g
, sent
, {})) for sent
in testcorpus
]