forked from dtuggener/CorZu
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcorzu.py
executable file
·2151 lines (1910 loc) · 116 KB
/
corzu.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""
# ================================================================ #
CorZu - Incremental Entity-mention Coreference Resolution for German
Author: [email protected]
# ================================================================ #
Usage:
train:
python corzu.py ../tueba_files/train.mables.parzu #real preprocessing
python corzu.py ../tueba_files/train_gold_prep.mables #gold preprocessing
test:
python corzu.py ../tueba_files/test.mables.parzu ../tueba_files/test_9.1.conll main.res
when loaded as module main:
train:
main.main('../tueba_files/train_ner.mables.parzu')
test:
main.main('../tueba_files/dev_ner.mables.parzu','../tueba_files/dev_9.1.conll','mle_dev_tmp.res') #real preprocessing
main.main('../tueba_files/dev_gold_prep.mables','../tueba_files/dev_9.1.conll','mle_dev_tmp.res') #gold preprocessing
"""
# ============================================= #
''' IMPORTS '''
import copy, cPickle, operator, re, sys, pdb, os, subprocess
from math import ceil,log
from itertools import combinations
from collections import defaultdict,Counter
from verbadicendi import vdic
import random
# ============================================= #
''' SETTINGS '''
global mode, output_format
mode='test' #train or test
output_format='semeval' #semeval or tueba; take semeval for runnning CorZu on raw text
global preprocessing
preprocessing='real' # gold or real
global classifier
classifier='mle' #mle, thebeast, wapiti
if classifier=='mle':
global ante_counts,pronouns_counts
ante_counts,pronouns_counts={'PPER':0,'PPOSAT':0,'PRELS':0,'PRELAT':0,'PDS':0},{'PPER':0,'PPOSAT':0,'PRELS':0,'PRELAT':0,'PDS':0}
if classifier=='wapiti':
global wapiti_mode,wapiti_path
wapiti_mode='sequence' #sequence one instance per pronoun and all ante_cands
#wapiti_mode='single' #single is one training instance per ante_cand-pper-pair,
if wapiti_mode=='single': wapiti_path='wapiti'
if wapiti_mode=='sequence': wapiti_path='wapiti_seq'
if classifier=='thebeast':
global train_file
train_file='mln/thebeast.train.tueba'
if mode=='train' and os.path.exists(train_file):
os.remove(train_file) #delete the training instances file if we train, as we append to it
global avg_ante_counts,single_ante_counts
avg_ante_counts=defaultdict(list)
single_ante_counts=defaultdict(list)
global output_pronoun_eval, trace_errors, trace_nouns
trace_errors=False #trace pronoun resolution errors
trace_nouns=False #trace noun resolution errors
if mode=='train':
trace_errors=False
trace_nouns=False
output_pronoun_eval=False #print pronoun classifier accuracy for cases where the true antecedent is actually available (i.e. among the candidates)
global link_ne_nn_sets
link_ne_nn_sets=False #rule-based concatenation of person NE entitiy sets to certain animate common noun sets
if link_ne_nn_sets:
global eval_link_ne_nn_sets
eval_link_ne_nn_sets=defaultdict(int)
global verb_postfilter, twin_mode, verb_postfilter_context_w2v, verb_postfilter_context_graph
verb_postfilter_context_w2v=False
verb_postfilter_context_graph=False
verb_postfilter='off' #train, test, or off; re-ranks the top two candidates based on verb semantics
if verb_postfilter=='train':
global verb_postfilter_str,verb_postfilter_feature_names
verb_postfilter_str,verb_postfilter_feature_names=[],[]
if verb_postfilter!='off' or verb_postfilter_context_w2v or verb_postfilter_context_graph:
global verb_postfilter_cnt, accuracy
accuracy=defaultdict(lambda: defaultdict(lambda:defaultdict(int)))
verb_postfilter_cnt=0
twin_mode='off' # train, test, or off; re-ranks the top two candidates; no real improvement
if twin_mode!='off' or verb_postfilter!='off': # can only have twin mode with ranked candidates, i.e. test mode
mode='test'
if verb_postfilter!='off' or verb_postfilter_context_w2v or verb_postfilter_context_graph:
import numpy as np
import compsplit
import gensim
import networkx as nx
import graph_access as graph
from scipy.spatial.distance import cosine
from scipy.sparse import csr_matrix
# make script work from arbitrary directory
corzu_dir = os.path.dirname(os.path.realpath(__file__))
# ============================================= #
''' FUNCTION DEFINITIONS '''
def morph_comp(m1,m2): #m1=[person,number,gender]
"""compare morphology values"""
if m1[1]==m2[1] and m1[2]==m2[2]: return 1 #exact match
if m1[1]=='*' and m1[2]=='*': return 1 #ante underspecified
if m2[1]=='*' and m2[2]=='*': return 1 #anaph underspecified
if m1[1]=='*' and m1[2]==m2[2]: return 1
if m2[1]=='*' and m1[2]==m2[2]: return 1
if m1[2]=='*' and m1[1]==m2[1]: return 1
if m2[2]=='*' and m1[1]==m2[1]: return 1
def pper_comp(ante,pper):
"""morphological compatibility check for personal and relative pronouns"""
#if pper[5]==1: return 0 #don't resolve 1st and 2nd person pronouns
#if pper[5]==1 and ante[9]=='ANIM' and ante[7]=='SG': return 1 #1st person pronoun to animate antes
if ante[-1]=='es': return 0
if pper[1]-ante[1] >3: return 0 #sentence distance
if pper[5]!=ante[5]: return 0 #Person agreement
if pper[-1].lower() in ['sie','ihre','ihr'] and ante[7]=='SG' and ante[6] in ['MASC','NEUT']: return 0
if pper[-1].lower() in ['sie','ihre','ihr'] and ante[-1].lower() in ['er','seine','sein']: return 0
if pper[-1].lower() in ['er','seine','sein'] and ante[-1].lower() in ['sie','ihre','ihr']: return 0
if pper[-1].lower() in ['er','seine','sein'] and ante[6] in ['FEM']: return 0
if not ante[4]=='PPOSAT' and not pper[4] in ['PRELS','PRELAT'] and not ante[5]==1: #same head exclusive, except PPOSAT as ante and PRELS as anaph
if pper[1]==ante[1] and pper[10]==ante[10] and pper[11]==ante[11]!='*': return 0
if not ante[4]=='PPOSAT' and not pper[4] in ['PRELS','PRELAT']:
if pper[1]==ante[1] and pper[2]>=ante[2] and pper[3]<=ante[3]: return 0 # pper not in ante extension
if morph_comp(ante[5:8],pper[5:8]): return 1
def pposat_comp(ante,pper):
"""morphological compatibility check for possessive pronouns"""
if pper[5]!=ante[5]: return 0 #Person
if pper[1]-ante[1] >3: return 0 #sentence distance
if ante[6]=='*' and ante[7]=='*': return 1 #ante underspecified
if re.match('[Mm]ein.*',pper[-1]):
if ante[5]==1 and ante[7]=='SG': return 1
if re.match('[Dd]ein.*',pper[-1]):
if ante[5]==2 and ante[7]=='SG': return 1
if re.match('[Ss]ein.*',pper[-1]) and not ante[-1].lower() in ['sie','ihre','ihr']:
if ante[6] in ['MASC','NEUT','*'] and ante[7]=='SG' and ante[5]==3: return 1
if re.match('[Ii]hr.*',pper[-1]) and not ante[-1].lower() in ['er','seine','sein']:
if ante[6] in ['FEM','*'] and ante[7]=='SG' and ante[5]==3: return 1
if re.match('[Ii]hr.*',pper[-1]) and not ante[-1].lower() in ['er','seine','sein']:
if ante[7]=='PL' and ante[5]==3: return 1
if re.match('[Ee]ur.*',pper[-1]):
if ante[7]=='PL': return 1
if re.match('[Uu]ns.*',pper[-1]):
if ante[7]=='PL' and ante[5]==1: return 1
def update_csets(ante,mable):
"""disambiguate pronoun and update coreference partition"""
mable[9]=ante[9] #animacy projection of ante to mable
mable[12]=ante[12] #ne_type
if mable[4]=='PRF': #override morpho and gf of reflexives by ante
mable[5:10]=ante[5:10]
#if ante[4] in ['NN','NE'] and mable[4] in ['NN','NE']: mable[6:8]=ante[6:8]
if ante[6]!='*' and mable[6]=='*': mable[6]=ante[6]
elif ante[6]=='*' and mable[6]!='*': ante[6]=mable[6]
if ante[7]!='*' and mable[7]=='*': mable[7]=ante[7]
elif ante[7]=='*' and mable[7]!='*': ante[7]=mable[7]
if mable[4]=='PPOSAT':
if ante[1]==mable[1]: mable[8]=ante[8] #same sentence: keep gf/salience of ante
if ante in wl: #ante is from wl: open new cset
csets.append([ante,mable])
wl.remove(ante)
else: #ante is from cset: append to set
for cset in csets:
if ante in cset:
cset.append(mable)
break
def get_true_ante(mable,ante_cands_wl,ante_cands_csets):
"""return true antecedent if amongst antecedent candidates"""
try:
#find cset containing the markable. markable is not the first mention in the cset (otherwise no antecedent)
coref_id_anaphor=next(x for x,y in coref.items() if mable[1:4] in y and sorted(y).index(mable[1:4])!=0)
all_antes=ante_cands_wl+ante_cands_csets
all_antes.sort(reverse=True) #reverse sort to find most recent ante
true_ante=next(a for a in all_antes if a[1:4] in coref[coref_id_anaphor])
except:
true_ante=[]
return true_ante
def get_mable(tm):
try:
return next(m for m in mables if m[1:4]==tm)
except StopIteration:
return tm
# ============================================= #
''' VERB SEMANTICS RELATED STUFF '''
def load_verb_res():
''' Load verb semantics related resources. '''
global G, w2v_model, w2v_model_gf
sys.stderr.write('Loading graph...')
G=nx.read_gpickle('../../sdewac_graph/verbs_and_args_no_subcat.gpickle')
sys.stderr.write(' done.\nLoading word2vec models...')
w2v_model_gf=gensim.models.Word2Vec.load('../../word2vec/vectors_sdewac_gf_skipgram_min50_new.gensim')
sys.stderr.write(' done.\n')
def get_lex(m,res,gf=None):
''' Return a common noun for a markable '''
lex=m[-1]
if m[4]=='NE': #handle coref set info here: try to get a nominal desciptor
if (m[1],m[2]) in nominal_mods:
lex=nominal_mods[m[1],m[2]][0]
else:
try:
cset_m=next(c for c in csets if m in c)
ne_mentions=[mention for mention in cset_m if mention[4]=='NE']
for mention in ne_mentions:
if (mention[1],mention[2]) in nominal_mods:
lex=nominal_mods[mention[1],mention[2]][0]
break
except StopIteration:
lex=m[-1]
elif not m[4]=='NN': #get noun ante for non-NN candidates, i.e. pronouns
try:
cset_m=next(c for c in csets if m in c)
try:
nn_mention=next(mention for mention in cset_m if mention[4]=='NN')
lex=nn_mention[-1]
except StopIteration:
ne_mentions=[mention for mention in cset_m if mention[4]=='NE']
for mention in ne_mentions:
if (mention[1],mention[2]) in nominal_mods:
lex=nominal_mods[mention[1],mention[2]][0]
break
else:
if not ne_mentions==[]:
lex=ne_mentions[0][-1]
else:
lex=m[-1]
except StopIteration:
lex=m[-1]
if '-' in lex: #take hyphenated head
lex=lex.split('-')[-1]
if '|' in lex: #ambiguous lemma, take the one that is in the w2c model
lex=lex.split('|')[0] #crudely take the first lemma
if ' und ' in lex:
lex=lex.split(' und ')[0] #conjunction head: 'man and wife' -> 'man'
try:
if not lex.decode('utf8').isupper(): #Don't change DDR to Ddr
try: lex=lex.decode('utf8').title() #PolitikerIn -> Politikerin
except: pass
except: pass
if res=='w2v_model_gf': #need unicode
try:
lex_unicode=lex.decode('utf8')
except:
lex_unicode=lex
if lex_unicode+'^'+gf in w2v_model_gf:
return lex_unicode+'^'+gf
else:
if unichr(223) in lex_unicode and lex_unicode.replace(unichr(223),'ss')+'^'+gf in w2v_model_gf:
return lex_unicode.replace(unichr(223),'ss')+'^'+gf
if gf=='root' and lex_unicode+'^subj' in w2v_model_gf:
return lex_unicode+'^subj'
#only split if it is not an NE
if not (m[4]=='NE' and lex_unicode==m[-1]):
lex_split=compsplit.split_compound(lex_unicode)
if lex_split[0][0]>0:
lex_unicode=lex_split[0][2]+'^'+gf
if lex_unicode in w2v_model_gf:
return lex_unicode
if unichr(223) in lex_unicode and lex_unicode.replace(unichr(223),'ss')+'^'+gf in w2v_model_gf:
return lex_unicode.replace(unichr(223),'ss')+'^'+gf
return lex_unicode+'^'+gf
if res=='w2v_model': #need unicode
try:
lex_unicode=lex.decode('utf8')
except:
lex_unicode=lex
if lex_unicode in w2v_model:
return lex_unicode
else:
if unichr(223) in lex_unicode and lex_unicode.replace(unichr(223),'ss') in w2v_model:
return lex_unicode.replace(unichr(223),'ss')
#only split if it is not an NE
if not (m[4]=='NE' and lex_unicode==m[-1]):
lex_split=compsplit.split_compound(lex_unicode)
if lex_split[0][0]>0:
lex_unicode=lex_split[0][2]
if lex_unicode in w2v_model:
return lex_unicode
if unichr(223) in lex_unicode and lex_unicode.replace(unichr(223),'ss') in w2v_model:
return lex_unicode.replace(unichr(223),'ss')
return lex_unicode
if res=='graph': #need utf8
try:
lex=lex.encode('utf8')
except:
pass
if lex in G:
return lex
else:
try:
lex=lex.decode('utf8')
if unichr(223) in lex and lex.replace(unichr(223),'ss') in G:
return lex.replace(unichr(223),'ss').encode('utf8')
if not (m[4]=='NE' and lex==m[-1].decode('utf8')):
lex_split=compsplit.split_compound(lex)
if lex_split[0][0]>0:
lex=lex_split[0][2].encode('utf8')
except: pass
try:
return lex.encode('utf8')
except:
return lex
def get_lex_token(lex,res,gf=None):
"""
Try to map a noun to an instance in either the graph, word2vec
For word2_vec return unicode, for graph utf8
res: 'graph', 'w2v_model_gf'
"""
if '-' in lex: #take hyphenated head
lex=lex.split('-')[-1]
if '|' in lex: #ambiguous lemma, take the one that is in the w2c model
lex=lex.split('|')[0] #crudely take the first lemma
if ' und ' in lex:
lex=lex.split(' und ')[0] #conjunction head: 'man and wife' -> 'man'
try:
if not lex.decode('utf8').isupper(): #Don't change DDR to Ddr
try: lex=lex.decode('utf8').title() #PolitikerIn -> Politikerin
except: pass
except: pass
if res=='w2v_model_gf':
try:
lex_unicode=lex.decode('utf8')
except:
lex_unicode=lex
if lex_unicode+'^'+gf in w2v_model_gf:
return lex_unicode+'^'+gf
else:
if unichr(223) in lex_unicode and lex_unicode.replace(unichr(223),'ss')+'^'+gf in w2v_model_gf:
return lex_unicode.replace(unichr(223),'ss')+'^'+gf
if gf=='root' and lex_unicode+'^subj' in w2v_model_gf:
return lex_unicode+'^subj'
lex_split=compsplit.split_compound(lex_unicode)
if lex_split[0][0]>-0.5:
lex_unicode=lex_split[0][2]
if lex_unicode+'^'+gf in w2v_model_gf:
return lex_unicode+'^'+gf
if unichr(223) in lex_unicode and lex_unicode.replace(unichr(223),'ss')+'^'+gf in w2v_model_gf:
return lex_unicode.replace(unichr(223),'ss')+'^'+gf
return lex_unicode+'^'+gf
if res=='w2v_model': #need unicode
try:
lex_unicode=lex.decode('utf8')
except:
lex_unicode=lex
if lex_unicode in w2v_model:
return lex_unicode
else:
if unichr(223) in lex_unicode and lex_unicode.replace(unichr(223),'ss') in w2v_model:
return lex_unicode.replace(unichr(223),'ss')
lex_split=compsplit.split_compound(lex_unicode)
if lex_split[0][0]>0:
lex_unicode=lex_split[0][2]
if lex_unicode in w2v_model:
return lex_unicode
if unichr(223) in lex_unicode and lex_unicode.replace(unichr(223),'ss') in w2v_model:
return lex_unicode.replace(unichr(223),'ss')
return lex_unicode
if res=='graph':
try:
lex=lex.encode('utf8')
except:
pass
if lex in G:
return lex
else:
try:
lex=lex.decode('utf8')
if unichr(223) in lex and lex.replace(unichr(223),'ss') in G:
return lex.replace(unichr(223),'ss').encode('utf8')
lex_split=compsplit.split_compound(lex)
if lex_split[0][0]>0:
lex=lex_split[0][2].encode('utf8')
except: pass
try:
return lex.encode('utf8')
except:
return lex
# ============================================= #
''' ANTECEDENT SELECTION '''
def get_best(ante_cands,ante_cands_csets,mable,docid):
''' Antecedent selection: return best of the candidates. '''
ante=[]
all_antes=ante_cands+ante_cands_csets
if all_antes==[]:
return ante
all_antes.sort(reverse=True)
ante_cands.sort(reverse=True)
ante_cands_csets.sort(reverse=True)
if mode=='train':
if classifier=='mle':
if not mable[4] in raw_counts:
raw_counts[mable[4]]={}
pronouns_counts[mable[4]]+=1
ante_counts[mable[4]]+=len(all_antes)
if classifier=='thebeast':
f=open(train_file,'a') #accumualte training cases
if classifier=='wapiti':
wapiti_cmd=''
ante=get_true_ante(mable,ante_cands,ante_cands_csets)
if ante==[]: #don't learn on cases where there is no true ante
return ante
if mode=='test':
if len(all_antes)==1:
single_ante_counts[mable[4]].append(1)
return all_antes[0]
#random baseline
#return all_antes[random.randint(0,len(all_antes)-1)]
#most recent baseline
#return all_antes[0]
#most recent subject baseline
#try: return next(m for m in all_antes if m[8]=='SUBJ')
#except StopIteration: return all_antes[0]
#upper bound
#true_ante=get_true_ante(mable,ante_cands,ante_cands_csets)
#if not true_ante==[]: return true_ante
if classifier=='mle':
weighted_antes=[]
avg_ante_counts[mable[4]].append(len(all_antes))
if not mable[4] in raw_counts_twin_features:
raw_counts_twin_features[mable[4]]={}
if classifier=='thebeast':
f=open('mln/test.atoms','w') #single test case
if classifier=='wapiti':
wapiti_cmd=''
wapiti_ante_weights=[]
if classifier=='thebeast': #write the features for thebeast
f.write('>>\n')
f.write('>docid\n'+re.search('\d+',docid).group()+'\n\n')
if mode=='train': #add the true antecedent
f.write('>coref\n')
f.write(str(mable[0])+' '+str(ante[0])+'\n\n')
f.write('>anaphor\n'+str(mable[0])+'\n\n')
if mable[4]=='PPOSAT':
if (mable[1],mable[2]) in pposat_heads:
pposat_head=pposat_heads[mable[1],mable[2]]
f.write('>pposat_head_gf\n')
f.write(str(mable[0])+' "'+pposat_head[7].upper()+'"\n\n')
f.write('>candidate_index\n')
for m in all_antes:
f.write(str(m[0])+' '+str(all_antes.index(m))+'\n')
f.write('\n>ante_cand_wl\n')
for m in ante_cands:
f.write(str(m[0])+'\n')
f.write('\n>ante_cand_cset\n')
for m in ante_cands_csets:
f.write(str(m[0])+'\n')
f.write('\n>ante_cand\n')
for m in all_antes:
f.write(str(m[0])+'\n')
f.write('\n>ante_type\n')
for m in ante_cands:
f.write(str(m[0])+' "New"\n')
for m in ante_cands_csets:
f.write(str(m[0])+' "Old"\n')
f.write('\n>has_genus\n')
for m in all_antes:
f.write(str(m[0])+' "'+m[6]+'"\n')
f.write(str(mable[0])+' "'+mable[6]+'"\n\n')
f.write('>has_num\n')
for m in all_antes:
f.write(str(m[0])+' "'+m[7]+'"\n')
f.write(str(mable[0])+' "'+mable[7]+'"\n\n')
f.write('>has_anim\n')
for m in all_antes:
f.write(str(m[0])+' "'+m[9]+'"\n')
f.write(str(mable[0])+' "'+mable[9]+'"\n\n')
f.write('>has_pos\n')
for m in all_antes:
f.write(str(m[0])+' "'+m[4]+'"\n')
f.write(str(mable[0])+' "'+mable[4]+'"\n\n')
f.write('>has_gf\n')
for m in all_antes:
f.write(str(m[0])+' "'+m[8]+'"\n')
f.write(str(mable[0])+' "'+mable[8]+'"\n\n')
f.write('>has_ne_type\n')
for m in all_antes:
if not m[12]=='*':
f.write(str(m[0])+' '+m[12]+'\n')
f.write('\n>has_connector\n')
for m in all_antes:
if m[-2]=='conn':
f.write(str(m[0])+'\n')
if mable[-2]=='conn':
f.write(str(mable[0])+'\n')
f.write('\n>in_sentence\n')
for m in all_antes:
f.write(str(m[0])+' '+str(m[1])+'\n')
f.write(str(mable[0])+' '+str(mable[1])+'\n\n')
f.write('\n>parent_id\n')
for m in all_antes:
f.write(str(m[0])+' '+str(m[10])+'\n')
f.write(str(mable[0])+' '+str(mable[10])+'\n\n')
f.write('\n')
f.close()
if mode=='test':
thebeast.stdin.write('load corpus from "mln/test.atoms";test to "mln/thebeast.res";\n')
outs=[]
while True:
out = thebeast.stdout.readline()
outs.append(out)
if out.startswith('End:coref'):
break
res_thebeast=open('mln/thebeast.res').read()
try:
ante=re.search('>coref\n\d+.*?(\d+)',res_thebeast).group(1)
ante=next(a for a in all_antes if a[0]==int(ante))
except:
pass
if classifier=='mle':
ante_features={}
for a in all_antes:
features={}
# ================================================================ #
''' GET FEATURES '''
"""
''' BASELINE FEATURES '''
# sent. distance
features['sent_dist'] = mable[1]-a[1]
# markable distance
features['mable_dist_all'] = mable[0]-a[0]
# gramm. function of ante
features['gf_ante'] = a[8]
# gf parallel
features['gf_parallel']='parallel' if mable[8] == a[8] else 'not_parallel'
# pos ante
features['pos_ante'] = a[4]
# det
#'''
if a[4] == 'NN':
if (a[1],a[2]) in determiners:
det=determiners[a[1],a[2]]
if det.startswith('d'): features['def']='def'
elif det.startswith('e'): features['def']='indef'
else: features['def']='unk'
else: features['def']='indef'
else: features['def'] = 'na'
#'''
"""
# ================================================================ #
''' EXTENDED FEATURES '''
#'''
""" DISTANCE """
#sentence distance
if mable[4] not in ['PRELS','PRELAT']:
sent_type=mable[13] #conn or noconn, also the feature name
features[sent_type]=mable[1]-a[1]
#markable distance in the same sentence
if mable[1]==a[1]: #same sentence
features['mable_dist']=mable[0]-a[0]
#candidate index
cand_index=all_antes.index(a)
features['cand_index']=cand_index
""" SYNTAX """
#grammatical function of the antecedent
features['gf_ante']=a[8]
#gf_seq: sent. dist., gf ante, gf pronoun, PoS ante
gf_seq=str(mable[1]-a[1])+'_'+a[8]+'_'+mable[8]+'_'+a[4]
features['gf_seq']=gf_seq
#PPOSAT specific features:
if mable[4]=='PPOSAT':
same_head='not_same_head' # PPOSAT is governed by same verb as ante
if a[1]==mable[1] and a[10]==mable[10]:
same_head='same_head'
if (mable[1],mable[2]) in pposat_heads:
pposat_head=pposat_heads[mable[1],mable[2]]
features['head_gf_seq']='_'.join([str(mable[1]-a[1]),a[8],pposat_head[7].upper(),a[4]])
if same_head=='same_head':
features['same_head_gf_seq']='_'.join([a[8],pposat_head[7].upper(),a[4]])
#(sub)clause type, i.e. gf of verb governing the candidate
if (a[1],a[10]) in verbs:
features['subclause']=verbs[a[1],a[10]]['verb'][7]
else:
features['subclause']='*'
#(sub)clause type seq
sent_dist='0' if mable[1]==a[1] else '1'
if (mable[1],mable[10]) in verbs:
features['subclause_seq']=sent_dist+'_'+features['subclause']+'_'+verbs[mable[1],mable[10]]['verb'][7]
else:
features['subclause_seq']=sent_dist+'_'+features['subclause']+'_*'
""" ANTE PROPERTIES """
#animacy of the antecedent; condition on gen+num also? mln has gen atleast
features['anim_num_gen']=a[9]+'_'+a[6]+'_'+a[7]
#ne_type fo the antecedent
if not a[12]=='-': features['ne_type']=a[12]
#features['ne_type']=a[12]
#gender of ante
features['gen']=a[6]
#number of ante
features['num']=a[7]
#preposition
if a[8]=='PN' and (a[1],a[2]) in prepositions: features['pp_ante']=prepositions[a[1],a[2]]
""" DISCOURSE """
#discourse status: old/new
if a in ante_cands_csets: discourse_status='old'
else: discourse_status='new'
features['discourse_status']=discourse_status
# cset candidate: how old is the entity, i.e. in which sentence was it introduced
if a in ante_cands_csets:
ante_cset=next(c for c in csets if a in c)
features['entity_introduction_sentence']=ante_cset[0][1]-mables[0][1]
#'''
ante_features[a[0]]=features
if mode=='test':
weight={}
pos=mable[4]
#add feature counts to pos/neg raw_counts depending whether a is the true_ante or not
#for i in range(1,len(features)+1): #all feature combinations
#for i in range(1,4): #only unary features
for i in range(1,2): #only unary features
for c in combinations(features,i):
combined_feature_name='/'.join([x for x in c])
combined_feature_values='/'.join([str(features[x]) for x in c])
if mode=='train':
#dict housekeeping
if not combined_feature_name in raw_counts[pos]:
raw_counts[pos][combined_feature_name]={}
if not combined_feature_values in raw_counts[pos][combined_feature_name]:
raw_counts[pos][combined_feature_name][combined_feature_values]={'pos':0,'neg':0}
#count incrementation
if a!=ante:
raw_counts[pos][combined_feature_name][combined_feature_values]['neg']+=1
else:
raw_counts[pos][combined_feature_name][combined_feature_values]['pos']+=1
if mode=='test':
if combined_feature_name in weights_global[pos]:
if combined_feature_values in weights_global[pos][combined_feature_name]:
weight[combined_feature_name]=weights_global[pos][combined_feature_name][combined_feature_values]
#weight.append(weights_global[pos][combined_feature_name][combined_feature_values])
if mode=='test':
weighted_antes.append([reduce(operator.mul,weight.values()),a,weight]) #product of the weights
if mode=='test':
if not weighted_antes==[]:
weighted_antes.sort(reverse=True)
ante=weighted_antes[0][1]
if verb_postfilter_context_graph:
if mable[4] in ['PPER','PRELS','PDS'] and mable[8] in ['SUBJ','OBJA','OBJD','OBJP'] and not mable[11]=='*' and len(weighted_antes)>1:
global verb_postfilter_cnt
verb_postfilter_cnt+=1
pper_verb_utf8=mable[11].replace('#','')
if pper_verb_utf8 in G:
gf=mable[8].lower()
add_args={}
# Check for additional verb arguments, i.e. construct context
if (mable[1],mable[10]) in verbs:
for v_gf,varg in verbs[mable[1],mable[10]].items():
if v_gf in ['verb','subcat']: continue
if v_gf in ['subj','obja','objd','objp']:
if varg[4]=='NN':
#if v_gf=='objp': v_gf='pn' # We don't have PNs in the graph, useless
# Only selected args; well we don't have anything else, really, so the filter doesn't do anything here
#if v_gf in ['pn', 'subj', 'obja', 'objd']:
if '-' in varg[2]: varg[2]=re.sub('.*-','',varg[2])
if varg[2] in G: add_args[v_gf]=varg[2]
else:
lex_varg=get_lex_token(varg[2],'graph')
if '-' in lex_varg: lex_varg=re.sub('.*-','',lex_varg)
if lex_varg in G: add_args[v_gf]=lex_varg
elif varg[4] in ['PPER','PRELS'] and int(varg[0])<mable[2]: # Get nominal ante of pronoun args
try:
closest_mable=next(m for m in mables if m[1]==mable[1] and m[2]==int(varg[0]))
if closest_mable!=mable:
lex_varg=get_lex(closest_mable,'graph')
if '-' in lex_varg: lex_varg=re.sub('.*-','',lex_varg)
if not lex_varg.startswith(varg[2].title()) and lex_varg in G: add_args[v_gf]=lex_varg
except StopIteration: pass
# Determine nbest args of pper verb
# TODO: use count to sort instead of npmi?
pper_verb_cooc1=graph.first_order_coocurrences(G,pper_verb_utf8,gf)
pper_verb_cooc1_lemmas=[n[1] for n in pper_verb_cooc1]
if len(pper_verb_cooc1)>=100: nbest=10
else: nbest=len(pper_verb_cooc1)/10
if nbest<3: nbest=3 # at least three
ante_features={}
reranked_antes=[]
for ax in weighted_antes[:2]:
a=ax[1]
features={}
lex_utf8=a[-1] if a[-1] in G else get_lex(a,'graph')
if '-' in lex_utf8: lex_utf8=re.sub('.*-','',lex_utf8)
if lex_utf8 in G:
verb_features={}
# 1st order co-occurrence
verb_features['cooc1']=graph.preference(G,lex_utf8,pper_verb_utf8,gf)
# Similar arg cooc1
"""
di=graph.preference(G,lex_utf8,pper_verb_utf8,gf)
if di>0: verb_features['cooc1']=di
else:
sibling=graph.similar_arg(G,lex_utf8,pper_verb_utf8,gf)
cooc1_sibling=graph.preference(G,sibling[1],pper_verb_utf8,gf)
verb_features['cooc1']=cooc1_sibling*sibling[0]
"""
#"""
# Cooc1 of pper_verb of pper_verb arg most similar to ante_cand; unfortunately a speed bottleneck
sibling=graph.similar_arg(G,lex_utf8,pper_verb_utf8,gf,weight='scount')
cooc1_sibling=graph.preference(G,sibling[1],pper_verb_utf8,gf)
# Degrade preference of similar arg by similarity to the similar arg
verb_features['cooc1_similar']=cooc1_sibling*sibling[0]
#"""
"""
#nmf scaled
#maxx=max(subj_nmf[n_index_subj['Hund']].toarray().flatten())
#nmf_pref=subj_nmf[n_index_subj['Hund'],v_index_subj['bellen']]
#nmf_pref=nmf_pref/maxx
"""
# Similarity of ante_cand to topn cooc1 args of pper_verb_utf8
#"""
#cooc1_sim=[ graph.similarity(G,lex_utf8,n,gf,weight='scount') for n in pper_verb_cooc1_lemmas[:nbest] ]
#cooc1_sim=np.mean(cooc1_sim) if not cooc1_sim==[] else 0
#verb_features['cooc1_sim']=cooc1_sim
verb_features['cooc1_sim']=graph.similarity_one_vs_all(G,lex_utf8,pper_verb_cooc1_lemmas[:nbest],gf,gf,weight='scount')
#"""
"""
# Similarity of ante_verb and pper_verb
# Only in cases where both candidates have relevant gf, i.e. not GMOD or PN
try:
next(m for m in weighted_antes[:2] if not m[1][8] in ['SUBJ','OBJA','OBJD','OBJP']) # Relevant GFs
except:
verb_sim=graph.weighted_path(G,pper_verb_utf8,a[11],gf,a[8].lower(),weight='scount') if a[8] in ['SUBJ','OBJA','OBJD','OBJP'] and a[11] in G else 0
verb_features['verb_sim']=verb_sim
"""
verb_features['verb_sim']=graph.weighted_path(G,pper_verb_utf8,a[11],gf,a[8].lower(),weight='scount') if a[8] in ['SUBJ','OBJA','OBJD','OBJP'] and a[11] in G else 0
#"""
# Similarity of ante to additional pper_verb args, i.e. context
add_args_sim=[ graph.weighted_path(G,lex_utf8,v_arg,gf,v_gf,weight='scount') for v_gf,v_arg in add_args.items() ]
# Take the mean instead of sum to not overweigh add_args_sim feature in the sum below
add_args_sim=np.mean(add_args_sim) if not add_args_sim==[] else 0
verb_features['add_args_sim']=add_args_sim
#"""
"""
# Similarity of nbest args of ante_verb to nbest args of pper_verb
# cooc1 of nbest ante_verb args with pper_verb; only where cooc1>0
verb_arg_sim,sim_verb_args_pper_verb=0,0
#TODO Problem here: only similarity of subj, obja, objd antes is considered, and it's always positive.
#if we sum up, these candidates will always benefit from that.
#That is, e.g. gmod and pn candidates are always discouraged.. Then again: how often are they among the top 2 candidates anyway?
if a[8] in ['SUBJ','OBJA','OBJD','OBJP'] and a[11] in G and not pper_verb_cooc1_lemmas==[]:
ante_verb_cooc1=graph.first_order_coocurrences(G,a[11],a[8].lower())
if not ante_verb_cooc1==[]:
if len(ante_verb_cooc1)>=100: nbest=10
else: nbest=len(ante_verb_cooc1)/10
if nbest<3: nbest=3 # at least three
ante_verb_cooc1_lemmas=[n[1] for n in ante_verb_cooc1[:nbest]]
verb_arg_sim=graph.n_similarity(G,ante_verb_cooc1_lemmas, pper_verb_cooc1_lemmas[:nbest],gf)
# cooc1 of nbest ante_verb args with pper_verb; only where cooc1>0
sim_verb_args_pper_verb=[]
for n in ante_verb_cooc1_lemmas:
di=graph.scaled_preference(G,n,pper_verb_utf8,gf)
if not di==0: sim_verb_args_pper_verb.append(di)
sim_verb_args_pper_verb=np.mean(sim_verb_args_pper_verb) if not sim_verb_args_pper_verb==[] else 0
verb_features['sim_verb_args_pper_verb']=sim_verb_args_pper_verb
verb_features['verb_arg_sim']=verb_arg_sim
"""
# Mean of all weights
sim=np.mean(verb_features.values())
ante_features[a[0]]=verb_features
reranked_antes.append([sim,a])
if len(reranked_antes)==2:
reranked_antes.sort(reverse=True)
true_ante=get_true_ante(mable,ante_cands,ante_cands_csets)
if not true_ante==[] and reranked_antes[0][0]>reranked_antes[1][0]:
verb_ante=reranked_antes[0][1]
"""
# Feature vector for Weka and the lot
runner_up=reranked_antes[1][1]
inst=''
feats=['cooc1', 'cooc1_sim', 'add_args_sim', 'sim_verb_args_pper_verb', 'verb_arg_sim', 'verb_sim']
for f in feats:
inst+="%.2f" % ante_features[verb_ante[0]][f] #round to 2 decimals
inst+=' '
for f in feats:
inst+="%.2f" % ante_features[runner_up[0]][f]
inst+=' '
for f in feats:
inst+="%.2f" % (ante_features[verb_ante[0]][f]-ante_features[runner_up[0]][f])
inst+=' '
inst+='pos' if verb_ante==true_ante else 'neg'
"""
# Trace
#"""
if mable[4]=='PPER':
print '\n\n',mable
print 'true_ante:\t',true_ante
print 'sel_ante:\t',ante
print 'verb_ante:\t',verb_ante
print add_args
print pper_verb_cooc1_lemmas[:nbest]
for x in reranked_antes:print x
for x,y in ante_features.items(): print x,y
print ''
pdb.set_trace()
#"""
# Evaluate
if ante==true_ante==verb_ante:
accuracy[pos][mable[-1]]['both correct']+=1
elif ante==true_ante:
accuracy[pos][mable[-1]]['baseline correct']+=1
elif verb_ante==true_ante:
accuracy[pos][mable[-1]]['verb_sel correct']+=1
else:
accuracy[pos][mable[-1]]['both wrong']+=1
if verb_postfilter_context_w2v:
if mable[4] in ['PPER','PRELS','PDS'] and mable[8] in ['SUBJ','OBJA','OBJD','OBJP'] and not mable[11]=='*' and len(weighted_antes)>1:
#global verb_postfilter_cnt
#verb_postfilter_cnt+=1
pper_verb_unicode=mable[11].replace('#','').decode('utf8')+'^V'
if pper_verb_unicode in w2v_model_gf:
gf=mable[8].lower()
if gf=='objp': gf='pn'
context=[] #build the pronoun's context
if (mable[1],mable[10]) in verbs: #check for additional verb arguments
for v_gf,varg in verbs[mable[1],mable[10]].items():
if v_gf in ['verb','subcat']: continue
#if v_gf in ['pn', 'subj', 'obja', 'objd']: #only selected args
if varg[4]=='NN':
if v_gf=='objp': v_gf='pn'
if varg[2]+'^'+v_gf in w2v_model_gf: context.append(varg[2]+'^'+v_gf)
else:
lex_varg=get_lex_token(varg[2],'w2v_model_gf',nominal_mods,csets,gf=v_gf)
if lex_varg in w2v_model_gf: context.append(lex_varg)
elif varg[4] in ['PPER','PRELS'] and int(varg[0])<mable[2]: #get nominal ante of pronoun args
try:
closest_mable=next(m for m in mables if m[1]==mable[1] and m[2]==int(varg[0]))
if closest_mable!=mable:
lex_varg=get_lex(closest_mable,'w2v_model_gf',nominal_mods,csets,varg[7])
if not lex_varg.startswith(varg[2].title().decode('utf8')) and lex_varg in w2v_model_gf: context.append(lex_varg)
except StopIteration: pass
context.append(pper_verb_unicode)
if not context==[]:
#if len(context)>1:
ante_features={}
reranked_antes=[]
for ax in weighted_antes[:2]:
a=ax[1]
features={}
if a[-1].decode('utf8')+'^'+gf in w2v_model_gf: lex_unicode=a[-1].decode('utf8')+'^'+gf
else: lex_unicode=get_lex(a,'w2v_model_gf',gf.lower())
if lex_unicode in w2v_model_gf:
sim=w2v_model_gf.n_similarity(context,[lex_unicode]) #average similarity to all args
#sim=w2v_model_gf.similarity(pper_verb_unicode,lex_unicode) #similarity to verb
#multiply vectors of context args, cosine to product af context: much worse
#context_prod=reduce(operator.mul,[w2v_model_gf[carg] for carg in context])
#sim=1 - cosine(w2v_model_gf[lex_unicode],context_prod)
#sim=w2v_model_gf.similarity(lex_unicode,pper_verb_unicode) # only similarity to the verb
reranked_antes.append([sim,a])
if len(reranked_antes)==2:
reranked_antes.sort(reverse=True)
true_ante=get_true_ante(mable,ante_cands,ante_cands_csets)
if not true_ante==[] and reranked_antes[0][0]>reranked_antes[1][0]:
verb_ante=reranked_antes[0][1]
if ante==true_ante==verb_ante:
accuracy[pos][mable[-1]]['both correct']+=1
elif ante==true_ante:
accuracy[pos][mable[-1]]['baseline correct']+=1
elif verb_ante==true_ante:
accuracy[pos][mable[-1]]['verb_sel correct']+=1
"""
print '\n\n',mable
print 'true_ante:\t',true_ante
print 'sel_ante:\t',ante
print context
for x in reranked_antes:print x
print ''
pdb.set_trace()
"""
else:
accuracy[pos][mable[-1]]['both wrong']+=1
if not verb_postfilter=='off':
#TODO don't restrict gf -> w2v and new graph with pn
if mable[4]=='PPER' and mable[8] in ['SUBJ','OBJA','OBJD'] and not mable[11]=='*' and len(weighted_antes)>1:
verb_postfilter_cnt+=1
pper_verb_utf8=mable[11].replace('#','')
pper_verb_unicode=pper_verb_utf8.decode('utf8')+'^V'
gf=mable[8].lower()
context=[]
add_args_pper_verb={}
if (mable[1],mable[10]) in verbs: #check for additional verb arguments
for v_gf,varg in verbs[mable[1],mable[10]].items():
if v_gf in ['verb','subcat']: continue
if varg[4]=='NN':
if varg[2] in G: add_args_pper_verb[v_gf]=varg[2]
else:
lex_varg=get_lex_token(varg[2],res='graph')
if lex_varg in G:
add_args_pper_verb[v_gf]=lex_varg