-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtatqa_metric.py
363 lines (322 loc) · 13.7 KB
/
tatqa_metric.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
from typing import Set, Tuple, Union
from tatqa_utils import *
import pandas as pd
import numpy as np
from scipy.optimize import linear_sum_assignment
def _answer_to_bags(answer: Union[str, List[str], Tuple[str, ...]]) -> Tuple[List[str], List[Set[str]]]:
if isinstance(answer, (list, tuple)):
raw_spans = answer
else:
raw_spans = [answer]
normalized_spans: List[str] = []
token_bags = []
for raw_span in raw_spans:
normalized_span = normalize_answer(raw_span)
normalized_spans.append(normalized_span)
token_bags.append(set(normalized_span.split()))
return normalized_spans, token_bags
def _align_bags(predicted: List[Set[str]], gold: List[Set[str]]) -> List[float]:
"""
Takes gold and predicted answer sets and first finds the optimal 1-1 alignment
between them and gets maximum metric values over all the answers.
"""
scores = np.zeros([len(gold), len(predicted)])
for gold_index, gold_item in enumerate(gold):
for pred_index, pred_item in enumerate(predicted):
# if _match_numbers_if_present(gold_item, pred_item): no need to match number in tatqa
scores[gold_index, pred_index] = _compute_f1(pred_item, gold_item)
row_ind, col_ind = linear_sum_assignment(-scores)
max_scores = np.zeros([max(len(gold), len(predicted))])
for row, column in zip(row_ind, col_ind):
max_scores[row] = max(max_scores[row], scores[row, column])
return max_scores
def _compute_f1(predicted_bag: Set[str], gold_bag: Set[str]) -> float:
intersection = len(gold_bag.intersection(predicted_bag))
if not predicted_bag:
precision = 1.0
else:
precision = intersection / float(len(predicted_bag))
if not gold_bag:
recall = 1.0
else:
recall = intersection / float(len(gold_bag))
f1 = (2 * precision * recall) / (precision + recall) if not (precision == 0.0 and recall == 0.0) else 0.0
return f1
def _match_numbers_if_present(gold_bag: Set[str], predicted_bag: Set[str]) -> bool:
gold_numbers = set()
predicted_numbers = set()
for word in gold_bag:
if is_number(word):
gold_numbers.add(word)
for word in predicted_bag:
if is_number(word):
predicted_numbers.add(word)
if (not gold_numbers) or gold_numbers.intersection(predicted_numbers):
return True
return False
def get_metrics(predicted: Union[str, List[str], Tuple[str, ...]],
gold: Union[str, List[str], Tuple[str, ...]]) -> Tuple[float, float]:
"""
Takes a predicted answer and a gold answer (that are both either a string or a list of
strings), and returns exact match and the DROP F1 metric for the prediction. If you are
writing a script for evaluating objects in memory (say, the output of predictions during
validation, or while training), this is the function you want to call, after using
:func:`answer_json_to_strings` when reading the gold answer from the released data file.
"""
predicted_bags = _answer_to_bags(predicted)
gold_bags = _answer_to_bags(gold)
if set(predicted_bags[0]) == set(gold_bags[0]) and len(predicted_bags[0]) == len(gold_bags[0]):
exact_match = 1.0
else:
exact_match = 0.0
f1_per_bag = _align_bags(predicted_bags[1], gold_bags[1])
f1 = np.mean(f1_per_bag)
f1 = round(f1, 2)
return exact_match, f1
def extract_gold_answers(qa_annotation):
'''
span
multi-span
arithmetic (+ - * /)
count
date
other
gold answers is a list of list, each item in gold answers is a valid answer
'''
answer_type, scale = qa_annotation["answer_type"], qa_annotation['scale']
answer_content = qa_annotation['answer']
gold_answers = []
if answer_type in ['multi-span', 'span']: # list
assert isinstance(answer_content, list), answer_content
gold_answers = answer_content # multi-span
elif answer_type in ["arithmetic"]:
gold_answers.append(str(answer_content))
elif answer_type in ['count']:
gold_answers.append(str(int(answer_content)))
else:
gold_answers.append(str(answer_content))
return answer_type, gold_answers, scale
def metric_max_over_ground_truths(metric_fn, predictions, ground_truths):
scores_for_ground_truths = []
for pred in predictions:
for ground_truth in ground_truths:
score = metric_fn(pred, ground_truth)
scores_for_ground_truths.append(score)
if len(scores_for_ground_truths) == 0:
return 0, 0
return max(scores_for_ground_truths)
class AverageMeter(object):
"""Computes and stores the average and current value."""
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += val * n
self.count += n
self.avg = self.sum / self.count
def get_answer_str(answers: list, scale: str):
"""
:param ans_type: span, multi-span, arithmetic, count
:param ans_list:
:param scale: "", thousand, million, billion, percent
:param mode:
:return:
"""
sorted_ans = sorted(answers)
ans_temp = []
for ans in sorted_ans:
ans_str = str(ans)
if is_number(ans_str):
ans_num = to_number(ans_str)
if ans_num is None:
if scale:
ans_str = ans_str + " " + str(scale)
else:
if '%' in ans_str: # has been handled the answer itself is a percentage
ans_str = '%.4f' % ans_num
else:
ans_str = '%.4f' % (round(ans_num, 2) * scale_to_num(scale))
else:
if scale:
ans_str = ans_str + " " + str(scale)
ans_temp.append(ans_str)
return [" ".join(ans_temp)]
# handle percentage
def add_percent_pred(prediction_strings, pred_scale, pred):
"""
to solve [pred = 0.2342] <> [ans = 23.42 and scale == 'percent']
:param prediction_strings:
:param gold_ans_type:
:param gold_scale:
:param pred:
:return:
"""
if len(pred) > 1:
return prediction_strings
pred_str = str(pred[0])
if pred_str is None:
return prediction_strings
if not pred_scale and '%' not in pred_str and is_number(pred_str): # mode only or no pred_scale num only
pred_str = to_number(pred_str)
if pred_str is None:
return prediction_strings
prediction_strings.append('%.4f' % pred_str)
return prediction_strings
class TaTQAEmAndF1(object):
"""
This :class:`Metric` takes the best span string computed by a model, along with the answer
strings labeled in the data, and computes exact match and F1 score using the official DROP
evaluator (which has special handling for numbers and for questions with multiple answer spans,
among other things).
"""
def __init__(self) -> None:
self._total_em = 0.0
self._total_f1 = 0.0
self._scale_em = 0.0
self._op_em = 0.0
self.op_correct_count = {"SPAN": 0, "MULTI_SPAN": 1, "COUNT": 2, "ARITHMETIC": 3}
self.op_total_count = {"SPAN": 0, "MULTI_SPAN": 1, "COUNT": 2, "ARITHMETIC": 3}
self.scale_correct_count = {"": 0, "thousand": 0, "million": 0, "billion": 0, "percent": 0}
self.scale_total_count = {"": 0, "thousand": 0, "million": 0, "billion": 0, "percent": 0}
self._count = 0
self._details = []
def __call__(self,
ground_truth: dict,
prediction: Union[str, List],
pred_scale="",
pred_span = None,
gold_span = None,
pred_op=None,
gold_op=None): # type: ignore
"""
:param ground_truth:
:param prediction:
:param pred_scale:
:param pred_span:
:param gold_span:
:param pred_op:
:param gold_op:
:return:
"""
if pred_op is not None:
if pred_op == 'ARITHMETIC' and gold_op == 'ARITHMETIC':
self.op_correct_count[pred_op] += 1
self._op_em += 1
elif pred_op in ['SPAN', 'COUNT', 'MULTI_SPAN'] and gold_op in ['SPAN', 'COUNT', 'MULTI_SPAN']:
self.op_correct_count[pred_op] += 1
self._op_em += 1
self.op_total_count[gold_op] += 1
if pred_scale == ground_truth["scale"]:
self.scale_correct_count[pred_scale] += 1
self.scale_total_count[ground_truth["scale"]] += 1
if prediction is None or prediction == []:
exact_match = 0
f1_score = 0
span_exact_match = 0
span_f1_score = 0
else:
gold_type, gold_answer, gold_scale = extract_gold_answers(ground_truth)
if gold_answer is None:
exact_match = 0
f1_score = 0
span_exact_match = 0
span_f1_score = 0
else:
ground_truth_answer_strings = get_answer_str(gold_answer, gold_scale)
if gold_scale == pred_scale:
self._scale_em += 1
prediction = prediction if isinstance(prediction, list) else [prediction]
prediction_strings = get_answer_str(prediction, pred_scale)
prediction_strings = add_percent_pred(prediction_strings, pred_scale, prediction)
exact_match, f1_score = metric_max_over_ground_truths(
get_metrics,
prediction_strings,
ground_truth_answer_strings
)
# if ground_truth['uid'] == 'adfc652018f8560af945f804f8557ab8':
# import pdb; pdb.set_trace()
# if ground_truth['answer_from'] == 'text' and exact_match != 1:
# import pdb; pdb.set_trace()
# gold_answer, prediction, exact_match, ground_truth['uid']
if gold_type in ['arithmetic', 'count']:
"""if gold type equals with arithmetic and count, set the f1_score == exact_match"""
f1_score = exact_match
if not pred_span:
span_exact_match = 0
span_f1_score = 0
else:
pred_span_strings = get_answer_str(pred_span, "")
gold_span_strings = get_answer_str(gold_span, "")
span_exact_match, span_f1_score = metric_max_over_ground_truths(
get_metrics,
pred_span_strings,
gold_span_strings,
)
self._total_em += exact_match
self._total_f1 += f1_score
self._count += 1
it = {**ground_truth,
**{"pred":prediction,
"pred_scale":pred_scale,
"em":exact_match,
"f1":f1_score,
"pred_span":pred_span,
"gold_span":gold_span,
"span_em":span_exact_match,
"span_f1":span_f1_score}}
self._details.append(it)
return exact_match
def get_overall_metric(self, reset: bool = False) -> Tuple[float, float, float, float]:
"""
Returns
-------
Average exact match and F1 score (in that order) as computed by the official DROP script
over all inputs.
"""
exact_match = self._total_em / self._count if self._count > 0 else 0
f1_score = self._total_f1 / self._count if self._count > 0 else 0
scale_score = self._scale_em / self._count if self._count > 0 else 0
op_score = self._op_em / self._count if self._count > 0 else 0
op_em_detail = {"SPAN": 0, "MULTI_SPAN": 1, "COUNT": 2, "ARITHMETIC": 3}
scale_em_detail = {"": 0, "thousand": 0, "million": 0, "billion": 0, "percent": 0}
for k in op_em_detail.keys():
op_em_detail[k] = self.op_correct_count[k] / self.op_total_count[k] if self.op_total_count[k] > 0 else 0
for k in scale_em_detail.keys():
scale_em_detail[k] = self.scale_correct_count[k] / self.scale_total_count[k] if self.scale_total_count[k] > 0 else 0
if reset:
self.reset()
return exact_match, f1_score, scale_score, op_score
def get_detail_metric(self):
df = pd.DataFrame(self._details)
if len(self._details) == 0:
return None, None
em_pivot_tab = df.pivot_table(index='answer_type', values=['em'],
columns=['answer_from'], aggfunc='mean').fillna(0)
f1_pivot_tab = df.pivot_table(index='answer_type', values=['f1'],
columns=['answer_from'], aggfunc='mean').fillna(0)
return em_pivot_tab, f1_pivot_tab
def get_raw_pivot_table(self):
df = pd.DataFrame(self._details)
pivot_tab = df.pivot_table(index='answer_type', values=['em'],
columns=['answer_from'], aggfunc='count').fillna(0)
return pivot_tab
def get_raw(self):
return self._details
def reset(self):
self._total_em = 0.0
self._total_f1 = 0.0
self._scale_em = 0.0
self._op_em = 0.0
self._count = 0
self._details = []
self.op_correct_count = {"SPAN": 0, "MULTI_SPAN": 1, "COUNT": 2, "ARITHMETIC": 3}
self.op_total_count = {"SPAN": 0, "MULTI_SPAN": 1, "COUNT": 2, "ARITHMETIC": 3}
self.scale_correct_count = {"": 0, "thousand": 0, "million": 0, "billion": 0, "percent": 0}
self.scale_total_count = {"": 0, "thousand": 0, "million": 0, "billion": 0, "percent": 0}
def __str__(self):
return f"TaTQAEmAndF1(em={self._total_em}, f1={self._total_f1}, count={self._count})"