/
metrics.py
296 lines (204 loc) · 9.79 KB
/
metrics.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
# rouge
#from rouge_score import rouge_scorer # native rouge package
# moverscore
#from moverscore_v2 import get_idf_dict, word_mover_score
#from collections import defaultdict
# other metrics (BLEU, BertScore, etc)
import datasets
meteor = datasets.load_metric('meteor')
bleu = datasets.load_metric('bleu')
bertscore = datasets.load_metric('bertscore')
def compute_rouge_batch(predictions, references):
"""
predictions: list
references: list
"""
result_dict = {}
predictions = list(predictions)
references = list(references)
if (type(predictions) != list or type(references) != list):
print('"predictions" or "references" is not a list!')
return result_dict
scorer = datasets.load_metric('rouge')
r1_pre, r2_pre, rL_pre = [], [], []
r1_re, r2_re, rL_re = [], [], []
r1_fm, r2_fm, rL_fm = [], [], []
for pre, ref in zip(pre, ref):
output = compute_rouge_single(pre, ref)
r1_pre.append(output['rouge1_precision'])
r2_pre.append(output['rouge2_precision'])
rL_pre.append(output['rougeL_precision'])
r1_re.append(output['rouge1_recall'])
r2_re.append(output['rouge2_recall'])
rL_re.append(output['rougeL_recall'])
r1_fm.append(output['rouge1_fmeasure'])
r2_fm.append(output['rouge2_fmeasure'])
rL_fm.append(output['rougeL_fmeasure'])
result_dict['rouge1_precision'] = r1_pre
result_dict['rouge2_precision'] = r2_pre
result_dict['rougeL_precision'] = rL_pre
result_dict['rouge1_recall'] = r1_re
result_dict['rouge2_recall'] = r2_re
result_dict['rougeL_recall'] = rL_re
result_dict['rouge1_fmeasure'] = r1_fm
result_dict['rouge2_fmeasure'] = r2_fm
result_dict['rougeL_fmeasure'] = rL_fm
#print('result_dict: ', result_dict)
return result_dict
def compute_rouge_single(prediction, reference):
"""
predictions: single string
references: single string
"""
result_dict = {}
if (type(prediction) != str or type(reference) != str):
print('"prediction" or "reference" is not a string!')
return result_dict
scorer = datasets.load_metric('rouge')
output = scorer.compute(predictions=[prediction], references=[reference])
result_dict['rouge1_precision'] = output['rouge1'].mid.precision
result_dict['rouge2_precision'] = output['rouge2'].mid.precision
result_dict['rougeL_precision'] = output['rougeL'].mid.precision
result_dict['rouge1_recall'] = output['rouge1'].mid.recall
result_dict['rouge2_recall'] = output['rouge2'].mid.recall
result_dict['rougeL_recall'] = output['rougeL'].mid.recall
result_dict['rouge1_fmeasure'] = output['rouge1'].mid.fmeasure
result_dict['rouge2_fmeasure'] = output['rouge2'].mid.fmeasure
result_dict['rougeL_fmeasure'] = output['rougeL'].mid.fmeasure
#print('result_dict: ', result_dict)
return result_dict
def compute_bertscore_batch(predictions, references):
result_dict = {}
prel, re, f1 = [], [], []
#scorer = datasets.load_metric('bertscore')
for pre, ref in zip(predictions, references):
print('pre: ', pre)
print('ref: ', ref)
output = bertscore.compute(predictions=[pre], references=[ref], lang='en')
prel.append(output['precision'][0])
re.append(output['recall'][0])
f1.append(output['f1'][0])
print('output: ', output)
print('-------------------')
result_dict = {}
result_dict['bertscore_precision'] = sum(prel)/len(prel)
result_dict['bertscore_recall'] = sum(re)/len(re)
result_dict['bertscore_f1'] = sum(f1)/len(f1)
return result_dict
def compute_bleu_single(prediction, reference):
result_dict = {}
if (type(prediction) != str or type(reference) != str):
print('"prediction" or "reference" is not a string!')
return result_dict
prediction = prediction.split()
reference = reference.split()
#scorer = datasets.load_metric('bleu')
output = {}
try:
output = bleu.compute(predictions=[prediction], references=[[reference]])
except:
result_dict['bleu'] = 0
return result_dict
#print('output: ', output)
result_dict['bleu'] = output['bleu']
#print('result_dict: ', result_dict)
return result_dict
def compute_bleu_batch(predictions, references):
result_dict = {}
if (type(predictions) != list or type(references) != list):
print('"predictions" or "references" is not a list!')
return result_dict
predictions = [[x.strip('.') for x in pre.split()] for pre in predictions]
references = [[x.strip('.') for x in ref.split()] for ref in references]
#print('predictions: ', predictions)
#print('references: ', [references])
#scorer = datasets.load_metric('bleu')
output = {}
try:
output = bleu.compute(predictions=predictions, references=[references])
except:
result_dict['bleu'] = 0
return result_dict
#print('output: ', output)
result_dict['bleu'] = output['bleu']
#print('result_dict: ', result_dict)
return result_dict
def compute_meteor_single(prediction, reference):
result_dict = {}
if (type(prediction) != str or type(reference) != str):
print('"prediction" or "reference" is not a string!')
return result_dict
#scorer = datasets.load_metric('meteor')
output = meteor.compute(predictions=[prediction], references=[reference])
#print('output: ', output)
result_dict['meteor'] = output['meteor']
#print('result_dict: ', result_dict)
return result_dict
def compute_meteor_batch(predictions, references):
result_dict = {}
if (type(predictions) != list or type(references) != list):
print('"predictions" or "references" is not a list!')
return result_dict
#scorer = datasets.load_metric('meteor')
output = meteor.compute(predictions=[predictions], references=[references])
#print('output: ', output)
result_dict['meteor'] = output['meteor']
#print('result_dict: ', result_dict)
return result_dict
def compute_bertscore_single(prediction, reference):
result_dict = {}
if (type(prediction) != str or type(reference) != str):
print('"prediction" or "reference" is not a string!')
return result_dict
# microsoft/deberta-xlarge-mnli (best model), model_type=roberta-large (default)
#scorer = datasets.load_metric('bertscore')
output = bertscore.compute(predictions=[prediction], references=[reference], lang='en')
result_dict['bertscore_precision'] = output['precision']
result_dict['bertscore_recall'] = output['recall']
result_dict['bertscore_f1'] = output['f1']
return result_dict
def compute_moverscore_single(prediction, reference):
result_dict = {}
if (type(prediction) != str or type(reference) != str):
print('"prediction" or "reference" is not a string!')
return result_dict
# Transformers==3.1.0, some errors
# DistilBERT (original BERTMNLI)
idf_dict_ref = get_idf_dict(reference) # idf_dict_ref = defaultdict(lambda: 1.)
idf_dict_hyp = get_idf_dict(prediction) # idf_dict_hyp = defaultdict(lambda: 1.)
#print('idf_dict_ref: ', idf_dict_ref)
#print('idf_dict_hyp: ', idf_dict_hyp)
score = word_mover_score(reference, prediction, idf_dict_ref, idf_dict_hyp, \
stop_words=[], n_gram=1, remove_subwords=True)
#print('score:' , score)'''
return result_dict
#..................
'''from nltk.translate.bleu_score import sentence_bleu
reference = [['the', 'quick', 'brown', 'fox', 'jumped', 'over', 'the', 'lazy', 'dog']]
candidate = ['the', 'fast', 'brown', 'fox', 'jumped', 'over', 'the', 'sleepy', 'dog']
reference1 = ' '.join(x for x in reference[0])
candidate1 = ' '.join(x for x in candidate)
print('nltk: ', sentence_bleu(reference, candidate))
'''
'''from sacrebleu.metrics import BLEU, CHRF, TER
import sacrebleu
bleu = BLEU()
predictions = ['The', 'film', 'Death', 'on', 'a', 'Factory', 'Farm', 'was', 'shown', 'on', 'HBO', 'and', \
'it', 'was', 'written', 'and', 'directed', 'by', 'Tom', 'Simon', 'Geof', 'Bartz', 'is', 'the', \
'editor', 'of', 'the', 'film']
references = [['Death', 'on', 'a', 'Factory', 'Farm', 'is', 'an', 'HBO', 'Film', 'directed', 'and', 'produced', \
'by', 'Tom', 'Simon', 'Geof', 'Bartz', 'is', 'the', 'editor'],
['Death', 'on', 'a', 'Factory', 'Farm', 'is', 'an', 'HBO', 'film', 'directed,', 'produced,', 'and', \
'edited', 'by', 'Geof', 'Bartz', 'and', 'Tom', 'Simon'],
['Tom', 'Simon', 'directed', 'and', 'produced', 'the', 'film', '‘Death', 'on', 'a', 'Factory', 'Farm’,', \
'which', 'was', 'broadcasted', 'by', 'HBO', 'Geof', 'Bartz', 'on', 'the', 'other', 'hand', 'edited', 'the', \
'film']]
references1 = [' '.join(x for x in reference) for reference in references]
predictions1 = [' '.join(x for x in predictions)]
print('references1: ', references1)
print('predictions1: ', predictions1)
#print('bleu: ', bleu.corpus_score(predictions1, [references1]))
print('datasets: ', compute_bleu_batch(predictions1, references1))
print('sacrebleu: ', sacrebleu.corpus_bleu(predictions1, [references1]))
#from nltk.translate.bleu_score import sentence_bleu
#print('nltk: ', sentence_bleu(references, predictions))'''