-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.py
2036 lines (1737 loc) · 99.7 KB
/
main.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
from collections import OrderedDict
import re
import numpy as np
from scipy import optimize
import pickle
import scipy.special as special
import matplotlib.pyplot as plt
from matplotlib import colors
import seaborn as sns
import pandas as pd
import time
import os
class ClassStatistics:
"""
define classes of features and its statistics (e.g. counts)
"""
def __init__(self, file_path):
"""
:param file_path: full path of the train file to read
"""
self.file_path = file_path
self.Y = set() # all the different tags we saw in training
# Init all features classes dictionaries
self.class100_dict = OrderedDict() # {(100, word, tag): # times seen}
self.class101_dict = OrderedDict() # {(101, word[- length:], tag): # times seen}
self.class102_dict = OrderedDict() # {(102, word[:length], tag): # times seen}
self.class103_dict = OrderedDict() # {(103, tag-2, tag-1, tag): # times seen}
self.class104_dict = OrderedDict() # {(104, tag-1, tag): # times seen}
self.class105_dict = OrderedDict() # {(105, tag): # times seen}
# Additional
self.class106_dict = OrderedDict() # {(106, word-1, tag): # times seen}
self.class107_dict = OrderedDict() # {(107, word+1, tag): # times seen}
# Numbers
self.class108_dict = OrderedDict() # {(108.x, tag): # times seen}
# Capital letters
self.class109_dict = OrderedDict() # {(109.x, prev_tag, cur_tag): # times seen}
# Additional patterns
self.class110_dict = OrderedDict() # {(110.x, tag): # times seen}
self.class111_dict = OrderedDict() # {(111.x, tag): # times seen}
def set_class100_dict(self):
"""
Create counts dict for class 100 features
"""
with open(self.file_path) as f:
for line in f:
splited_words = re.split(' |[\n]', line)
if splited_words[-1] == "":
del splited_words[-1] # remove \n
for word_idx in range(len(splited_words)):
cur_word, cur_tag = splited_words[word_idx].split('_')
self.Y.add(cur_tag)
if (100, cur_word, cur_tag) not in self.class100_dict:
self.class100_dict[(100, cur_word, cur_tag)] = 1
else:
self.class100_dict[(100, cur_word, cur_tag)] += 1
self.Y = sorted(list(self.Y))
def set_class101_dict(self):
"""
Create counts dict for class 101 features
"""
with open(self.file_path) as f:
for line in f:
splited_words = re.split(' |[\n]', line)
if splited_words[-1] == "":
del splited_words[-1] # remove \n
for word_idx in range(len(splited_words)):
cur_word, cur_tag = splited_words[word_idx].split('_')
if not re.match('^[0-9]+([-,.:]?[0-9]?)*$', cur_word) and not re.match('^[0-9]+\\\\/[0-9]+$',
cur_word):
n = min(len(cur_word) - 1, 7)
for suffix_length in range(1, n + 1):
if not re.match('^[0-9]+$', cur_word[-suffix_length:]):
if (101, cur_word[-suffix_length:], cur_tag) not in self.class101_dict:
self.class101_dict[(101, cur_word[-suffix_length:], cur_tag)] = 1
else:
self.class101_dict[(101, cur_word[-suffix_length:], cur_tag)] += 1
def set_class102_dict(self):
"""
Create counts dict for class 102 features
"""
with open(self.file_path) as f:
for line in f:
splited_words = re.split(' |[\n]', line)
if splited_words[-1] == "":
del splited_words[-1] # remove \n
for word_idx in range(len(splited_words)):
cur_word, cur_tag = splited_words[word_idx].split('_')
if not re.match('^[0-9]+([-,.:]*[0-9]*)*$', cur_word) and not re.match('^[0-9]+\\\\/[0-9]+$',
cur_word):
n = min(len(cur_word) - 1, 7)
for prefix_length in range(1, n + 1):
if not re.match('^[0-9]+$', cur_word[:prefix_length]):
if (102, cur_word[:prefix_length], cur_tag) not in self.class102_dict:
self.class102_dict[(102, cur_word[:prefix_length], cur_tag)] = 1
else:
self.class102_dict[(102, cur_word[:prefix_length], cur_tag)] += 1
def set_class103_dict(self):
"""
Create counts dict for class 103 features
"""
with open(self.file_path) as f:
for line in f:
splited_words = re.split(' |[\n]', line)
if splited_words[-1] == "":
del splited_words[-1] # remove \n
for word_idx in range(len(splited_words)):
cur_tag = splited_words[word_idx].split('_')[1]
prev_tag = splited_words[word_idx - 1].split('_')[1] if word_idx > 0 else ''
prev_prev_tag = splited_words[word_idx - 2].split('_')[1] if word_idx - 1 > 0 else ''
if (103, prev_prev_tag, prev_tag, cur_tag) not in self.class103_dict:
self.class103_dict[(103, prev_prev_tag, prev_tag, cur_tag)] = 1
else:
self.class103_dict[(103, prev_prev_tag, prev_tag, cur_tag)] += 1
def set_class104_dict(self):
"""
Create counts dict for class 104 features
"""
with open(self.file_path) as f:
for line in f:
splited_words = re.split(' |[\n]', line)
if splited_words[-1] == "":
del splited_words[-1] # remove \n
for word_idx in range(len(splited_words)):
cur_tag = splited_words[word_idx].split('_')[1]
prev_tag = splited_words[word_idx - 1].split('_')[1] if word_idx > 0 else ''
if (104, prev_tag, cur_tag) not in self.class104_dict:
self.class104_dict[(104, prev_tag, cur_tag)] = 1
else:
self.class104_dict[(104, prev_tag, cur_tag)] += 1
def set_class105_dict(self):
"""
Create counts dict for class 105 features
"""
with open(self.file_path) as f:
for line in f:
splited_words = re.split(' |[\n]', line)
if splited_words[-1] == "":
del splited_words[-1] # remove \n
for word_idx in range(len(splited_words)):
cur_tag = splited_words[word_idx].split('_')[1]
if (105, cur_tag) not in self.class105_dict:
self.class105_dict[(105, cur_tag)] = 1
else:
self.class105_dict[(105, cur_tag)] += 1
def set_class106_dict(self):
"""
Create counts dict for class 106 features
"""
with open(self.file_path) as f:
for line in f:
splited_words = re.split(' |[\n]', line)
if splited_words[-1] == "":
del splited_words[-1] # remove \n
for word_idx in range(len(splited_words)):
cur_tag = splited_words[word_idx].split('_')[1]
prev_word = splited_words[word_idx - 1].split('_')[0] if word_idx != 0 else '*'
if (106, prev_word, cur_tag) not in self.class106_dict:
self.class106_dict[(106, prev_word, cur_tag)] = 1
else:
self.class106_dict[(106, prev_word, cur_tag)] += 1
def set_class107_dict(self):
"""
Create counts dict for class 107 features
"""
with open(self.file_path) as f:
for line in f:
splited_words = re.split(' |[\n]', line)
if splited_words[-1] == "":
del splited_words[-1] # remove \n
for word_idx in range(len(splited_words)):
cur_tag = splited_words[word_idx].split('_')[1]
next_word = splited_words[word_idx + 1].split('_')[0] if \
word_idx != len(splited_words) - 1 else 'STOP'
if (107, next_word, cur_tag) not in self.class107_dict:
self.class107_dict[(107, next_word, cur_tag)] = 1
else:
self.class107_dict[(107, next_word, cur_tag)] += 1
def set_class108_dict(self):
"""
Create counts dict for class 108 features - Numbers
Description of the sub-classes in our numbers class:
define number = [numbers][\/]?[numbers]
1. if word is only number or [-.:,\/%] chars
2. elif word is [letters][-.][number]([-.]*[letters]+)+
by division to the final three chars is letters or not
3. elif word is [letters][-.][number]
by division based on first char
4. elif word is [number][-.][letters]([-.]*[number]+)+
5. elif word is [number][-.][letters]
6. if word is year pattern --> e.g. 1980s , mid-1980, ‘80s
7. any other pattern with digits
by division to the final three chars is letters or not
and amount of '-' chars
"""
with open(self.file_path) as f:
for line in f:
splited_words = re.split(' |[\n]', line)
if splited_words[-1] == "":
del splited_words[-1] # remove \n
for word_idx in range(len(splited_words)):
cur_tag = splited_words[word_idx].split('_')[1]
cur_word = splited_words[word_idx].split('_')[0]
hyphen_count = cur_word.count('-')
if re.search(r'\d', cur_word):
splited_cur_word = re.split('-', cur_word)
no_category = True
if re_match_words('^[0-9]+$', re.split('[-]|[,]|[.]|[:]|[\\\\]|[/]|[%]', cur_word)):
if (108.1, cur_tag) not in self.class108_dict:
self.class108_dict[(108.1, cur_tag)] = 1
else:
self.class108_dict[(108.1, cur_tag)] += 1
no_category = False
elif hyphen_count > 1 and re_match_letters_numbers(['^[A-Za-z]+$', '^[0-9]+$'],
splited_cur_word) \
and not cur_word.startswith('mid'):
if re.match('^[A-Za-z]+$', splited_cur_word[-1]):
if (108.21, cur_tag) not in self.class108_dict:
self.class108_dict[(108.21, cur_tag)] = 1
else:
self.class108_dict[(108.21, cur_tag)] += 1
else:
if (108.22, cur_tag) not in self.class108_dict:
self.class108_dict[(108.22, cur_tag)] = 1
else:
self.class108_dict[(108.22, cur_tag)] += 1
no_category = False
elif hyphen_count == 1 and re_match_letters_numbers(['^[A-Za-z]+$', '^[0-9]+$'],
splited_cur_word):
if re.match('^[a-z]$', cur_word[0]):
if (108.31, cur_tag) not in self.class108_dict:
self.class108_dict[(108.31, cur_tag)] = 1
else:
self.class108_dict[(108.31, cur_tag)] += 1
else:
if (108.32, cur_tag) not in self.class108_dict:
self.class108_dict[(108.32, cur_tag)] = 1
else:
self.class108_dict[(108.32, cur_tag)] += 1
no_category = False
elif hyphen_count > 1 and re_match_numbers_letters(['^[0-9]+$', '^[A-Za-z]+$'],
splited_cur_word):
if (108.4, cur_tag) not in self.class108_dict:
self.class108_dict[(108.4, cur_tag)] = 1
else:
self.class108_dict[(108.4, cur_tag)] += 1
no_category = False
elif hyphen_count == 1 and re_match_numbers_letters(['^[0-9]+$', '^[A-Za-z]+$'],
splited_cur_word):
if (108.5, cur_tag) not in self.class108_dict:
self.class108_dict[(108.5, cur_tag)] = 1
else:
self.class108_dict[(108.5, cur_tag)] += 1
no_category = False
if re.match('^([a-zA-Z]*(-)?[0-9][0-9][0-9][0-9](s?))$|^(\'[0-9][0-9]s)$', cur_word):
if (108.6, cur_tag) not in self.class108_dict:
self.class108_dict[(108.6, cur_tag)] = 1
else:
self.class108_dict[(108.6, cur_tag)] += 1
no_category = False
if no_category:
if re.match('^[A-Za-z]+$', splited_cur_word[-1]):
if (108.7, hyphen_count, cur_tag) not in self.class108_dict:
self.class108_dict[(108.7, hyphen_count, cur_tag)] = 1
else:
self.class108_dict[(108.7, hyphen_count, cur_tag)] += 1
else:
if (108.8, hyphen_count, cur_tag) not in self.class108_dict:
self.class108_dict[(108.8, hyphen_count, cur_tag)] = 1
else:
self.class108_dict[(108.8, hyphen_count, cur_tag)] += 1
def set_class109_dict(self):
"""
Create counts dict for class 109 features - Capital Letters
Description of the sub-classes for capital letters treatment:
1. if word is not the first, starts with capital and has [- .]+ and both next and previous words starts with capital
2. elif word is not the first, starts with capital and has [- .]+ and prev starts with capital
3. elif word is not the first, starts with capital and has [- .]+
4. elif word is not the first, starts with capital and both next and previous words starts with capital
5. elif word is the first, starts with capital and has [- .]+ and next and prev word starts with capital
6. elif word is the first, starts with capital and has [- .]+ and next word starts with capital
7. elif word is the first, starts with capital and has [- .]+
8. elif word is the first, starts with capital and next and prev word starts with capital
9. elif word is only capital and has more than one letter, next word also, and also prev word
11. elif word is only capital and has more than one letter, next word also
12. elif word is only capital and has more than one letter
13. if just has some capital somewhere, and count number of '-' chars
14. if word has capital after small letter
"""
with open(self.file_path) as f:
for line in f:
splited_words = re.split(' |[\n]', line)
if splited_words[-1] == "":
del splited_words[-1] # remove \n
for word_idx in range(len(splited_words)):
cur_tag = splited_words[word_idx].split('_')[1]
cur_word = splited_words[word_idx].split('_')[0]
prev_word = splited_words[word_idx - 1].split('_')[0] if word_idx > 0 else '*'
prev_tag = splited_words[word_idx - 1].split('_')[1] if word_idx > 0 else ''
next_word = splited_words[word_idx + 1].split('_')[0] if word_idx + 1 < len(
splited_words) - 1 else 'STOP'
hyphen_count = cur_word.count('-')
if word_idx > 0 and re.match('^[A-Z](.*?)[-.]+(.*?)', cur_word) and re.match('^[A-Z]', next_word) \
and re.match('^[A-Z]', prev_word):
if (109.1, prev_tag, cur_tag) not in self.class109_dict:
self.class109_dict[(109.1, prev_tag, cur_tag)] = 1
else:
self.class109_dict[(109.1, prev_tag, cur_tag)] += 1
elif word_idx > 0 and re.match('^[A-Z](.*?)[-.]+(.*?)', cur_word) and re.match('^[A-Z]', prev_word):
if (109.2, prev_tag, cur_tag) not in self.class109_dict:
self.class109_dict[(109.2, prev_tag, cur_tag)] = 1
else:
self.class109_dict[(109.2, prev_tag, cur_tag)] += 1
elif word_idx > 0 and re.match('^[A-Z](.*?)[-.]+(.*?)', cur_word):
if (109.3, prev_tag, cur_tag) not in self.class109_dict:
self.class109_dict[(109.3, prev_tag, cur_tag)] = 1
else:
self.class109_dict[(109.3, prev_tag, cur_tag)] += 1
elif word_idx > 0 and re.match('^[A-Z]', cur_word) and re.match('^[A-Z]', next_word) \
and re.match('^[A-Z]', prev_word):
if (109.4, prev_tag, cur_tag) not in self.class109_dict:
self.class109_dict[(109.4, prev_tag, cur_tag)] = 1
else:
self.class109_dict[(109.4, prev_tag, cur_tag)] += 1
elif word_idx == 0 or (word_idx > 0 and prev_word in ['``', '.']):
if re.match('^[A-Z](.*?)[-.]+(.*?)', cur_word) and re.match('^[A-Z]', next_word) \
and re.match('^[A-Z]', prev_word):
if (109.5, prev_tag, cur_tag) not in self.class109_dict:
self.class109_dict[(109.5, prev_tag, cur_tag)] = 1
else:
self.class109_dict[(109.5, prev_tag, cur_tag)] += 1
elif word_idx == 0 or (word_idx > 0 and prev_word in ['``', '.']):
if re.match('^[A-Z](.*?)[-.]+(.*?)', cur_word) and re.match('^[A-Z]', next_word):
if (109.6, prev_tag, cur_tag) not in self.class109_dict:
self.class109_dict[(109.6, prev_tag, cur_tag)] = 1
else:
self.class109_dict[(109.6, prev_tag, cur_tag)] += 1
elif word_idx == 0 or (word_idx > 0 and prev_word in ['``', '.']):
if re.match('^[A-Z](.*?)[-.]+(.*?)', cur_word):
if (109.7, prev_tag, cur_tag) not in self.class109_dict:
self.class109_dict[(109.7, prev_tag, cur_tag)] = 1
else:
self.class109_dict[(109.7, prev_tag, cur_tag)] += 1
elif word_idx == 0 or (word_idx > 0 and prev_word in ['``', '.']):
if re.match('^[A-Z]', cur_word) and re.match('^[A-Z]', next_word) \
and re.match('^[A-Z]', prev_word):
if (109.8, prev_tag, cur_tag) not in self.class109_dict:
self.class109_dict[(109.8, prev_tag, cur_tag)] = 1
else:
self.class109_dict[(109.8, prev_tag, cur_tag)] += 1
elif re.match('^[A-Z][A-Z]+$', cur_word) and re.match('^[A-Z][A-Z]+$', next_word) and re.match(
'^[A-Z][A-Z]+$', prev_word):
if (109.9, prev_tag, cur_tag) not in self.class109_dict:
self.class109_dict[(109.9, prev_tag, cur_tag)] = 1
else:
self.class109_dict[(109.9, prev_tag, cur_tag)] += 1
elif re.match('^[A-Z][A-Z]+$', cur_word) and re.match('^[A-Z][A-Z]+$', next_word):
if (109.11, prev_tag, cur_tag) not in self.class109_dict:
self.class109_dict[(109.11, prev_tag, cur_tag)] = 1
else:
self.class109_dict[(109.11, prev_tag, cur_tag)] += 1
elif re.match('^[A-Z][A-Z]+$', cur_word):
if (109.12, prev_tag, cur_tag) not in self.class109_dict:
self.class109_dict[(109.12, prev_tag, cur_tag)] = 1
else:
self.class109_dict[(109.12, prev_tag, cur_tag)] += 1
if re.match('[A-Z]', cur_word):
if (109.13, hyphen_count, prev_tag, cur_tag) not in self.class109_dict:
self.class109_dict[(109.13, hyphen_count, prev_tag, cur_tag)] = 1
else:
self.class109_dict[(109.13, hyphen_count, prev_tag, cur_tag)] += 1
if re.match('(.*?)[a-z](.*?)[A-Z]', cur_word):
if (109.14, prev_tag, cur_tag) not in self.class109_dict:
self.class109_dict[(109.14, prev_tag, cur_tag)] = 1
else:
self.class109_dict[(109.14, prev_tag, cur_tag)] += 1
def set_class110_dict(self):
"""
Create counts dict for class 110 features - additional patterns for model 1
Description of the sub-classes:
110.12. if the word length is >= 13 and finish with common suffixes for 'RB' tag
110.135. if the word length is >= 13 and finish with common suffixes for 'NNP' tag
110.2. if the word length is >= 13 and finish with common suffixes for 'NN'/'NNS' tag
elif:
110.3. if the word is from the form of number ('CD' tag)
110.35. if the word is from the form of number ('CD' tag) - greek numbers
110.4. if the word contains hyphen and finish with common suffixes for 'JJ' tag
elif the word is not kind of Punctuation mark
110.5. if the word is from common pattern of 'NNS' tag, and has not common year pattern.
110.6. if the word is from common pattern of 'NNP' tag (few patterns conatin capital letters)
110.7. if the word is from common pattern of 'JJ' tag (number + hyphen + letters)
110.9. if the word contains dot (common pattern of 'NNP' tag)
"""
with open(self.file_path) as f:
for line in f:
splited_words = re.split(' |[\n]', line)
if splited_words[-1] == "":
del splited_words[-1] # remove \n
for word_idx in range(len(splited_words)):
cur_tag = splited_words[word_idx].split('_')[1]
cur_word = splited_words[word_idx].split('_')[0]
if len(cur_word) >= 13:
if re.search('ally$', cur_word) or re.search('ely$', cur_word) or \
re.search('tly$', cur_word):
if (110.12, cur_tag) not in self.class110_dict: # RB tag
self.class110_dict[(110.12, cur_tag)] = 1
else:
self.class110_dict[(110.12, cur_tag)] += 1
elif re.search('tant$', cur_word) or \
re.search('cal$', cur_word) or \
re.search('ic$', cur_word) or \
re.search('ive$', cur_word) or \
re.search('nal$', cur_word) or \
re.search('-dependent$', cur_word) or \
re.search('-sensitive$', cur_word) or \
re.search('-specific$', cur_word) or \
re.search('tly$', cur_word):
if re.match('^[A-Z]$', cur_word[0]): # NNP tag
if (110.135, cur_tag) not in self.class110_dict:
self.class110_dict[(110.135, cur_tag)] = 1
else:
self.class110_dict[(110.135, cur_tag)] += 1
elif not (re.search('[\-]', cur_word)): # NN + NNS tags
if cur_word[-1] == 's' and not \
re.search('ness$', cur_word) and not re.match('^[A-Z]$', cur_word[0]):
if (110.2, cur_tag) not in self.class110_dict:
self.class110_dict[(110.2, cur_tag)] = 1
else:
self.class110_dict[(110.2, cur_tag)] += 1
if re.match('^[0-9\-,.:]*[][0-9]+[0-9\-,.:]*$', cur_word) or (cur_word in ["II", "III", "IV"] or
re.match(
'^[0-9\-.]+[L][R][B][0-9\-.]+[R][R][B][0-9\-.]+$',
cur_word)): # CD tag
if cur_word in ["II", "III", "IV"]: # in big model its NNP and not CD
if (110.35, cur_tag) not in self.class110_dict:
self.class110_dict[(110.35, cur_tag)] = 1
else:
self.class110_dict[(110.35, cur_tag)] += 1
elif (110.3, cur_tag) not in self.class110_dict:
self.class110_dict[(110.3, cur_tag)] = 1
else:
self.class110_dict[(110.3, cur_tag)] += 1
elif (re.search('[\-]', cur_word) and not re.match('^[A-Z]', cur_word.split('-')[-1])) and \
(re.search('ing$', cur_word.split('-')[-1]) or
re.search('ed$', cur_word.split('-')[-1]) or
re.search('ic$', cur_word.split('-')[-1]) or
re.search('age$', cur_word.split('-')[-1]) or
re.search('like$', cur_word.split('-')[-1]) or
re.search('ive$', cur_word.split('-')[-1]) or
re.search('ven$', cur_word.split('-')[-1]) or
re.search('^pre', cur_word.split('-')[0]) or
re.search('^anti', cur_word.split('-')[0]) or
re.search('er$', cur_word.split('-')[0])): # JJ tag. also ~40 NN get in.
if (110.4, cur_tag) not in self.class110_dict:
self.class110_dict[(110.4, cur_tag)] = 1
else:
self.class110_dict[(110.4, cur_tag)] += 1
elif cur_word not in ["-LCB-", "-RCB-", "-LRB-", "-RRB-", "--", "...", "I", "A", ",", ".", ":"]:
if (re.match('^[a-z]*[A-Z\-0-9.,]+[s]$', cur_word) and # NNS tag
len(cur_word) != 2) and not \
re.match('^([a-zA-Z]*(-)?[0-9][0-9][0-9][0-9](s?))$|^([a-zA-Z]*(-)?[0-9][0-9]s)$',
cur_word):
if (110.5, cur_tag) not in self.class110_dict:
self.class110_dict[(110.5, cur_tag)] = 1
else:
self.class110_dict[(110.5, cur_tag)] += 1
if re.match('^[A-Z\-0-9.,]+$', cur_word) or \
re.search('[a-z\-][A-Z]', cur_word) or \
re.match('^[A-Za-z][\-][a-z]+$', cur_word): # NNP tag
if (110.6, cur_tag) not in self.class110_dict:
self.class110_dict[(110.6, cur_tag)] = 1
else:
self.class110_dict[(110.6, cur_tag)] += 1
if re.match('^[0-9\-.,]+[\-][a-zA-Z]+$', cur_word): # JJ tag
if (110.7, cur_tag) not in self.class110_dict:
self.class110_dict[(110.7, cur_tag)] = 1
else:
self.class110_dict[(110.7, cur_tag)] += 1
if re.search('\.$', cur_word) and cur_word not in [".",
"No."]: # in big model its NNP, and not FW
if (110.9, cur_tag) not in self.class110_dict:
self.class110_dict[(110.9, cur_tag)] = 1
else:
self.class110_dict[(110.9, cur_tag)] += 1
def set_class111_dict(self):
"""
Create counts dict for class 111 features - additional patterns for model 2
Description of the sub-classes:
110.11. if the word length is >= 13 and finish with common suffixes for 'VBG' tag
110.12. if the word length is >= 13 and finish with common suffixes for 'RB' tag
110.13. if the word length is >= 13 and finish with common suffixes for 'JJ' tag
110.14. if the word length is >= 13 and finish with common suffixes for 'VBN'/'VBD' tag
110.135. if the word length is >= 13 and finish with common suffixes for 'NNP' tag
110.2. if the word length is >= 13 and finish with common suffixes for 'NN'/'NNS' tag
110.1. if the word length is >= 13 and finish with common suffixes for 'NN' tag
elif:
110.3. if the word is from the form of number ('CD' tag)
110.4. if the word contains hyphen and finish with common suffixes for 'JJ' tag
else:
110.5. if the word is from common special pattern of 'NNS' tag.
110.6. if the word is from common pattern of 'NN' tag (patterns contain capital letters)
110.7. if the word is from common pattern of 'JJ' tag (number + hyphen + letters)
110.8. if the word is from common pattern of 'NN' tag (letters + hyphen + numbers)
110.9. if the word contains dot (common pattern of 'FW' tag)
110.92. if the word contains dot (common pattern of 'FW' tag)
110.93. if the word contains dot (common pattern of 'LS' tag)
"""
with open(self.file_path) as f:
for line in f:
splited_words = re.split(' |[\n]', line)
if splited_words[-1] == "":
del splited_words[-1] # remove \n
for word_idx in range(len(splited_words)):
cur_tag = splited_words[word_idx].split('_')[1]
cur_word = splited_words[word_idx].split('_')[0]
if len(cur_word) >= 13:
if re.search('ing$', cur_word) and not (re.search('[\-]', cur_word)):
if (111.11, cur_tag) not in self.class111_dict:
self.class111_dict[(111.11, cur_tag)] = 1
else:
self.class111_dict[(111.11, cur_tag)] += 1
elif re.search('ed$', cur_word) and not (re.search('[\-]', cur_word)):
if (111.14, cur_tag) not in self.class111_dict:
self.class111_dict[(111.14, cur_tag)] = 1
else:
self.class111_dict[(111.14, cur_tag)] += 1
elif re.search('ally$', cur_word) or re.search('ely$', cur_word) or \
re.search('tly$', cur_word):
if (111.12, cur_tag) not in self.class111_dict: # RB tag
self.class111_dict[(111.12, cur_tag)] = 1
else:
self.class111_dict[(111.12, cur_tag)] += 1
elif re.search('tant$', cur_word) or \
re.search('cal$', cur_word) or \
re.search('ic$', cur_word) or \
re.search('ive$', cur_word) or \
re.search('nal$', cur_word) or \
re.search('-dependent$', cur_word) or \
re.search('-sensitive$', cur_word) or \
re.search('-specific$', cur_word) or \
re.search('tly$', cur_word): # JJ tag
if (111.13, cur_tag) not in self.class111_dict:
self.class111_dict[(111.13, cur_tag)] = 1
else:
self.class111_dict[(111.13, cur_tag)] += 1
else: # NN + NNS tags
if cur_word[-1] == 's':
if (111.2, cur_tag) not in self.class111_dict:
self.class111_dict[(111.2, cur_tag)] = 1
else:
self.class111_dict[(111.2, cur_tag)] += 1
if (111.1, cur_tag) not in self.class111_dict:
self.class111_dict[(111.1, cur_tag)] = 1
else:
self.class111_dict[(111.1, cur_tag)] += 1
if re.match('^[0-9\-,.:]*[][0-9]+[0-9\-,.:]*$', cur_word) or (cur_word in ["II", "III", "IV"] or
re.match(
'^[0-9\-.]+[L][R][B][0-9\-.]+[R][R][B][0-9\-.]+$',
cur_word)): # CD tag
if (111.3, cur_tag) not in self.class111_dict:
self.class111_dict[(111.3, cur_tag)] = 1
else:
self.class111_dict[(111.3, cur_tag)] += 1
elif ((re.search('[\-]', cur_word) and
(re.search('ing$', cur_word.split('-')[-1]) or
re.search('ed$', cur_word.split('-')[-1]) or
re.search('ic$', cur_word.split('-')[-1]) or
re.search('age$', cur_word.split('-')[-1]) or
re.search('like$', cur_word.split('-')[-1]) or
re.search('ive$', cur_word.split('-')[-1]) or
re.search('ven$', cur_word.split('-')[-1]) or
re.search('^pre', cur_word.split('-')[0]) or
re.search('^anti', cur_word.split('-')[0]) or
re.search('er$', cur_word.split('-')[0]))) or
re.search('kDa$', cur_word)): # JJ tag
if (111.4, cur_tag) not in self.class111_dict:
self.class111_dict[(111.4, cur_tag)] = 1
else:
self.class111_dict[(111.4, cur_tag)] += 1
else:
if re.match('^[a-z]*[A-Z\-0-9.,]+[s]$', cur_word): # NNS tag
if (111.5, cur_tag) not in self.class111_dict:
self.class111_dict[(111.5, cur_tag)] = 1
else:
self.class111_dict[(111.5, cur_tag)] += 1
if (re.match('^[A-Z\-0-9.,]+$', cur_word) and cur_word not in ["I", "A", ",", ".", ":"]) or \
re.search('[a-z\-][A-Z]', cur_word) or \
re.match('^[A-Za-z][\-][a-z]+$', cur_word) or \
re.match('^[a-z\-]+[0-9]+$', cur_word) or \
re.search('coid$', cur_word) or \
re.search('ness$', cur_word): # NN tag
if (111.6, cur_tag) not in self.class111_dict:
self.class111_dict[(111.6, cur_tag)] = 1
else:
self.class111_dict[(111.6, cur_tag)] += 1
if re.match('^[0-9\-.,]+[\-][a-zA-Z]+$', cur_word): # might be JJ tag
if (111.7, cur_tag) not in self.class111_dict:
self.class111_dict[(111.7, cur_tag)] = 1
else:
self.class111_dict[(111.7, cur_tag)] += 1
if re.match('^[A-Z]?[a-z]+[\-][0-9\-.,]+$', cur_word): # might be NN tag
if (111.8, cur_tag) not in self.class111_dict:
self.class111_dict[(111.8, cur_tag)] = 1
else:
self.class111_dict[(111.8, cur_tag)] += 1
if re.search('\.$', cur_word) and cur_word != ".": # might be FW tag, but not only
if (111.9, cur_tag) not in self.class111_dict:
self.class111_dict[(111.9, cur_tag)] = 1
else:
self.class111_dict[(111.9, cur_tag)] += 1
if cur_word in ['Treponema', 'cerevisiae', 'pallidum', 'Borrelia', 'burgdorferi',
'vitro', 'vivo', 'i.e.', 'e.g.']: # FW tag
if (111.92, cur_tag) not in self.class111_dict:
self.class111_dict[(111.92, cur_tag)] = 1
else:
self.class111_dict[(111.92, cur_tag)] += 1
if cur_word in ['in', 'In'] and word_idx != len(splited_words) - 1: # FW tag
next_word = splited_words[word_idx + 1].split('_')[0]
if next_word in ['vitro', 'vivo']:
if (111.92, cur_tag) not in self.class111_dict:
self.class111_dict[(111.92, cur_tag)] = 1
else:
self.class111_dict[(111.92, cur_tag)] += 1
if cur_word in ['i', 'ii', 'iii', 'iv']: # LS tag
if (111.93, cur_tag) not in self.class111_dict:
self.class111_dict[(111.93, cur_tag)] = 1
else:
self.class111_dict[(111.93, cur_tag)] += 1
class Feature2Id:
"""
define unique index for each feature which pass its class threshold.
"""
def __init__(self, feature_statistics: ClassStatistics):
self.feature_statistics = feature_statistics
self.all_feature_index_dict = OrderedDict()
self.n_total_features = 0 # Total number of features accumulated
self.class100_feature_index_dict = OrderedDict() # Init all features index dictionaries
self.n_class100 = 0 # Number of Word\Tag pairs features - this is the index for class 1
self.class101_feature_index_dict = OrderedDict()
self.n_class101 = 0
self.class102_feature_index_dict = OrderedDict()
self.n_class102 = 0
self.class103_feature_index_dict = OrderedDict()
self.n_class103 = 0
self.class104_feature_index_dict = OrderedDict()
self.n_class104 = 0
self.class105_feature_index_dict = OrderedDict()
self.n_class105 = 0
self.class106_feature_index_dict = OrderedDict()
self.n_class106 = 0
self.class107_feature_index_dict = OrderedDict()
self.n_class107 = 0
self.class108_feature_index_dict = OrderedDict()
self.n_class108 = 0
self.class109_feature_index_dict = OrderedDict()
self.n_class109 = 0
self.class110_feature_index_dict = OrderedDict()
self.n_class110 = 0
self.class111_feature_index_dict = OrderedDict()
self.n_class111 = 0
def set_index_class100(self, threshold=0):
"""
Extract out of text all word/tag pairs
:param threshold: feature count threshold - empirical count must be equal or greater than threshold
"""
for key, value in self.feature_statistics.class100_dict.items():
if value >= threshold:
self.class100_feature_index_dict[key] = self.n_class100 + self.n_total_features
self.n_class100 += 1
self.n_total_features += self.n_class100
def set_index_class101(self, threshold=0):
for key, value in self.feature_statistics.class101_dict.items():
if value >= threshold:
self.class101_feature_index_dict[key] = self.n_class101 + self.n_total_features
self.n_class101 += 1
self.n_total_features += self.n_class101
def set_index_class102(self, threshold=0):
# set thresholds for class, f102 we choose the threshold to be the mean in every length category
thresholds = dict() # length of prefix : threshold
for length in [1, 2, 3, 4, 5, 6, 7]:
keys = [key for key in self.feature_statistics.class102_dict if len(key[1]) == length]
values = [self.feature_statistics.class102_dict[key] for key in keys]
thresholds[length] = np.mean(values)
for key, value in self.feature_statistics.class102_dict.items():
if value >= thresholds[len(key[1])]:
self.class102_feature_index_dict[key] = self.n_class102 + self.n_total_features
self.n_class102 += 1
self.n_total_features += self.n_class102
def set_index_class103(self, threshold=0):
keys = [key for key in self.feature_statistics.class103_dict]
values = [self.feature_statistics.class103_dict[key] for key in keys]
threshold = np.mean(values)
for key, value in self.feature_statistics.class103_dict.items():
if value >= threshold:
self.class103_feature_index_dict[key] = self.n_class103 + self.n_total_features
self.n_class103 += 1
self.n_total_features += self.n_class103
def set_index_class104(self, threshold=0):
for key, value in self.feature_statistics.class104_dict.items():
if value >= threshold:
self.class104_feature_index_dict[key] = self.n_class104 + self.n_total_features
self.n_class104 += 1
self.n_total_features += self.n_class104
def set_index_class105(self, threshold=0):
for key, value in self.feature_statistics.class105_dict.items():
if value >= threshold:
self.class105_feature_index_dict[key] = self.n_class105 + self.n_total_features
self.n_class105 += 1
self.n_total_features += self.n_class105
def set_index_class106(self, threshold=0):
keys = [key for key in self.feature_statistics.class106_dict]
values = [self.feature_statistics.class106_dict[key] for key in keys]
threshold = np.mean(values)
for key, value in self.feature_statistics.class106_dict.items():
if value >= threshold:
self.class106_feature_index_dict[key] = self.n_class106 + self.n_total_features
self.n_class106 += 1
self.n_total_features += self.n_class106
def set_index_class107(self, threshold=0):
keys = [key for key in self.feature_statistics.class107_dict]
values = [self.feature_statistics.class107_dict[key] for key in keys]
threshold = np.mean(values)
for key, value in self.feature_statistics.class107_dict.items():
if value >= threshold:
self.class107_feature_index_dict[key] = self.n_class107 + self.n_total_features
self.n_class107 += 1
self.n_total_features += self.n_class107
def set_index_class108(self, threshold=0):
for key, value in self.feature_statistics.class108_dict.items():
if value >= threshold:
self.class108_feature_index_dict[key] = self.n_class108 + self.n_total_features
self.n_class108 += 1
self.n_total_features += self.n_class108
def set_index_class109(self, threshold=0):
for key, value in self.feature_statistics.class109_dict.items():
if value >= threshold:
self.class109_feature_index_dict[key] = self.n_class109 + self.n_total_features
self.n_class109 += 1
self.n_total_features += self.n_class109
def set_index_class110(self, threshold=0):
for key, value in self.feature_statistics.class110_dict.items():
if value >= threshold:
self.class110_feature_index_dict[key] = self.n_class110 + self.n_total_features
self.n_class110 += 1
self.n_total_features += self.n_class110
def set_index_class111(self, threshold=0):
for key, value in self.feature_statistics.class111_dict.items():
if value >= threshold:
self.class111_feature_index_dict[key] = self.n_class111 + self.n_total_features
self.n_class111 += 1
self.n_total_features += self.n_class111
def build_all_classes_feature_index_dict(self):
self.all_feature_index_dict.update(self.class100_feature_index_dict)
self.all_feature_index_dict.update(self.class101_feature_index_dict)
self.all_feature_index_dict.update(self.class102_feature_index_dict)
self.all_feature_index_dict.update(self.class103_feature_index_dict)
self.all_feature_index_dict.update(self.class104_feature_index_dict)
self.all_feature_index_dict.update(self.class105_feature_index_dict)
self.all_feature_index_dict.update(self.class106_feature_index_dict)
self.all_feature_index_dict.update(self.class107_feature_index_dict)
self.all_feature_index_dict.update(self.class108_feature_index_dict)
self.all_feature_index_dict.update(self.class109_feature_index_dict)
self.all_feature_index_dict.update(self.class110_feature_index_dict)
self.all_feature_index_dict.update(self.class111_feature_index_dict)
class ConfusionMatrix:
def __init__(self, conf_mat: dict, m=None, M=None):
"""
build ConfusionMatrix object
:param conf_mat: (true_tag, predicted_tag) keys with values number of occurrences
:param m: minimum value for color map - everything smaller will get the same color
:param M: maximum value for color map - everything bigger will get the same color
"""
self.conf_mat = conf_mat
self.m = m
self.M = M
# source: https://stackoverflow.com/questions/38931566/pandas-style-background-gradient-both-rows-and-columns
def background_gradient(self, s, low=0, high=0):
"""
create colors for data frame values
:param s: data frame
:param low: parameter for normalization
:param high: parameter for normalization
:return: color map to apply
"""
cmap = sns.light_palette("red", as_cmap=True)
if self.m is None:
self.m = s.min().min()
if self.M is None:
self.M = s.max().max()
rng = self.M - self.m
norm = colors.Normalize(self.m - (rng * low),
self.M + (rng * high))
normed = s.apply(norm)
cm = plt.cm.get_cmap(cmap)
c = normed.applymap(lambda x: colors.rgb2hex(cm(x)))
ret = c.applymap(lambda x: 'background-color: %s' % x)
return ret
@staticmethod
def highlight_green(s):
color = '#baf1a1'
return 'background-color: %s' % color
@staticmethod
def highlight_zero(s):
color = '#C2C2C2'
return 'background-color: %s' % color
def plot_confusion_matrix(self, output_path: str = '', colored=False):
"""
creates confusion matrix.
if colored = False only plot the DataFrame to console
but if colored = True create beautiful colored table and save to .html file with path 'outputh_path'
TRUE TAG FOR TOP 10 CONFUSED TAGS
________________________________
PREDICTED TAG | || || || |
________________________________
| || || || |
________________________________
.
.
.
________________________________
| || || || |
________________________________
(in Jupyter / Python Notebook it shows in the interface, in python script need to save to .html to show result)
:param output_path: the path for .html file to save (only saves if colored = True)
:param colored: if True will save .html file with colored confusion matrix
:return: None
"""
# create dict for wrong tagging in the format -> true_tag : total amount of mistakes
conf_matrix_dict_wrong_tagging = dict()
for (true, pred), amount_mistakes in self.conf_mat.items():
if true != pred:
if true not in conf_matrix_dict_wrong_tagging:
conf_matrix_dict_wrong_tagging[true] = amount_mistakes
else:
conf_matrix_dict_wrong_tagging[true] += amount_mistakes
# sort by amount of mistakes desc.
conf_matrix_dict_wrong_tagging = sorted(conf_matrix_dict_wrong_tagging.items(), key=lambda item: item[1],
reverse=True)
# see what columns we need for our confusion matrix (columns = true label)
columns_tags = sorted([true for true, _ in conf_matrix_dict_wrong_tagging[:10]])
# set rows to be the columns + all other tags (rows = predicted label)
rows_tags = list(columns_tags) + sorted(set([true_tag for (true_tag, pred_tag), _ in self.conf_mat.items() if
true_tag not in columns_tags]))
# create empty DataFrame with rows and cols needed
df = pd.DataFrame(0, index=rows_tags, columns=columns_tags)
# fill the DataFrame with the values
for pred_tag in df.index:
for true_tag in df.columns:
if (true_tag, pred_tag) in self.conf_mat:
df.loc[pred_tag][true_tag] = self.conf_mat[(true_tag, pred_tag)]
else:
df.loc[pred_tag][true_tag] = 0
# plot the regular DataFrame without colors
if not colored:
print(df)
return
# else: plot styled DataFrame with colors
# change colors for wrong tagging
style = df.style.apply(self.background_gradient, axis=None)
# change color for 0 values
for pred_tag in df.index:
for true_tag in df.columns:
if df.loc[pred_tag][true_tag] == 0:
style = style.applymap(self.highlight_zero, subset=pd.IndexSlice[pred_tag, true_tag])
# change color for correct tagging
for tag in columns_tags:
style = style.applymap(self.highlight_green, subset=pd.IndexSlice[tag, tag])
# write the pandas styler object to HTML -> can view the confusion matrix from any web browser
with open(output_path, "w") as html:
html.write('<font size="10" face="Courier New" >' + style.render() + '</font>')
# Auxiliary function for class f108
def re_match_words(regular_exp: str, lst):
if not [w for w in lst if w != '']:
return False
for word in lst:
if word != '' and not re.match(regular_exp, word):
return False
return True
# Auxiliary function for class f108
def re_match_letters_numbers(regular_exps: list, lst):