-
Notifications
You must be signed in to change notification settings - Fork 20
/
evaluation.py
executable file
·222 lines (155 loc) · 5.73 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
import regex
import json
import string
import unicodedata
from typing import List
import numpy as np
from collections import Counter
from rouge import Rouge
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):
return regex.sub(r'\b(a|an|the)\b', ' ', text)
def white_space_fix(text):
return ' '.join(text.split())
def remove_punc(text):
exclude = set(string.punctuation)
return ''.join(ch for ch in text if ch not in exclude)
def lower(text):
return text.lower()
return white_space_fix(remove_articles(remove_punc(lower(s))))
def exact_match_score(prediction, ground_truth):
return normalize_answer(prediction) == normalize_answer(ground_truth)
def ems(prediction, ground_truths):
return max([exact_match_score(prediction, gt) for gt in ground_truths])
def f1_score(prediction, 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:
return 0
precision = 1.0 * num_same / len(prediction_tokens)
recall = 1.0 * num_same / len(ground_truth_tokens)
f1 = (2 * precision * recall) / (precision + recall)
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):
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 ems(output, answer): # EM evaluation
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_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