-
Notifications
You must be signed in to change notification settings - Fork 15
/
evaluate_prediction.py
1448 lines (1276 loc) · 67 KB
/
evaluate_prediction.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
import numpy as np
import argparse
import config
from utils.string_helper import *
from collections import defaultdict
import os
import logging
import pykp.io
import pickle
def check_valid_keyphrases(str_list):
num_pred_seq = len(str_list)
is_valid = np.zeros(num_pred_seq, dtype=bool)
for i, word_list in enumerate(str_list):
keep_flag = True
if len(word_list) == 0:
keep_flag = False
for w in word_list:
if opt.invalidate_unk:
if w == pykp.io.UNK_WORD or w == ',' or w == '.':
keep_flag = False
else:
if w == ',' or w == '.':
keep_flag = False
is_valid[i] = keep_flag
return is_valid
def dummy_filter(str_list):
num_pred_seq = len(str_list)
return np.ones(num_pred_seq, dtype=bool)
def compute_extra_one_word_seqs_mask(str_list):
num_pred_seq = len(str_list)
mask = np.zeros(num_pred_seq, dtype=bool)
num_one_word_seqs = 0
for i, word_list in enumerate(str_list):
if len(word_list) == 1:
num_one_word_seqs += 1
if num_one_word_seqs > 1:
mask[i] = False
continue
mask[i] = True
return mask, num_one_word_seqs
def check_duplicate_keyphrases(keyphrase_str_list):
"""
:param keyphrase_str_list: a 2d list of tokens
:return: a boolean np array indicate, 1 = unique, 0 = duplicate
"""
num_keyphrases = len(keyphrase_str_list)
not_duplicate = np.ones(num_keyphrases, dtype=bool)
keyphrase_set = set()
for i, keyphrase_word_list in enumerate(keyphrase_str_list):
if '_'.join(keyphrase_word_list) in keyphrase_set:
not_duplicate[i] = False
else:
not_duplicate[i] = True
keyphrase_set.add('_'.join(keyphrase_word_list))
return not_duplicate
def check_present_keyphrases(src_str, keyphrase_str_list, match_by_str=False):
"""
:param src_str: stemmed word list of source text
:param keyphrase_str_list: stemmed list of word list
:return:
"""
num_keyphrases = len(keyphrase_str_list)
is_present = np.zeros(num_keyphrases, dtype=bool)
for i, keyphrase_word_list in enumerate(keyphrase_str_list):
joined_keyphrase_str = ' '.join(keyphrase_word_list)
if joined_keyphrase_str.strip() == "": # if the keyphrase is an empty string
is_present[i] = False
else:
if not match_by_str: # match by word
# check if it appears in source text
match = False
for src_start_idx in range(len(src_str) - len(keyphrase_word_list) + 1):
match = True
for keyphrase_i, keyphrase_w in enumerate(keyphrase_word_list):
src_w = src_str[src_start_idx + keyphrase_i]
if src_w != keyphrase_w:
match = False
break
if match:
break
if match:
is_present[i] = True
else:
is_present[i] = False
else: # match by str
if joined_keyphrase_str in ' '.join(src_str):
is_present[i] = True
else:
is_present[i] = False
return is_present
def find_present_and_absent_index(src_str, keyphrase_str_list, use_name_variations=False):
"""
:param src_str: stemmed word list of source text
:param keyphrase_str_list: stemmed list of word list
:return:
"""
num_keyphrases = len(keyphrase_str_list)
#is_present = np.zeros(num_keyphrases, dtype=bool)
present_indices = []
absent_indices = []
for i, v in enumerate(keyphrase_str_list):
if use_name_variations:
keyphrase_word_list = v[0]
else:
keyphrase_word_list = v
joined_keyphrase_str = ' '.join(keyphrase_word_list)
if joined_keyphrase_str.strip() == "": # if the keyphrase is an empty string
#is_present[i] = False
absent_indices.append(i)
else:
# check if it appears in source text
match = False
for src_start_idx in range(len(src_str) - len(keyphrase_word_list) + 1):
match = True
for keyphrase_i, keyphrase_w in enumerate(keyphrase_word_list):
src_w = src_str[src_start_idx + keyphrase_i]
if src_w != keyphrase_w:
match = False
break
if match:
break
if match:
#is_present[i] = True
present_indices.append(i)
else:
#is_present[i] = False
absent_indices.append(i)
return present_indices, absent_indices
def separate_present_absent_by_source_with_variations(src_token_list, keyphrase_variation_token_3dlist, use_name_variations=True):
num_keyphrases = len(keyphrase_variation_token_3dlist)
present_indices = []
absent_indices = []
for keyphrase_idx, v in enumerate(keyphrase_variation_token_3dlist):
if use_name_variations:
keyphrase_variation_token_2dlist = v
else:
keyphrase_variation_token_2dlist = [v]
present_flag = False
absent_flag = False
# iterate every variation of a keyphrase
for variation_idx, keyphrase_token_list in enumerate(keyphrase_variation_token_2dlist):
joined_keyphrase_str = ' '.join(keyphrase_token_list)
if joined_keyphrase_str.strip() == "": # if the keyphrase is an empty string
absent_flag = True
else: # check if it appears in source text
match = False
for src_start_idx in range(len(src_token_list) - len(keyphrase_token_list) + 1):
match = True
for keyphrase_i, keyphrase_w in enumerate(keyphrase_token_list):
src_w = src_token_list[src_start_idx + keyphrase_i]
if src_w != keyphrase_w:
match = False
break
if match:
break
if match:
# is_present[i] = True
# present_indices.append(i)
present_flag = True
else:
# is_present[i] = False
# absent_indices.append(i)
absent_flag = True
if present_flag and absent_flag:
present_indices.append(keyphrase_idx)
absent_indices.append(keyphrase_idx)
elif present_flag:
present_indices.append(keyphrase_idx)
elif absent_flag:
absent_indices.append(keyphrase_idx)
else:
raise ValueError("Problem occurs in present absent checking")
present_keyphrase_variation_token_3dlist = [keyphrase_variation_token_3dlist[present_index] for present_index in
present_indices]
absent_keyphrase_variation_token_3dlist = [keyphrase_variation_token_3dlist[absent_index] for absent_index in
absent_indices]
return present_keyphrase_variation_token_3dlist, absent_keyphrase_variation_token_3dlist
def check_present_and_duplicate_keyphrases(src_str, keyphrase_str_list, match_by_str=False):
"""
:param src_str: stemmed word list of source text
:param keyphrase_str_list: stemmed list of word list
:return:
"""
num_keyphrases = len(keyphrase_str_list)
is_present = np.zeros(num_keyphrases, dtype=bool)
not_duplicate = np.ones(num_keyphrases, dtype=bool)
keyphrase_set = set()
for i, keyphrase_word_list in enumerate(keyphrase_str_list):
joined_keyphrase_str = ' '.join(keyphrase_word_list)
if joined_keyphrase_str in keyphrase_set:
not_duplicate[i] = False
else:
not_duplicate[i] = True
if joined_keyphrase_str.strip() == "": # if the keyphrase is an empty string
is_present[i] = False
else:
if not match_by_str: # match by word
# check if it appears in source text
match = False
for src_start_idx in range(len(src_str) - len(keyphrase_word_list) + 1):
match = True
for keyphrase_i, keyphrase_w in enumerate(keyphrase_word_list):
src_w = src_str[src_start_idx + keyphrase_i]
if src_w != keyphrase_w:
match = False
break
if match:
break
if match:
is_present[i] = True
else:
is_present[i] = False
else: # match by str
if joined_keyphrase_str in ' '.join(src_str):
is_present[i] = True
else:
is_present[i] = False
keyphrase_set.add(joined_keyphrase_str)
return is_present, not_duplicate
def compute_match_result_backup(trg_str_list, pred_str_list, type='exact'):
assert type in ['exact', 'sub'], "Right now only support exact matching and substring matching"
num_pred_str = len(pred_str_list)
num_trg_str = len(trg_str_list)
is_match = np.zeros(num_pred_str, dtype=bool)
for pred_idx, pred_word_list in enumerate(pred_str_list):
if type == 'exact': # exact matching
is_match[pred_idx] = False
for trg_idx, trg_word_list in enumerate(trg_str_list):
if len(pred_word_list) != len(trg_word_list): # if length not equal, it cannot be a match
continue
match = True
for pred_w, trg_w in zip(pred_word_list, trg_word_list):
if pred_w != trg_w:
match = False
break
# If there is one exact match in the target, match succeeds, go the next prediction
if match:
is_match[pred_idx] = True
break
elif type == 'sub': # consider a match if the prediction is a subset of the target
joined_pred_word_list = ' '.join(pred_word_list)
for trg_idx, trg_word_list in enumerate(trg_str_list):
if joined_pred_word_list in ' '.join(trg_word_list):
is_match[pred_idx] = True
break
return is_match
def compute_match_result(trg_str_list, pred_str_list, type='exact', dimension=1):
assert type in ['exact', 'sub'], "Right now only support exact matching and substring matching"
assert dimension in [1, 2], "only support 1 or 2"
num_pred_str = len(pred_str_list)
num_trg_str = len(trg_str_list)
if dimension == 1:
is_match = np.zeros(num_pred_str, dtype=bool)
for pred_idx, pred_word_list in enumerate(pred_str_list):
joined_pred_word_list = ' '.join(pred_word_list)
for trg_idx, trg_word_list in enumerate(trg_str_list):
joined_trg_word_list = ' '.join(trg_word_list)
if type == 'exact':
if joined_pred_word_list == joined_trg_word_list:
is_match[pred_idx] = True
break
elif type == 'sub':
if joined_pred_word_list in joined_trg_word_list:
is_match[pred_idx] = True
break
else:
is_match = np.zeros((num_trg_str, num_pred_str), dtype=bool)
for trg_idx, trg_word_list in enumerate(trg_str_list):
joined_trg_word_list = ' '.join(trg_word_list)
for pred_idx, pred_word_list in enumerate(pred_str_list):
joined_pred_word_list = ' '.join(pred_word_list)
if type == 'exact':
if joined_pred_word_list == joined_trg_word_list:
is_match[trg_idx][pred_idx] = True
elif type == 'sub':
if joined_pred_word_list in joined_trg_word_list:
is_match[trg_idx][pred_idx] = True
return is_match
def prepare_classification_result_dict(precision_k, recall_k, f1_k, num_matches_k, num_predictions_k, num_targets_k, topk, is_present):
present_tag = "present" if is_present else "absent"
return {'precision@%d_%s' % (topk, present_tag): precision_k, 'recall@%d_%s' % (topk, present_tag): recall_k,
'f1_score@%d_%s' % (topk, present_tag): f1_k, 'num_matches@%d_%s' % (topk, present_tag): num_matches_k,
'num_predictions@%d_%s' % (topk, present_tag): num_predictions_k, 'num_targets@%d_%s' % (topk, present_tag): num_targets_k}
def compute_classification_metrics_at_k(is_match, num_predictions, num_trgs, topk=5, meng_rui_precision=False):
"""
:param is_match: a boolean np array with size [num_predictions]
:param predicted_list:
:param true_list:
:param topk:
:return: {'precision@%d' % topk: precision_k, 'recall@%d' % topk: recall_k, 'f1_score@%d' % topk: f1, 'num_matches@%d': num_matches}
"""
assert is_match.shape[0] == num_predictions
if topk == 'M':
topk = num_predictions
elif topk == 'G':
#topk = num_trgs
if num_predictions < num_trgs:
topk = num_trgs
else:
topk = num_predictions
if meng_rui_precision:
if num_predictions > topk:
is_match = is_match[:topk]
num_predictions_k = topk
else:
num_predictions_k = num_predictions
else:
if num_predictions > topk:
is_match = is_match[:topk]
num_predictions_k = topk
num_matches_k = sum(is_match)
precision_k, recall_k, f1_k = compute_classification_metrics(num_matches_k, num_predictions_k, num_trgs)
return precision_k, recall_k, f1_k, num_matches_k, num_predictions_k
def compute_classification_metrics_at_ks(is_match, num_predictions, num_trgs, k_list=[5,10], meng_rui_precision=False):
"""
:param is_match: a boolean np array with size [num_predictions]
:param predicted_list:
:param true_list:
:param topk:
:return: {'precision@%d' % topk: precision_k, 'recall@%d' % topk: recall_k, 'f1_score@%d' % topk: f1, 'num_matches@%d': num_matches}
"""
assert is_match.shape[0] == num_predictions
#topk.sort()
if num_predictions == 0:
precision_ks = [0] * len(k_list)
recall_ks = [0] * len(k_list)
f1_ks = [0] * len(k_list)
num_matches_ks = [0] * len(k_list)
num_predictions_ks = [0] * len(k_list)
else:
num_matches = np.cumsum(is_match)
num_predictions_ks = []
num_matches_ks = []
precision_ks = []
recall_ks = []
f1_ks = []
for topk in k_list:
if topk == 'M':
topk = num_predictions
elif topk == 'G':
#topk = num_trgs
if num_predictions < num_trgs:
topk = num_trgs
else:
topk = num_predictions
if meng_rui_precision:
if num_predictions > topk:
num_matches_at_k = num_matches[topk-1]
num_predictions_at_k = topk
else:
num_matches_at_k = num_matches[-1]
num_predictions_at_k = num_predictions
else:
if num_predictions > topk:
num_matches_at_k = num_matches[topk - 1]
else:
num_matches_at_k = num_matches[-1]
num_predictions_at_k = topk
precision_k, recall_k, f1_k = compute_classification_metrics(num_matches_at_k, num_predictions_at_k, num_trgs)
precision_ks.append(precision_k)
recall_ks.append(recall_k)
f1_ks.append(f1_k)
num_matches_ks.append(num_matches_at_k)
num_predictions_ks.append(num_predictions_at_k)
return precision_ks, recall_ks, f1_ks, num_matches_ks, num_predictions_ks
def compute_classification_metrics(num_matches, num_predictions, num_trgs):
precision = compute_precision(num_matches, num_predictions)
recall = compute_recall(num_matches, num_trgs)
f1 = compute_f1(precision, recall)
return precision, recall, f1
def compute_precision(num_matches, num_predictions):
return num_matches / num_predictions if num_predictions > 0 else 0.0
def compute_recall(num_matches, num_trgs):
return num_matches / num_trgs if num_trgs > 0 else 0.0
def compute_f1(precision, recall):
return float(2 * (precision * recall)) / (precision + recall) if precision + recall > 0 else 0.0
def dcg_at_k(r, k, num_trgs, method=1):
"""
Reference from https://www.kaggle.com/wendykan/ndcg-example and https://gist.github.com/bwhite/3726239
Score is discounted cumulative gain (dcg)
Relevance is positive real values. Can use binary
as the previous methods.
Example from
http://www.stanford.edu/class/cs276/handouts/EvaluationNew-handout-6-per.pdf
Args:
r: Relevance scores (list or numpy) in rank order
(first element is the first item)
k: Number of results to consider
method: If 0 then weights are [1.0, 1.0, 0.6309, 0.5, 0.4307, ...]
If 1 then weights are [1.0, 0.6309, 0.5, 0.4307, ...]
Returns:
Discounted cumulative gain
"""
num_predictions = r.shape[0]
if k == 'M':
k = num_predictions
elif k == 'G':
#k = num_trgs
if num_predictions < num_trgs:
k = num_trgs
else:
k = num_predictions
if num_predictions == 0:
dcg = 0.
else:
if num_predictions > k:
r = r[:k]
num_predictions = k
if method == 0:
dcg = r[0] + np.sum(r[1:] / np.log2(np.arange(2, r.size + 1)))
elif method == 1:
discounted_gain = r / np.log2(np.arange(2, r.size + 2))
dcg = np.sum(discounted_gain)
else:
raise ValueError('method must be 0 or 1.')
return dcg
def dcg_at_ks(r, k_list, num_trgs, method=1):
num_predictions = r.shape[0]
if num_predictions == 0:
dcg_array = np.array([0] * len(k_list))
else:
k_max = -1
for k in k_list:
if k == 'M':
k = num_predictions
elif k == 'G':
#k = num_trgs
if num_predictions < num_trgs:
k = num_trgs
else:
k = num_predictions
if k > k_max:
k_max = k
if num_predictions > k_max:
r = r[:k_max]
num_predictions = k_max
if method == 1:
discounted_gain = r / np.log2(np.arange(2, r.size + 2))
dcg = np.cumsum(discounted_gain)
return_indices = []
for k in k_list:
if k == 'M':
k = num_predictions
elif k == 'G':
#k = num_trgs
if num_predictions < num_trgs:
k = num_trgs
else:
k = num_predictions
return_indices.append((k - 1) if k <= num_predictions else (num_predictions - 1))
return_indices = np.array(return_indices, dtype=int)
dcg_array = dcg[return_indices]
else:
raise ValueError('method must 1.')
return dcg_array
def ndcg_at_k(r, k, num_trgs, method=1, include_dcg=False):
"""Score is normalized discounted cumulative gain (ndcg)
Relevance is positive real values. Can use binary
as the previous methods.
Example from
http://www.stanford.edu/class/cs276/handouts/EvaluationNew-handout-6-per.pdf
Args:
r: Relevance scores (list or numpy) in rank order
(first element is the first item)
k: Number of results to consider
method: If 0 then weights are [1.0, 1.0, 0.6309, 0.5, 0.4307, ...]
If 1 then weights are [1.0, 0.6309, 0.5, 0.4307, ...]
Returns:
Normalized discounted cumulative gain
"""
if r.shape[0] == 0:
ndcg = 0.0
dcg = 0.0
else:
dcg_max = dcg_at_k(np.array(sorted(r, reverse=True)), k, num_trgs, method)
if dcg_max <= 0.0:
ndcg = 0.0
else:
dcg = dcg_at_k(r, k, num_trgs, method)
ndcg = dcg / dcg_max
if include_dcg:
return ndcg, dcg
else:
return ndcg
def ndcg_at_ks(r, k_list, num_trgs, method=1, include_dcg=False):
if r.shape[0] == 0:
ndcg_array = [0.0] * len(k_list)
dcg_array = [0.0] * len(k_list)
else:
dcg_array = dcg_at_ks(r, k_list, num_trgs, method)
ideal_r = np.array(sorted(r, reverse=True))
dcg_max_array = dcg_at_ks(ideal_r, k_list, num_trgs, method)
ndcg_array = dcg_array / dcg_max_array
ndcg_array = np.nan_to_num(ndcg_array)
if include_dcg:
return ndcg_array, dcg_array
else:
return ndcg_array
def alpha_dcg_at_k(r_2d, k, method=1, alpha=0.5):
"""
:param r_2d: 2d relevance np array, shape: [num_trg_str, num_pred_str]
:param k:
:param method:
:param alpha:
:return:
"""
if r_2d.shape[-1] == 0:
alpha_dcg = 0.0
else:
# convert r_2d to gain vector
num_trg_str, num_pred_str = r_2d.shape
if k == 'M':
k = num_pred_str
elif k == 'G':
#k = num_trg_str
if num_pred_str < num_trg_str:
k = num_trg_str
else:
k = num_pred_str
if num_pred_str > k:
num_pred_str = k
gain_vector = np.zeros(num_pred_str)
one_minus_alpha_vec = np.ones(num_trg_str) * (1 - alpha) # [num_trg_str]
cum_r = np.concatenate((np.zeros((num_trg_str, 1)), np.cumsum(r_2d, axis=1)), axis=1)
for j in range(num_pred_str):
gain_vector[j] = np.dot(r_2d[:, j], np.power(one_minus_alpha_vec, cum_r[:, j]))
alpha_dcg = dcg_at_k(gain_vector, k, num_trg_str, method)
return alpha_dcg
def alpha_dcg_at_ks(r_2d, k_list, method=1, alpha=0.5):
"""
:param r_2d: 2d relevance np array, shape: [num_trg_str, num_pred_str]
:param ks:
:param method:
:param alpha:
:return:
"""
if r_2d.shape[-1] == 0:
return [0.0] * len(k_list)
# convert r_2d to gain vector
num_trg_str, num_pred_str = r_2d.shape
# k_max = max(k_list)
k_max = -1
for k in k_list:
if k == 'M':
k = num_pred_str
elif k == 'G':
#k = num_trg_str
if num_pred_str < num_trg_str:
k = num_trg_str
else:
k = num_pred_str
if k > k_max:
k_max = k
if num_pred_str > k_max:
num_pred_str = k_max
gain_vector = np.zeros(num_pred_str)
one_minus_alpha_vec = np.ones(num_trg_str) * (1 - alpha) # [num_trg_str]
cum_r = np.concatenate((np.zeros((num_trg_str, 1)), np.cumsum(r_2d, axis=1)), axis=1)
for j in range(num_pred_str):
gain_vector[j] = np.dot(r_2d[:, j], np.power(one_minus_alpha_vec, cum_r[:, j]))
return dcg_at_ks(gain_vector, k_list, num_trg_str, method)
def alpha_ndcg_at_k(r_2d, k, method=1, alpha=0.5, include_dcg=False):
"""
:param r_2d: 2d relevance np array, shape: [num_trg_str, num_pred_str]
:param k:
:param method:
:param alpha:
:return:
"""
if r_2d.shape[-1] == 0:
alpha_ndcg = 0.0
alpha_dcg = 0.0
else:
num_trg_str, num_pred_str = r_2d.shape
if k == 'M':
k = num_pred_str
elif k == 'G':
#k = num_trg_str
if num_pred_str < num_trg_str:
k = num_trg_str
else:
k = num_pred_str
# convert r to gain vector
alpha_dcg = alpha_dcg_at_k(r_2d, k, method, alpha)
# compute alpha_dcg_max
r_2d_ideal = compute_ideal_r_2d(r_2d, k, alpha)
alpha_dcg_max = alpha_dcg_at_k(r_2d_ideal, k, method, alpha)
if alpha_dcg_max <= 0.0:
alpha_ndcg = 0.0
else:
alpha_ndcg = alpha_dcg / alpha_dcg_max
alpha_ndcg = np.nan_to_num(alpha_ndcg)
if include_dcg:
return alpha_ndcg, alpha_dcg
else:
return alpha_ndcg
def alpha_ndcg_at_ks(r_2d, k_list, method=1, alpha=0.5, include_dcg=False):
"""
:param r_2d: 2d relevance np array, shape: [num_trg_str, num_pred_str]
:param k:
:param method:
:param alpha:
:return:
"""
if r_2d.shape[-1] == 0:
alpha_ndcg_array = [0] * len(k_list)
alpha_dcg_array = [0] * len(k_list)
else:
# k_max = max(k_list)
num_trg_str, num_pred_str = r_2d.shape
k_max = -1
for k in k_list:
if k == 'M':
k = num_pred_str
elif k == 'G':
#k = num_trg_str
if num_pred_str < num_trg_str:
k = num_trg_str
else:
k = num_pred_str
if k > k_max:
k_max = k
# convert r to gain vector
alpha_dcg_array = alpha_dcg_at_ks(r_2d, k_list, method, alpha)
# compute alpha_dcg_max
r_2d_ideal = compute_ideal_r_2d(r_2d, k_max, alpha)
alpha_dcg_max_array = alpha_dcg_at_ks(r_2d_ideal, k_list, method, alpha)
alpha_ndcg_array = alpha_dcg_array / alpha_dcg_max_array
alpha_ndcg_array = np.nan_to_num(alpha_ndcg_array)
if include_dcg:
return alpha_ndcg_array, alpha_dcg_array
else:
return alpha_ndcg_array
def compute_ideal_r_2d(r_2d, k, alpha=0.5):
num_trg_str, num_pred_str = r_2d.shape
one_minus_alpha_vec = np.ones(num_trg_str) * (1 - alpha) # [num_trg_str]
cum_r_vector = np.zeros((num_trg_str))
ideal_ranking = []
greedy_depth = min(num_pred_str, k)
for rank in range(greedy_depth):
gain_vector = np.zeros(num_pred_str)
for j in range(num_pred_str):
if j in ideal_ranking:
gain_vector[j] = -1000.0
else:
gain_vector[j] = np.dot(r_2d[:, j], np.power(one_minus_alpha_vec, cum_r_vector))
max_idx = np.argmax(gain_vector)
ideal_ranking.append(max_idx)
current_relevance_vector = r_2d[:, max_idx]
cum_r_vector = cum_r_vector + current_relevance_vector
return r_2d[:, np.array(ideal_ranking, dtype=int)]
def average_precision(r, num_predictions, num_trgs):
if num_predictions == 0 or num_trgs == 0:
return 0
r_cum_sum = np.cumsum(r, axis=0)
precision_sum = sum([compute_precision(r_cum_sum[k], k + 1) for k in range(num_predictions) if r[k]])
'''
precision_sum = 0
for k in range(num_predictions):
if r[k] is False:
continue
else:
precision_k = precision(r_cum_sum[k], k+1)
precision_sum += precision_k
'''
return precision_sum / num_trgs
def average_precision_at_k(r, k, num_predictions, num_trgs):
if k == 'M':
k = num_predictions
elif k == 'G':
#k = num_trgs
if num_predictions < num_trgs:
k = num_trgs
else:
k = num_predictions
if k < num_predictions:
num_predictions = k
r = r[:k]
return average_precision(r, num_predictions, num_trgs)
def average_precision_at_ks(r, k_list, num_predictions, num_trgs):
if num_predictions == 0 or num_trgs == 0:
return [0] * len(k_list)
# k_max = max(k_list)
k_max = -1
for k in k_list:
if k == 'M':
k = num_predictions
elif k == 'G':
#k = num_trgs
if num_predictions < num_trgs:
k = num_trgs
else:
k = num_predictions
if k > k_max:
k_max = k
if num_predictions > k_max:
num_predictions = k_max
r = r[:num_predictions]
r_cum_sum = np.cumsum(r, axis=0)
precision_array = [compute_precision(r_cum_sum[k], k + 1) * r[k] for k in range(num_predictions)]
precision_cum_sum = np.cumsum(precision_array, axis=0)
average_precision_array = precision_cum_sum / num_trgs
return_indices = []
for k in k_list:
if k == 'M':
k = num_predictions
elif k == 'G':
#k = num_trgs
if num_predictions < num_trgs:
k = num_trgs
else:
k = num_predictions
return_indices.append( (k-1) if k <= num_predictions else (num_predictions-1) )
return_indices = np.array(return_indices, dtype=int)
return average_precision_array[return_indices]
def find_v(f1_dict, num_samples, k_list, tag):
marco_f1_scores = np.zeros(len(k_list))
for i, topk in enumerate(k_list):
marco_avg_precision = f1_dict['precision_sum@{}_{}'.format(topk, tag)] / num_samples
marco_avg_recall = f1_dict['recall_sum@{}_{}'.format(topk, tag)] / num_samples
marco_f1_scores[i] = 2 * marco_avg_precision * marco_avg_recall / (marco_avg_precision + marco_avg_recall) if (marco_avg_precision + marco_avg_recall) > 0 else 0
# marco_f1_scores[i] = f1_dict['f1_score_sum@{}_{}'.format(topk, tag)] / num_samples
# for debug
print(marco_f1_scores)
return k_list[np.argmax(marco_f1_scores)]
def update_f1_dict(trg_token_2dlist_stemmed, pred_token_2dlist_stemmed, k_list, f1_dict, tag):
num_targets = len(trg_token_2dlist_stemmed)
num_predictions = len(pred_token_2dlist_stemmed)
is_match = compute_match_result(trg_token_2dlist_stemmed, pred_token_2dlist_stemmed,
type='exact', dimension=1)
# Classification metrics
precision_ks, recall_ks, f1_ks, num_matches_ks, num_predictions_ks = \
compute_classification_metrics_at_ks(is_match, num_predictions, num_targets, k_list=k_list, meng_rui_precision=opt.meng_rui_precision)
for topk, precision_k, recall_k in zip(k_list, precision_ks, recall_ks):
f1_dict['precision_sum@{}_{}'.format(topk, tag)] += precision_k
f1_dict['recall_sum@{}_{}'.format(topk, tag)] += recall_k
return f1_dict
def update_f1_dict_with_name_variation(trg_variation_token_3dlist, pred_token_2dlist, k_list, f1_dict, tag):
num_targets = len(trg_variation_token_3dlist)
num_predictions = len(pred_token_2dlist)
is_match = compute_var_match_result(trg_variation_token_3dlist, pred_token_2dlist)
# Classification metrics
precision_ks, recall_ks, f1_ks, num_matches_ks, num_predictions_ks = \
compute_classification_metrics_at_ks(is_match, num_predictions, num_targets, k_list=k_list,
meng_rui_precision=opt.meng_rui_precision)
for topk, precision_k, recall_k in zip(k_list, precision_ks, recall_ks):
f1_dict['precision_sum@{}_{}'.format(topk, tag)] += precision_k
f1_dict['recall_sum@{}_{}'.format(topk, tag)] += recall_k
return f1_dict
def update_score_dict(trg_token_2dlist_stemmed, pred_token_2dlist_stemmed, k_list, score_dict, tag):
num_targets = len(trg_token_2dlist_stemmed)
num_predictions = len(pred_token_2dlist_stemmed)
is_match = compute_match_result(trg_token_2dlist_stemmed, pred_token_2dlist_stemmed,
type='exact', dimension=1)
is_match_substring_2d = compute_match_result(trg_token_2dlist_stemmed,
pred_token_2dlist_stemmed, type='sub', dimension=2)
# Classification metrics
precision_ks, recall_ks, f1_ks, num_matches_ks, num_predictions_ks = \
compute_classification_metrics_at_ks(is_match, num_predictions, num_targets, k_list=k_list, meng_rui_precision=opt.meng_rui_precision)
# Ranking metrics
ndcg_ks, dcg_ks = ndcg_at_ks(is_match, k_list=k_list, num_trgs=num_targets, method=1, include_dcg=True)
alpha_ndcg_ks, alpha_dcg_ks = alpha_ndcg_at_ks(is_match_substring_2d, k_list=k_list, method=1,
alpha=0.5, include_dcg=True)
ap_ks = average_precision_at_ks(is_match, k_list=k_list,
num_predictions=num_predictions, num_trgs=num_targets)
for topk, precision_k, recall_k, f1_k, num_matches_k, num_predictions_k, ndcg_k, dcg_k, alpha_ndcg_k, alpha_dcg_k, ap_k in \
zip(k_list, precision_ks, recall_ks, f1_ks, num_matches_ks, num_predictions_ks, ndcg_ks, dcg_ks,
alpha_ndcg_ks, alpha_dcg_ks, ap_ks):
score_dict['precision@{}_{}'.format(topk, tag)].append(precision_k)
score_dict['recall@{}_{}'.format(topk, tag)].append(recall_k)
score_dict['f1_score@{}_{}'.format(topk, tag)].append(f1_k)
score_dict['num_matches@{}_{}'.format(topk, tag)].append(num_matches_k)
score_dict['num_predictions@{}_{}'.format(topk, tag)].append(num_predictions_k)
score_dict['num_targets@{}_{}'.format(topk, tag)].append(num_targets)
score_dict['AP@{}_{}'.format(topk, tag)].append(ap_k)
score_dict['NDCG@{}_{}'.format(topk, tag)].append(ndcg_k)
score_dict['AlphaNDCG@{}_{}'.format(topk, tag)].append(alpha_ndcg_k)
score_dict['num_targets_{}'.format(tag)].append(num_targets)
score_dict['num_predictions_{}'.format(tag)].append(num_predictions)
return score_dict
def update_score_dict_with_name_variation_backup(is_match_all, pred_indices, num_predictions, num_targets, k_list, score_dict, tag):
assert len(pred_indices) == num_predictions
is_match = is_match_all[pred_indices]
# Classification metrics
precision_ks, recall_ks, f1_ks, num_matches_ks, num_predictions_ks = \
compute_classification_metrics_at_ks(is_match, num_predictions, num_targets, k_list=k_list,
meng_rui_precision=opt.meng_rui_precision)
for topk, precision_k, recall_k, f1_k, num_matches_k, num_predictions_k in \
zip(k_list, precision_ks, recall_ks, f1_ks, num_matches_ks, num_predictions_ks):
score_dict['precision@{}_{}'.format(topk, tag)].append(precision_k)
score_dict['recall@{}_{}'.format(topk, tag)].append(recall_k)
score_dict['f1_score@{}_{}'.format(topk, tag)].append(f1_k)
score_dict['num_matches@{}_{}'.format(topk, tag)].append(num_matches_k)
score_dict['num_predictions@{}_{}'.format(topk, tag)].append(num_predictions_k)
score_dict['num_targets@{}_{}'.format(topk, tag)].append(num_targets)
return score_dict
def update_score_dict_with_name_variation(trg_variation_token_3dlist, pred_token_2dlist, k_list, score_dict, tag):
num_targets = len(trg_variation_token_3dlist)
num_predictions = len(pred_token_2dlist)
is_match = compute_var_match_result(trg_variation_token_3dlist, pred_token_2dlist)
# Classification metrics
precision_ks, recall_ks, f1_ks, num_matches_ks, num_predictions_ks = \
compute_classification_metrics_at_ks(is_match, num_predictions, num_targets, k_list=k_list,
meng_rui_precision=opt.meng_rui_precision)
for topk, precision_k, recall_k, f1_k, num_matches_k, num_predictions_k in \
zip(k_list, precision_ks, recall_ks, f1_ks, num_matches_ks, num_predictions_ks):
score_dict['precision@{}_{}'.format(topk, tag)].append(precision_k)
score_dict['recall@{}_{}'.format(topk, tag)].append(recall_k)
score_dict['f1_score@{}_{}'.format(topk, tag)].append(f1_k)
score_dict['num_matches@{}_{}'.format(topk, tag)].append(num_matches_k)
score_dict['num_predictions@{}_{}'.format(topk, tag)].append(num_predictions_k)
score_dict['num_targets@{}_{}'.format(topk, tag)].append(num_targets)
return score_dict
def compute_var_match_result(trg_variation_token_3dlist, pred_token_2dlist):
num_pred = len(pred_token_2dlist)
num_trg = len(trg_variation_token_3dlist)
is_match = np.zeros(num_pred, dtype=bool)
for pred_idx, pred_token_list in enumerate(pred_token_2dlist):
joined_pred_token_list = ' '.join(pred_token_list)
match_flag = False
for trg_idx, trg_variation_token_2dlist in enumerate(trg_variation_token_3dlist):
for trg_variation_token_list in trg_variation_token_2dlist:
joined_trg_variation_token_list = ' '.join(trg_variation_token_list)
if joined_pred_token_list == joined_trg_variation_token_list:
is_match[pred_idx] = True
match_flag = True
break
if match_flag:
break
return is_match
def filter_prediction(disable_valid_filter, disable_extra_one_word_filter, pred_token_2dlist_stemmed):
"""
Remove the duplicate predictions, can optionally remove invalid predictions and extra one word predictions
:param disable_valid_filter:
:param disable_extra_one_word_filter:
:param pred_token_2dlist_stemmed:
:param pred_token_2d_list:
:return:
"""
num_predictions = len(pred_token_2dlist_stemmed)
is_unique_mask = check_duplicate_keyphrases(pred_token_2dlist_stemmed) # boolean array, 1=unqiue, 0=duplicate
pred_filter = is_unique_mask
if not disable_valid_filter:
is_valid_mask = check_valid_keyphrases(pred_token_2dlist_stemmed)
pred_filter = pred_filter * is_valid_mask
if not disable_extra_one_word_filter:
extra_one_word_seqs_mask, num_one_word_seqs = compute_extra_one_word_seqs_mask(pred_token_2dlist_stemmed)
pred_filter = pred_filter * extra_one_word_seqs_mask
filtered_stemmed_pred_str_list = [word_list for word_list, is_keep in
zip(pred_token_2dlist_stemmed, pred_filter) if
is_keep]
num_duplicated_predictions = num_predictions - np.sum(is_unique_mask)
return filtered_stemmed_pred_str_list, num_duplicated_predictions
def find_unique_target(trg_token_2dlist_stemmed):
"""
Remove the duplicate targets
:param trg_token_2dlist_stemmed:
:return:
"""
num_trg = len(trg_token_2dlist_stemmed)
is_unique_mask = check_duplicate_keyphrases(trg_token_2dlist_stemmed) # boolean array, 1=unqiue, 0=duplicate
trg_filter = is_unique_mask
filtered_stemmed_trg_str_list = [word_list for word_list, is_keep in
zip(trg_token_2dlist_stemmed, trg_filter) if
is_keep]
num_duplicated_trg = num_trg - np.sum(is_unique_mask)
return filtered_stemmed_trg_str_list, num_duplicated_trg
def separate_present_absent_by_source(src_token_list_stemmed, keyphrase_token_2dlist_stemmed, match_by_str):
is_present_mask = check_present_keyphrases(src_token_list_stemmed, keyphrase_token_2dlist_stemmed, match_by_str)
present_keyphrase_token2dlist = []
absent_keyphrase_token2dlist = []
for keyphrase_token_list, is_present in zip(keyphrase_token_2dlist_stemmed, is_present_mask):
if is_present:
present_keyphrase_token2dlist.append(keyphrase_token_list)
else:
absent_keyphrase_token2dlist.append(keyphrase_token_list)
return present_keyphrase_token2dlist, absent_keyphrase_token2dlist
def separate_present_absent_by_segmenter(keyphrase_token_2dlist, segmenter):
present_keyphrase_token2dlist = []
absent_keyphrase_token2dlist = []
absent_flag = False
for keyphrase_token_list in keyphrase_token_2dlist:
if keyphrase_token_list[0] == segmenter:
absent_flag = True
# skip the segmenter token, because it should not be included in the evaluation
continue
if absent_flag:
absent_keyphrase_token2dlist.append(keyphrase_token_list)
else: