-
Notifications
You must be signed in to change notification settings - Fork 0
/
evaluate_prediction.py
2504 lines (2230 loc) · 106 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
import torch
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_token_level_reward_edit_distance(trg_word_list, pred_word_list):
#编辑距离
add_score = 1.0
del_score = 1.0
exc_score = 1.0
threshold_pos = 1.0
threshold_neg = 0.0
assert threshold_pos > threshold_neg
len_trg = len(trg_word_list)
len_pred = len(pred_word_list)
max_score = max(add_score, del_score, exc_score) * max(len_trg, len_pred)
dp = np.zeros((len_pred + 3, len_trg + 3))
for idx in range(1, len_pred + 1):
dp[idx][0] = idx
for idy in range(1, len_trg + 1):
dp[0][idy] = idy
for pred_idx, pred_word in enumerate(pred_word_list):
for trg_idx, trg_word in enumerate(trg_word_list):
if trg_word == pred_word:
dp[pred_idx + 1][trg_idx + 1] = dp[pred_idx][trg_idx]
else:
dp[pred_idx + 1][trg_idx + 1] = min(dp[pred_idx][trg_idx + 1] + add_score,
dp[pred_idx + 1][trg_idx] + del_score,
dp[pred_idx][trg_idx] + exc_score)
score = max(max_score - dp[len_pred][len_trg], 0) / max(max_score, 1e-5)
score = 1.0 if score >= threshold_pos else score
score = 0.0 if score <= threshold_neg else score
return score
def compute_token_level_reward_token_f1(trg_word_list, pred_word_list):
num_accurary = 0
rest_trg_word_list = [trg for trg in trg_word_list]
for pred_idx, pred_word in enumerate(pred_word_list):
if pred_word in rest_trg_word_list:
num_accurary += 1
idx = rest_trg_word_list.index(pred_word)
rest_trg_word_list.pop(idx)
precision = 1.0 * num_accurary / max(len(pred_word_list), 1)
recall = 1.0 * num_accurary / max(len(trg_word_list), 1)
F1_score = 2 * precision * recall / max(precision + recall, 1e-5)
return F1_score
##evaluate
def compute_token_level_token_f1(trg_word_list, pred_word_list):
num_accurary = 0
rest_trg_word_list = [trg for trg in trg_word_list]
for pred_idx, pred_word in enumerate(pred_word_list):
if pred_word in rest_trg_word_list:
num_accurary += 1
idx = rest_trg_word_list.index(pred_word)
rest_trg_word_list.pop(idx)
precision = 1.0 * num_accurary / max(len(pred_word_list), 1)
recall = 1.0 * num_accurary / max(len(trg_word_list), 1)
F1_score = 2 * precision * recall / max(precision + recall, 1e-5)
return F1_score, precision, recall
def compute_cp(trg_word_list, pred_word_list):
alpha = 1.0
beta = 2.0
cur_edit_distance_score = compute_token_level_reward_edit_distance(trg_word_list, pred_word_list)
cur_token_f1_score = compute_token_level_reward_token_f1(trg_word_list, pred_word_list)
cur_score = (alpha * cur_edit_distance_score + beta * cur_token_f1_score) / (alpha + beta)
return cur_score
def compute_phrase_level_reward(trg_str_list, pred_str_list, token_reward_type, bert = None):
num_pred_str = len(pred_str_list)
num_trg_str = len(trg_str_list)
score = np.zeros(num_pred_str)
if num_pred_str == 0 or num_trg_str == 0:
if num_pred_str > 0:
return -0.01
return 0.
###
# need_to_write = True
# file_size = os.path.getsize('/remote-home/ygxu/workspace/KG/KGM/score_data.txt')
# if need_to_write:
# f = open('/remote-home/ygxu/workspace/KG/KGM/score_data.txt', 'a+')
# else:
# f = None
###
if token_reward_type == 5:
bert_input_words = []
bert_input_padded_words = []
bert_max_len = 0
for target_list in trg_str_list:
for predicted_list in pred_str_list:
bert_words = f'{" ".join(target_list)} [SEP] {" ".join(predicted_list)}'
bert_input_instance = [bert.vocab.to_index(w) for w in bert_words.split(' ')]
bert_max_len = max(bert_max_len, len(bert_input_instance))
bert_input_words.append(bert_input_instance)
for ins in bert_input_words:
new_ins = ins + [bert.vocab.padding_idx] * (bert_max_len - len(ins))
bert_input_padded_words.append(new_ins)
bert_input_padded_words = torch.tensor(bert_input_padded_words)
if torch.cuda.is_available():
bert_input_padded_words = bert_input_padded_words.cuda()
with torch.no_grad():
predicted_score = bert(bert_input_padded_words)[0] # [pred * trg, 3]
predicted_score = predicted_score.view(num_pred_str, num_trg_str, -1)[:, :, 0].max(dim=1)[0]
score = predicted_score.cpu().detach().numpy()
original_score = np.sum(score) / max(num_pred_str, 1.0)
# corr = - ((num_trg_str - num_pred_str) ** 2) / (max(num_trg_str, 1) ** 2) + 1
if num_pred_str < num_trg_str:
# corr = num_pred_str / max(num_trg_str, 1)
corr = (num_pred_str ** 2) / (max(num_trg_str, 1) ** 2)
elif num_pred_str == num_trg_str:
corr = 1.
else:
corr = - ((num_trg_str - num_pred_str) ** 2) / (max(num_trg_str, 1) ** 2) + 1
return original_score * corr
for pred_idx, pred_word_list in enumerate(pred_str_list):
max_score = 0.0
for trg_idx, trg_word_list in enumerate(trg_str_list):
if token_reward_type == 1:
cur_score = compute_token_level_reward_edit_distance(trg_word_list, pred_word_list)
elif token_reward_type == 2:
cur_score = compute_token_level_reward_token_f1(trg_word_list, pred_word_list)
elif token_reward_type == 3:
cur_score = compute_cp(trg_word_list, pred_word_list)
elif token_reward_type == 4:
with torch.no_grad():
score_tmp, _ = bert(' '.join(pred_word_list), ' '.join(trg_word_list))
cur_score = float(score_tmp[0][0])
###
# token_f1_score = compute_token_level_reward_token_f1(trg_word_list, pred_word_list)
# example = f'{" ".join(trg_word_list)}\t{" ".join(pred_word_list)}\t{cur_score}\t{token_f1_score}\n'
# if f is not None and file_size < 1024 ** 3:
# f.write(example)
###
max_score = max(max_score, cur_score)
score[pred_idx] = max_score
original_score = np.sum(score) / max(num_pred_str, 1.0)
###
# if f is not None:
# f.close()
###
# corr = - ((num_trg_str - num_pred_str) ** 2) / (max(num_trg_str, 1) ** 2) + 1
if num_pred_str < num_trg_str:
#corr = num_pred_str / max(num_trg_str, 1)
corr = (num_pred_str ** 2) / (max(num_trg_str, 1) ** 2)
elif num_pred_str == num_trg_str:
corr = 1.
else:
corr = - ((num_trg_str - num_pred_str) ** 2) / (max(num_trg_str, 1) ** 2) + 1.
return original_score * corr
def compute_phrase_level_reward_15(trg_str_list, pred_str_list, token_reward_type, bert=None):
num_pred_str = len(pred_str_list)
num_trg_str = len(trg_str_list)
score = np.zeros(num_pred_str)
if num_pred_str == 0 or num_trg_str == 0:
if num_pred_str > 0:
return -0.01
return 0.
for pred_idx, pred_word_list in enumerate(pred_str_list):
max_score = 0.0
for trg_idx, trg_word_list in enumerate(trg_str_list):
if token_reward_type == 1:
cur_score = compute_token_level_reward_edit_distance(trg_word_list, pred_word_list)
elif token_reward_type == 2:
cur_score = compute_token_level_reward_token_f1(trg_word_list, pred_word_list)
elif token_reward_type == 3:
cur_score = compute_cp(trg_word_list, pred_word_list)
elif token_reward_type == 4:
with torch.no_grad():
score_tmp, _ = bert(' '.join(pred_word_list), ' '.join(trg_word_list))
cur_score = float(score_tmp[0][0])
max_score = max(max_score, cur_score)
score[pred_idx] = max_score
original_score = np.sum(score) / max(num_pred_str, 1.0)
# corr = - ((num_trg_str - num_pred_str) ** 2) / (max(num_trg_str, 1) ** 2) + 1
if num_pred_str <= num_trg_str + 1:
# corr = num_pred_str / max(num_trg_str, 1)
corr = (num_pred_str ** 2) / (max(num_trg_str, 1) ** 2)
else:
corr = - ((num_trg_str - num_pred_str) ** 2) / (max(num_trg_str, 1) ** 2) + 1.
return original_score * corr
def compute_phrase_level_reward_add(trg_str_list, pred_str_list, token_reward_type = 1):
num_pred_str = len(pred_str_list)
num_trg_str = len(trg_str_list)
if num_pred_str == 0: #no trg or no pred
if num_trg_str == 0:
return 0.5
else:
return 0.
score = np.zeros(num_pred_str)
threshold = 0.1
punishment = -0.05
for pred_idx, pred_word_list in enumerate(pred_str_list):
max_score = 0.0
for trg_idx, trg_word_list in enumerate(trg_str_list):
if token_reward_type == 1:
cur_score = compute_token_level_reward_edit_distance(trg_word_list, pred_word_list)
elif token_reward_type == 2:
cur_score = compute_token_level_reward_token_f1(trg_word_list, pred_word_list)
elif token_reward_type == 3:
cur_score = compute_cp(trg_word_list, pred_word_list)
max_score = max(max_score, cur_score)
score[pred_idx] = max_score
if score[pred_idx] <= threshold:
score[pred_idx] = punishment
original_score = np.sum(score)
return original_score
def compute_phrase_level_reward_add_coverage(trg_str_list, pred_str_list):
num_pred_str = len(pred_str_list)
num_trg_str = len(trg_str_list)
if num_pred_str == 0: #no trg or no pred
if num_trg_str == 0:
return 0.5
else:
return 0.
score = np.zeros(num_pred_str)
threshold = 0.1
punishment = -0.05
punishment_repeat = -0.3
dict_trg = {}
dict_pred = {}
for trg_idx, trg_word_list in enumerate(trg_str_list):
for word_idx, trg_word in enumerate(trg_word_list):
if trg_word in dict_trg:
dict_trg[trg_word] += 1
else:
dict_trg[trg_word] = 1
for pred_idx, pred_word_list in enumerate(pred_str_list):
max_score = 0.0
for trg_idx, trg_word_list in enumerate(trg_str_list):
# if token_reward_type == 1:
cur_score = compute_token_level_reward_edit_distance(trg_word_list, pred_word_list)
# elif token_reward_type == 2:
# cur_score = compute_token_level_reward_token_f1(trg_word_list, pred_word_list)
# elif token_reward_type == 3:
# cur_score = compute_cp(trg_word_list, pred_word_list)
max_score = max(max_score, cur_score)
score[pred_idx] = max_score
if score[pred_idx] <= threshold:
score[pred_idx] = punishment
repeat_fa = 0
for pred_word_idx, pred_word in enumerate(pred_word_list):
if pred_word not in dict_trg:
pass
# #不出现在trg里的重复惩罚
# if pred_word in dict_pred:
# repeat_fa = 1
# break
# else:
# dict_pred[pred_word] = 1
else:
if pred_word not in dict_pred:
dict_pred[pred_word] = 1
else:
dict_pred[pred_word] += 1
if(dict_pred[pred_word] > dict_trg[pred_word]):
repeat_fa = 1
break
if repeat_fa == 1:
score[pred_idx] = punishment_repeat
original_score = np.sum(score)
return original_score
def compute_phrase_level_reward_add_coverage_descending(trg_str_list, pred_str_list):
num_pred_str = len(pred_str_list)
num_trg_str = len(trg_str_list)
if num_pred_str == 0: #no trg or no pred
if num_trg_str == 0:
return 0.5
else:
return 0.
score = np.zeros(num_pred_str)
score_final = np.zeros(num_pred_str)
threshold = 0.1
punishment = -0.05
punishment_repeat = -0.3
dict_trg = {}
dict_pred = {}
for trg_idx, trg_word_list in enumerate(trg_str_list):
for word_idx, trg_word in enumerate(trg_word_list):
if trg_word in dict_trg:
dict_trg[trg_word] += 1
else:
dict_trg[trg_word] = 1
pred_score_tuple = []
for pred_idx, pred_word_list in enumerate(pred_str_list):
max_score = 0.0
for trg_idx, trg_word_list in enumerate(trg_str_list):
# if token_reward_type == 1:
cur_score = compute_token_level_reward_edit_distance(trg_word_list, pred_word_list)
# elif token_reward_type == 2:
# cur_score = compute_token_level_reward_token_f1(trg_word_list, pred_word_list)
# elif token_reward_type == 3:
# cur_score = compute_cp(trg_word_list, pred_word_list)
max_score = max(max_score, cur_score)
score[pred_idx] = max_score
if score[pred_idx] <= threshold:
score[pred_idx] = punishment
pred_score_tuple.append((pred_str_list[pred_idx], score[pred_idx]))
#pred_score_tuple 逆序排序
pred_score_tuple = sorted(pred_score_tuple, key=lambda x: x[1])
pred_score_tuple.reverse()
for tp_idx, tp in enumerate(pred_score_tuple):
pred_word_list, score_tmp = tp
#print(pred_word_list)
#print(score_tmp)
repeat_fa = 0
for pred_word_idx, pred_word in enumerate(pred_word_list):
if pred_word not in dict_trg:
pass
# #不出现在trg里的重复惩罚
# if pred_word in dict_pred:
# repeat_fa = 1
# break
# else:
# dict_pred[pred_word] = 1
else:
if pred_word not in dict_pred:
dict_pred[pred_word] = 1
else:
dict_pred[pred_word] += 1
if(dict_pred[pred_word] > dict_trg[pred_word]):
repeat_fa = 1
break
if repeat_fa == 1:
score_final[tp_idx] = punishment_repeat
else:
score_final[tp_idx] = score_tmp
#print(score_final)
original_score = np.sum(score_final)
return original_score
def compute_fg_score_k(trg_str_list, pred_str_list, eva = 0):
num_pred_str = len(pred_str_list)
num_trg_str = len(trg_str_list)
tmp_stat_token_f1 = [0] * 12
# no trg or no pred
if num_pred_str == 0 and num_trg_str == 0:
if eva == 1:
return 1.0, 0.0, 0.0, 0.0, tmp_stat_token_f1, num_pred_str
else:
return 0.5
if num_pred_str == 0:
if eva == 1:
return 0.0, 0.0, 0.0, 0.0, tmp_stat_token_f1, num_pred_str
else:
return 0.0
if num_trg_str == 0:
if eva == 1:
return 0.0, 0.0, 0.0, 0.0, tmp_stat_token_f1, num_pred_str
else:
return 0.0
###
# need_to_write = True
# file_size = os.path.getsize('/remote-home/ygxu/workspace/KG/KGM/score_data.txt')
# if need_to_write:
# f = open('/remote-home/ygxu/workspace/KG/KGM/score_data.txt', 'a+')
# else:
# f = None
###
##
# need_to_write = True
# file_size = os.path.getsize('/remote-home/ygxu/workspace/KG/KGM/score_data_new.txt')
# if need_to_write:
# f = open('/remote-home/ygxu/workspace/KG/KGM/score_data_new.txt', 'a+')
# else:
# f = None
##
score = np.zeros(num_pred_str)
score_final = np.zeros(num_pred_str)
threshold = 0.1
#punishment = -0.05
#punishment_repeat = -0.3
dict_trg = {}
dict_pred = {}
for trg_idx, trg_word_list in enumerate(trg_str_list):
for word_idx, trg_word in enumerate(trg_word_list):
if trg_word in dict_trg:
dict_trg[trg_word] += 1
else:
dict_trg[trg_word] = 1
pred_score_tuple = []
if eva == 1:
total_tk_f1 = 0.0
total_tk_p = 0.0
total_tk_r = 0.0
for pred_idx, pred_word_list in enumerate(pred_str_list):
max_score = 0.0
max_idx = 0
for trg_idx, trg_word_list in enumerate(trg_str_list):
# if token_reward_type == 1:
cur_score_ed = compute_token_level_reward_edit_distance(trg_word_list, pred_word_list)
# elif token_reward_type == 2:
cur_score_tf = compute_token_level_reward_token_f1(trg_word_list, pred_word_list)
cur_score = (cur_score_ed + cur_score_tf) / 2.0
if(cur_score > max_score):
max_score = cur_score
max_idx = trg_idx
score[pred_idx] = max_score
if eva == 1:
tk_f1, tk_p, tk_r = compute_token_level_token_f1(trg_str_list[max_idx], pred_word_list)
total_tk_f1 += tk_f1
total_tk_p += tk_p
total_tk_r += tk_r
if tk_f1 == 0.:
tmp_stat_token_f1[0] += 1
elif 0 < tk_f1 <= 0.1:
tmp_stat_token_f1[1] += 1
elif 0 < tk_f1 <= 0.2:
tmp_stat_token_f1[2] += 1
elif 0 < tk_f1 <= 0.3:
tmp_stat_token_f1[3] += 1
elif 0 < tk_f1 <= 0.4:
tmp_stat_token_f1[4] += 1
elif 0 < tk_f1 <= 0.5:
tmp_stat_token_f1[5] += 1
elif 0 < tk_f1 <= 0.6:
tmp_stat_token_f1[6] += 1
elif 0 < tk_f1 <= 0.7:
tmp_stat_token_f1[7] += 1
elif 0 < tk_f1 <= 0.8:
tmp_stat_token_f1[8] += 1
elif 0 < tk_f1 <= 0.9:
tmp_stat_token_f1[9] += 1
elif 0 < tk_f1 < 1.:
tmp_stat_token_f1[10] += 1
elif tk_f1 == 1.:
tmp_stat_token_f1[11] += 1
###
# if f is not None:
# if file_size > 1024 **2 * 20:
# exit(0)
# strs = f'{" ".join(trg_str_list[max_idx])}\t{" ".join(pred_word_list)}\n'
# f.write(strs)
###
if score[pred_idx] <= threshold:
score[pred_idx] = 0.0
pred_score_tuple.append((pred_str_list[pred_idx], score[pred_idx]))
###
# if f is not None:
# f.close()
###
#pred_score_tuple 逆序排序
pred_score_tuple = sorted(pred_score_tuple, key=lambda x: x[1])
pred_score_tuple.reverse()
for tp_idx, tp in enumerate(pred_score_tuple):
pred_word_list, score_tmp = tp
#print(pred_word_list)
#print(score_tmp)
repeat_fa = 0
for pred_word_idx, pred_word in enumerate(pred_word_list):
if pred_word not in dict_trg:
pass
# #不出现在trg里的重复惩罚
# if pred_word in dict_pred:
# repeat_fa = 1
# break
# else:
# dict_pred[pred_word] = 1
else:
if pred_word not in dict_pred:
dict_pred[pred_word] = 1
else:
dict_pred[pred_word] += 1
if(dict_pred[pred_word] > dict_trg[pred_word]):
repeat_fa = 1
if repeat_fa == 1:
score_final[tp_idx] = 0.0
for pred_word_idx, pred_word in enumerate(pred_word_list):
if pred_word in dict_trg:
dict_pred[pred_word] -= 1
else:
score_final[tp_idx] = score_tmp
#print(score_final)
original_score = np.sum(score_final) / num_pred_str
corr = 1.0 - ((num_trg_str - num_pred_str) ** 2) / (max(num_trg_str, num_pred_str, 1) ** 2)
###
# token_f1_score = compute_token_level_reward_token_f1(trg_word_list, pred_word_list)
# example = f'{" ".join(trg_word_list)}\t{" ".join(pred_word_list)}\t{cur_score}\t{token_f1_score}\n'
# if f is not None and file_size < 1024 ** 3:
# f.write(example)
###
if eva == 0:
return original_score * corr
else:
# final_token_f1 = total_tk_f1 / max(num_pred_str, 1)
# final_token_p = total_tk_p / max(num_pred_str, 1)
# final_token_r = total_tk_r / max(num_pred_str, 1)
# return original_score * corr, final_token_f1, final_token_p, final_token_r, tmp_stat_token_f1
return original_score * corr, total_tk_f1, total_tk_p, total_tk_r, tmp_stat_token_f1, num_pred_str
def compute_fg_score_k1(trg_str_list, pred_str_list, eva = 0):
#delete edit distance
num_pred_str = len(pred_str_list)
num_trg_str = len(trg_str_list)
# no trg or no pred
if num_pred_str == 0 and num_trg_str == 0:
if eva == 1:
return 1.0
else:
return 0.5
if num_pred_str == 0:
return 0.0
if num_trg_str == 0:
return 0.0
score = np.zeros(num_pred_str)
score_final = np.zeros(num_pred_str)
threshold = 0.1
#punishment = -0.05
#punishment_repeat = -0.3
dict_trg = {}
dict_pred = {}
for trg_idx, trg_word_list in enumerate(trg_str_list):
for word_idx, trg_word in enumerate(trg_word_list):
if trg_word in dict_trg:
dict_trg[trg_word] += 1
else:
dict_trg[trg_word] = 1
pred_score_tuple = []
for pred_idx, pred_word_list in enumerate(pred_str_list):
max_score = 0.0
max_idx = 0
for trg_idx, trg_word_list in enumerate(trg_str_list):
# if token_reward_type == 1:
#cur_score_ed = compute_token_level_reward_edit_distance(trg_word_list, pred_word_list)
# elif token_reward_type == 2:
cur_score_tf = compute_token_level_reward_token_f1(trg_word_list, pred_word_list)
#cur_score = (cur_score_ed + cur_score_tf) / 2.0
cur_score = cur_score_tf
if(cur_score > max_score):
max_score = cur_score
max_idx = trg_idx
score[pred_idx] = max_score
###
# if f is not None:
# if file_size > 1024 **2 * 20:
# exit(0)
# strs = f'{" ".join(trg_str_list[max_idx])}\t{" ".join(pred_word_list)}\n'
# f.write(strs)
###
if score[pred_idx] <= threshold:
score[pred_idx] = 0.0
pred_score_tuple.append((pred_str_list[pred_idx], score[pred_idx]))
###
# if f is not None:
# f.close()
###
#pred_score_tuple 逆序排序
pred_score_tuple = sorted(pred_score_tuple, key=lambda x: x[1])
pred_score_tuple.reverse()
for tp_idx, tp in enumerate(pred_score_tuple):
pred_word_list, score_tmp = tp
#print(pred_word_list)
#print(score_tmp)
repeat_fa = 0
for pred_word_idx, pred_word in enumerate(pred_word_list):
if pred_word not in dict_trg:
pass
# #不出现在trg里的重复惩罚
# if pred_word in dict_pred:
# repeat_fa = 1
# break
# else:
# dict_pred[pred_word] = 1
else:
if pred_word not in dict_pred:
dict_pred[pred_word] = 1
else:
dict_pred[pred_word] += 1
if(dict_pred[pred_word] > dict_trg[pred_word]):
repeat_fa = 1
if repeat_fa == 1:
score_final[tp_idx] = 0.0
for pred_word_idx, pred_word in enumerate(pred_word_list):
if pred_word in dict_trg:
dict_pred[pred_word] -= 1
else:
score_final[tp_idx] = score_tmp
#print(score_final)
original_score = np.sum(score_final) / num_pred_str
corr = 1.0 - ((num_trg_str - num_pred_str) ** 2) / (max(num_trg_str, num_pred_str, 1) ** 2)
###
# token_f1_score = compute_token_level_reward_token_f1(trg_word_list, pred_word_list)
# example = f'{" ".join(trg_word_list)}\t{" ".join(pred_word_list)}\t{cur_score}\t{token_f1_score}\n'
# if f is not None and file_size < 1024 ** 3:
# f.write(example)
###
return original_score * corr
def compute_fg_score_k2(trg_str_list, pred_str_list, eva = 0):
#delete TF1
num_pred_str = len(pred_str_list)
num_trg_str = len(trg_str_list)
# no trg or no pred
if num_pred_str == 0 and num_trg_str == 0:
if eva == 1:
return 1.0
else:
return 0.5
if num_pred_str == 0:
return 0.0
if num_trg_str == 0:
return 0.0
score = np.zeros(num_pred_str)
score_final = np.zeros(num_pred_str)
threshold = 0.1
#punishment = -0.05
#punishment_repeat = -0.3
dict_trg = {}
dict_pred = {}
for trg_idx, trg_word_list in enumerate(trg_str_list):
for word_idx, trg_word in enumerate(trg_word_list):
if trg_word in dict_trg:
dict_trg[trg_word] += 1
else:
dict_trg[trg_word] = 1
pred_score_tuple = []
for pred_idx, pred_word_list in enumerate(pred_str_list):
max_score = 0.0
max_idx = 0
for trg_idx, trg_word_list in enumerate(trg_str_list):
# if token_reward_type == 1:
cur_score_ed = compute_token_level_reward_edit_distance(trg_word_list, pred_word_list)
# elif token_reward_type == 2:
#cur_score_tf = compute_token_level_reward_token_f1(trg_word_list, pred_word_list)
#cur_score = (cur_score_ed + cur_score_tf) / 2.0
cur_score = cur_score_ed
if(cur_score > max_score):
max_score = cur_score
max_idx = trg_idx
score[pred_idx] = max_score
if score[pred_idx] <= threshold:
score[pred_idx] = 0.0
pred_score_tuple.append((pred_str_list[pred_idx], score[pred_idx]))
###
# if f is not None:
# f.close()
###
#pred_score_tuple 逆序排序
pred_score_tuple = sorted(pred_score_tuple, key=lambda x: x[1])
pred_score_tuple.reverse()
for tp_idx, tp in enumerate(pred_score_tuple):
pred_word_list, score_tmp = tp
#print(pred_word_list)
#print(score_tmp)
repeat_fa = 0
for pred_word_idx, pred_word in enumerate(pred_word_list):
if pred_word not in dict_trg:
pass
# #不出现在trg里的重复惩罚
# if pred_word in dict_pred:
# repeat_fa = 1
# break
# else:
# dict_pred[pred_word] = 1
else:
if pred_word not in dict_pred:
dict_pred[pred_word] = 1
else:
dict_pred[pred_word] += 1
if(dict_pred[pred_word] > dict_trg[pred_word]):
repeat_fa = 1
if repeat_fa == 1:
score_final[tp_idx] = 0.0