-
Notifications
You must be signed in to change notification settings - Fork 6
/
evaluate_prediction.py
1730 lines (1510 loc) · 79 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
from collections import defaultdict
import os
# import pykp.utils.io as io
UNK_WORD = '<unk>'
import pickle
from nltk.stem.porter import *
stemmer = PorterStemmer()
def stem_str_2d_list(str_2dlist):
# stem every word in a list of word list
# str_list is a list of word list
stemmed_str_2dlist = []
for str_list in str_2dlist:
stemmed_str_list = [stem_word_list(word_list) for word_list in str_list]
stemmed_str_2dlist.append(stemmed_str_list)
return stemmed_str_2dlist
def stem_str_list(str_list):
# stem every word in a list of word list
# str_list is a list of word list
stemmed_str_list = []
for word_list in str_list:
stemmed_word_list = stem_word_list(word_list)
stemmed_str_list.append(stemmed_word_list)
return stemmed_str_list
def stem_word_list(word_list):
return [stemmer.stem(w.strip().lower()) for w in word_list]
def prediction_to_sentence(prediction, idx2word, vocab_size, oov, eos_idx, unk_idx=None, replace_unk=False,
src_word_list=None, attn_dist=None):
"""
:param prediction: a list of 0 dim tensor
:param attn_dist: tensor with size [trg_len, src_len]
:return: a list of words, does not include the final EOS
"""
sentence = []
for i, pred in enumerate(prediction):
_pred = int(pred.item()) # convert zero dim tensor to int
if i == len(prediction) - 1 and _pred == eos_idx: # ignore the final EOS token
break
if _pred < vocab_size:
if _pred == unk_idx and replace_unk:
assert src_word_list is not None and attn_dist is not None, \
"If you need to replace unk, you must supply src_word_list and attn_dist"
_, max_attn_idx = attn_dist[i].topk(2, dim=0)
if max_attn_idx[0] < len(src_word_list):
word = src_word_list[int(max_attn_idx[0].item())]
else:
word = src_word_list[int(max_attn_idx[1].item())]
else:
word = idx2word[_pred]
else:
word = oov[_pred - vocab_size]
sentence.append(word)
return sentence
def split_word_list_by_delimiter(word_list, keyphrase_delimiter):
"""
Convert a word list into a list of keyphrase, each keyphrase is a word list.
:param word_list: word list of concated keyprhases, separated by a delimiter
:param keyphrase_delimiter
:return: a list of keyphrase, each keyphrase is a word list.
"""
tmp_pred_str_list = []
tmp_word_list = []
for word in word_list:
if word == keyphrase_delimiter:
if len(tmp_word_list) > 0:
tmp_pred_str_list.append(tmp_word_list)
tmp_word_list = []
else:
tmp_word_list.append(word)
if len(tmp_word_list) > 0: # append the final keyphrase to the pred_str_list
tmp_pred_str_list.append(tmp_word_list)
return tmp_pred_str_list
def split_word_list_from_set(word_list, decoder_score, max_kp_len, max_kp_num, end_word, null_word):
pred_str_list = []
kp_scores = []
tmp_score = 0
tmp_word_list = []
for kp_start_idx in range(0, max_kp_len * max_kp_num, max_kp_len):
for word, score in zip(word_list[kp_start_idx:kp_start_idx + max_kp_len],
decoder_score[kp_start_idx:kp_start_idx + max_kp_len]):
if word == null_word:
tmp_word_list = []
tmp_score = 0
break
elif word == end_word:
if len(tmp_word_list) > 0:
pred_str_list.append(tmp_word_list)
kp_scores.append(tmp_score / len(tmp_word_list))
tmp_word_list = []
tmp_score = 0
break
else:
tmp_word_list.append(word)
tmp_score += score
if len(tmp_word_list) > 0: # append the final keyphrase to the pred_str_list
pred_str_list.append(tmp_word_list)
kp_scores.append(tmp_score / len(tmp_word_list))
tmp_word_list = []
tmp_score = 0
if pred_str_list: # sorting by score for F1@5
seq_pairs = sorted(zip(kp_scores, pred_str_list), key=lambda p: -p[0])
kp_scores, pred_str_list = zip(*seq_pairs)
return pred_str_list
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 == 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_duplicate_shorter_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()
longer_to_short = np.array([len(i) for i in keyphrase_str_list]).argsort()[::-1]
for i in longer_to_short:
kp = keyphrase_str_list[i]
if '_'.join(kp) in keyphrase_set:
not_duplicate[i] = False
else:
not_duplicate[i] = True
for inner_kp_len in range(1, len(kp) + 1):
for inner_kp_start in range(0, len(kp) - inner_kp_len + 1):
keyphrase_set.add('_'.join(kp[inner_kp_start:inner_kp_start + inner_kp_len]))
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)