-
Notifications
You must be signed in to change notification settings - Fork 1
/
evaluation.py
257 lines (190 loc) · 6.91 KB
/
evaluation.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
import regex
import json
import string
import unicodedata
from typing import List
import numpy as np
from collections import Counter
from rouge import Rouge
def hits(ans, res):
n = 0
res = normalize_answer(res)
for a in ans:
a = normalize_answer(a)
n += res.count(a)
return n
class SimpleTokenizer(object):
ALPHA_NUM = r'[\p{L}\p{N}\p{M}]+'
NON_WS = r'[^\p{Z}\p{C}]'
def __init__(self):
"""
Args:
annotators: None or empty set (only tokenizes).
"""
self._regexp = regex.compile(
'(%s)|(%s)' % (self.ALPHA_NUM, self.NON_WS),
flags=regex.IGNORECASE + regex.UNICODE + regex.MULTILINE
)
def tokenize(self, text, uncased=False):
matches = [m for m in self._regexp.finditer(text)]
if uncased:
tokens = [m.group().lower() for m in matches]
else:
tokens = [m.group() for m in matches]
return tokens
def check_answer(example, tokenizer) -> List[bool]:
"""Search through all the top docs to see if they have any of the answers."""
answers = example['answers']
ctxs = example['ctxs']
hits = []
for _, doc in enumerate(ctxs):
text = doc['text']
if text is None: # cannot find the document for some reason
hits.append(False)
continue
hits.append(has_answer(answers, text, tokenizer))
return hits
def has_answer(answers, text, tokenizer=SimpleTokenizer()) -> bool:
"""Check if a document contains an answer string."""
text = _normalize(text)
text = tokenizer.tokenize(text, uncased=True)
for answer in answers:
answer = _normalize(answer)
answer = tokenizer.tokenize(answer, uncased=True)
for i in range(0, len(text) - len(answer) + 1):
if answer == text[i: i + len(answer)]:
return True
return False
def _normalize(text):
return unicodedata.normalize('NFD', text)
def normalize_answer(s):
def remove_articles(text):
s = r'\b(an|the)\b'
# print('normalize: ', s)
return regex.sub(s, ' ', text) # dont remove a for mmlu
def white_space_fix(text):
return ' '.join(text.split())
def remove_punc(text):
exclude = set(string.punctuation)
for ch in exclude:
text = text.replace(ch, ' ')
return text
def lower(text):
if type(text) == list:
print(text)
return text.lower()
return white_space_fix(remove_articles(remove_punc(lower(s))))
def exact_match_score(prediction, ground_truth):
# print(normalize_answer(prediction), normalize_answer(ground_truth))
if type(ground_truth) == list: #physics
ground_truth = ','.join(ground_truth)
# print(ground_truth, prediction)
return normalize_answer(prediction) == normalize_answer(ground_truth)
def ems(prediction, ground_truths):
# print(prediction, ground_truths)
return max([exact_match_score(prediction, gt) for gt in ground_truths])
def f1_score(prediction, ground_truth):
if type(ground_truth) == list: #physics
ground_truth = ','.join(ground_truth)
prediction_tokens = normalize_answer(prediction).split()
ground_truth_tokens = normalize_answer(ground_truth).split()
common = Counter(prediction_tokens) & Counter(ground_truth_tokens)
num_same = sum(common.values())
if num_same == 0:
f1 = 0
else:
precision = 1.0 * num_same / len(prediction_tokens)
recall = 1.0 * num_same / len(ground_truth_tokens)
f1 = (2 * precision * recall) / (precision + recall)
# print(f"**prd: {prediction}**grd: {ground_truth}**F1: {f1}**")
return f1
def f1(prediction, ground_truths):
return max([f1_score(prediction, gt) for gt in ground_truths])
def rougel_score(prediction, ground_truth):
rouge = Rouge()
# no normalization
try:
scores = rouge.get_scores(prediction, ground_truth, avg=True)
except ValueError: # "Hypothesis is empty."
return 0.0
return scores["rouge-l"]["f"]
def rl(prediction, ground_truths):
return max([rougel_score(prediction, gt) for gt in ground_truths])
## file-level evaluation ... ###
def eval_recall(infile):
tokenizer = SimpleTokenizer()
lines = open(infile, 'r').readlines()[1:]
has_answer_count = 0
answer_lengths = []
for line in lines:
line = json.loads(line)
answer = line['answer']
output = ' || '.join(line['output'])
if has_answer(answer, output, tokenizer):
has_answer_count += 1
answer_lengths.append(len(output.split()))
recall = round(has_answer_count/len(lines), 4)
lens = round(np.mean(answer_lengths), 4)
return recall, lens
def eval_question_answering(infile, end=None):
lines = open(infile, 'r').readlines()[1:]
# print(len(lines))
# lines = lines[:4]
exact_match_count = 0
answer_lengths = []
f1_scores = []
for line in lines:
line = json.loads(line)
# print(line)
answer = line['answer']
output = line['output'][0] if line['output'] else ''
if end:
output = output.split(end)[0]
output = output.split('\n')[0] # added
if ems(output, answer): # EM evaluation
# print(ems(output, answer))
exact_match_count += 1
answer_lengths.append(len(output.split()))
f1_scores.append(f1(output, answer))
em = round(exact_match_count/len(lines), 4)
lens = round(np.mean(answer_lengths), 4)
F1 = round(np.mean(f1_scores), 4)
em_f1 = round(f1_scores.count(1)/len(lines), 4)
print(exact_match_count, len(lines))
print(em, F1, em_f1)
return em, lens, F1
def eval_fact_checking(infile):
tokenizer = SimpleTokenizer()
lines = open(infile, 'r').readlines()[1:]
exact_match_count = 0
answer_lengths = []
for line in lines:
line = json.loads(line)
answer = line['answer']
output = line['output'][0]
if answer == ["refutes"]:
answer = ["refutes", "no", "false"]
if answer == ["supports"]:
answer = ["supports", "yes", "true"]
if has_answer(answer, output, tokenizer):
exact_match_count += 1
answer_lengths.append(len(output.split()))
em = round(exact_match_count/len(lines), 4)
lens = round(np.mean(answer_lengths), 4)
return em, lens
def eval_dialogue_system(infile):
lines = open(infile, 'r').readlines()[1:]
f1_scores = []
rl_scores = []
answer_lengths = []
for line in lines:
line = json.loads(line)
answer = line['answer']
output = line['output'][0]
f1_scores.append(f1(output, answer))
rl_scores.append(rl(output, answer))
answer_lengths.append(len(output.split()))
F1 = round(np.mean(f1_scores), 4)
RL = round(np.mean(rl_scores), 4)
lens = round(np.mean(answer_lengths), 4)
return F1, RL, lens