Spaces:
Runtime error
Runtime error
Timothyxxx
commited on
Commit
•
7de3018
1
Parent(s):
0b8fc5a
Add missed MMQA
Browse files- utils/mmqa/__init__.py +0 -0
- utils/mmqa/eval_mmqa.py +19 -0
- utils/mmqa/evaluator.py +408 -0
- utils/mmqa/image_stuff.py +28 -0
- utils/mmqa/mmqa_captions.json +0 -0
- utils/mmqa/qc_mmqa_dev.csv +2 -0
- utils/mmqa/qimc.py +41 -0
- utils/mmqa/qimc_mmqa_dev.csv +3 -0
- utils/mmqa/qpmc.py +24 -0
- utils/mmqa/qpmc_mmqa_dev.csv +3 -0
utils/mmqa/__init__.py
ADDED
File without changes
|
utils/mmqa/eval_mmqa.py
ADDED
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from utils.mmqa.evaluator import evaluate_predictions
|
2 |
+
import json
|
3 |
+
|
4 |
+
ANNOTATION_RESULT_PATH = "../results_mmqa/unfiltered_mmqa_nsqls_mmqa_v2_all_standard.json"
|
5 |
+
EXECUTION_RESULT_PATH = "../results_mmqa/unfiltered_mmqa_nsqls_mmqa_v2_all_standard_new_qa_pool_bug_fixed_v1.jsonn"
|
6 |
+
|
7 |
+
if __name__ == '__main__':
|
8 |
+
right = 0
|
9 |
+
all_num = 0
|
10 |
+
with open(ANNOTATION_RESULT_PATH, "r") as f:
|
11 |
+
all_data = json.load(f)
|
12 |
+
with open(EXECUTION_RESULT_PATH, "r") as f:
|
13 |
+
pred_data = json.load(f)
|
14 |
+
|
15 |
+
pred_dict = {eid: [str(a) for a in pred_data[eid]['pred_answer']] for eid in pred_data}
|
16 |
+
gold_dict = {eid: [str(a) for a in pred_data[eid]['gold_answer']] for eid in pred_data}
|
17 |
+
eval_scores, instance_eval_results = evaluate_predictions(pred_dict, gold_dict)
|
18 |
+
print(eval_scores)
|
19 |
+
print(instance_eval_results)
|
utils/mmqa/evaluator.py
ADDED
@@ -0,0 +1,408 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import re
|
2 |
+
import string
|
3 |
+
import numpy as np
|
4 |
+
from collections import Counter
|
5 |
+
from typing import List, Set, Tuple, Union
|
6 |
+
from scipy.optimize import linear_sum_assignment
|
7 |
+
from word2number.w2n import word_to_num
|
8 |
+
import json
|
9 |
+
|
10 |
+
# copy from https://github.com/allenai/multimodalqa/blob/master/baselines/evaluate.py
|
11 |
+
|
12 |
+
|
13 |
+
ALL_QUESTION_TYPES = [
|
14 |
+
'TextQ',
|
15 |
+
'TableQ',
|
16 |
+
'ImageQ',
|
17 |
+
'ImageListQ',
|
18 |
+
'Compose(TableQ,ImageListQ)',
|
19 |
+
'Compose(TextQ,ImageListQ)',
|
20 |
+
'Compose(ImageQ,TableQ)',
|
21 |
+
'Compose(ImageQ,TextQ)',
|
22 |
+
'Compose(TextQ,TableQ)',
|
23 |
+
'Compose(TableQ,TextQ)',
|
24 |
+
'Intersect(TableQ,TextQ)',
|
25 |
+
'Intersect(ImageListQ,TableQ)',
|
26 |
+
'Intersect(ImageListQ,TextQ)',
|
27 |
+
'Compare(Compose(TableQ,ImageQ),TableQ)',
|
28 |
+
'Compare(Compose(TableQ,ImageQ),Compose(TableQ,TextQ))',
|
29 |
+
'Compare(TableQ,Compose(TableQ,TextQ))',
|
30 |
+
]
|
31 |
+
|
32 |
+
TEXT_SINGLE_HOP_QUESTION_TYPES = [
|
33 |
+
'TextQ',
|
34 |
+
]
|
35 |
+
TEXT_AS_FIRST_HOP_QUESTION_TYPES = [
|
36 |
+
'Compare(TableQ,Compose(TableQ,TextQ))',
|
37 |
+
'Compose(ImageQ,TextQ)',
|
38 |
+
'Compose(TableQ,TextQ)',
|
39 |
+
'Intersect(TableQ,TextQ)',
|
40 |
+
'Intersect(ImageListQ,TextQ)',
|
41 |
+
]
|
42 |
+
TEXT_AS_SECOND_HOP_QUESTION_TYPES = [
|
43 |
+
'Compare(Compose(TableQ,ImageQ),Compose(TableQ,TextQ))',
|
44 |
+
'Compose(TextQ,ImageListQ)',
|
45 |
+
'Compose(TextQ,TableQ)',
|
46 |
+
]
|
47 |
+
|
48 |
+
TABLE_SINGLE_HOP_QUESTION_TYPES = [
|
49 |
+
"TableQ"
|
50 |
+
]
|
51 |
+
TABLE_AS_FIRST_HOP_QUESTION_TYPES = [
|
52 |
+
'Compose(ImageQ,TableQ)',
|
53 |
+
'Compose(TextQ,TableQ)',
|
54 |
+
]
|
55 |
+
TABLE_AS_SECOND_HOP_QUESTION_TYPES = [
|
56 |
+
'Compare(Compose(TableQ,ImageQ),TableQ)',
|
57 |
+
'Compare(TableQ,Compose(TableQ,TextQ))',
|
58 |
+
'Compose(TableQ,ImageListQ)',
|
59 |
+
'Compose(TableQ,TextQ)',
|
60 |
+
'Intersect(ImageListQ,TableQ)',
|
61 |
+
'Intersect(TableQ,TextQ)',
|
62 |
+
]
|
63 |
+
|
64 |
+
IMAGE_SINGLE_HOP_QUESTION_TYPES = [
|
65 |
+
'ImageQ',
|
66 |
+
'ImageListQ'
|
67 |
+
]
|
68 |
+
IMAGE_AS_FIRST_HOP_QUESTION_TYPES = [
|
69 |
+
'Compare(Compose(TableQ,ImageQ),Compose(TableQ,TextQ))',
|
70 |
+
'Compare(Compose(TableQ,ImageQ),TableQ)',
|
71 |
+
'Compose(TableQ,ImageListQ)',
|
72 |
+
'Compose(TextQ,ImageListQ)',
|
73 |
+
'Intersect(ImageListQ,TableQ)',
|
74 |
+
]
|
75 |
+
IMAGE_AS_SECOND_HOP_QUESTION_TYPES = [
|
76 |
+
'Compose(ImageQ,TableQ)',
|
77 |
+
'Compose(ImageQ,TextQ)',
|
78 |
+
'Intersect(ImageListQ,TextQ)',
|
79 |
+
]
|
80 |
+
|
81 |
+
|
82 |
+
# every question should be answered either as a single hop question, or two-hop question
|
83 |
+
assert set(TEXT_SINGLE_HOP_QUESTION_TYPES + TEXT_AS_SECOND_HOP_QUESTION_TYPES
|
84 |
+
+ TABLE_SINGLE_HOP_QUESTION_TYPES + TABLE_AS_SECOND_HOP_QUESTION_TYPES
|
85 |
+
+ IMAGE_SINGLE_HOP_QUESTION_TYPES + IMAGE_AS_SECOND_HOP_QUESTION_TYPES) == set(ALL_QUESTION_TYPES)
|
86 |
+
assert len(set(TEXT_SINGLE_HOP_QUESTION_TYPES) & set(TEXT_AS_SECOND_HOP_QUESTION_TYPES)) == 0
|
87 |
+
assert len(set(TABLE_SINGLE_HOP_QUESTION_TYPES) & set(TABLE_AS_SECOND_HOP_QUESTION_TYPES)) == 0
|
88 |
+
assert len(set(IMAGE_SINGLE_HOP_QUESTION_TYPES) & set(IMAGE_AS_SECOND_HOP_QUESTION_TYPES)) == 0
|
89 |
+
|
90 |
+
SINGLE_HOP_QUESTION_TYPES = TEXT_SINGLE_HOP_QUESTION_TYPES \
|
91 |
+
+ TABLE_SINGLE_HOP_QUESTION_TYPES \
|
92 |
+
+ IMAGE_SINGLE_HOP_QUESTION_TYPES
|
93 |
+
MULTI_HOP_QUESTION_TYPES = TEXT_AS_SECOND_HOP_QUESTION_TYPES \
|
94 |
+
+ TABLE_AS_SECOND_HOP_QUESTION_TYPES + \
|
95 |
+
IMAGE_AS_SECOND_HOP_QUESTION_TYPES
|
96 |
+
# no duplicated multi-hop question types
|
97 |
+
assert len(MULTI_HOP_QUESTION_TYPES) == len(set(MULTI_HOP_QUESTION_TYPES))
|
98 |
+
# no duplication for the first hop
|
99 |
+
assert set(TEXT_AS_FIRST_HOP_QUESTION_TYPES + TABLE_AS_FIRST_HOP_QUESTION_TYPES + IMAGE_AS_FIRST_HOP_QUESTION_TYPES) \
|
100 |
+
== set(MULTI_HOP_QUESTION_TYPES)
|
101 |
+
# single + multi = all
|
102 |
+
assert set(SINGLE_HOP_QUESTION_TYPES + MULTI_HOP_QUESTION_TYPES) == set(ALL_QUESTION_TYPES)
|
103 |
+
|
104 |
+
|
105 |
+
def process_question_for_implicit_decomp(question, question_type, hop=0, bridge_entity='', sep_token='[SEP]'):
|
106 |
+
if isinstance(bridge_entity, list) or isinstance(bridge_entity, set):
|
107 |
+
bridge_entity = "; ".join(bridge_entity)
|
108 |
+
return (
|
109 |
+
f'{question_type} {sep_token} '
|
110 |
+
f'HOP={hop} {sep_token} '
|
111 |
+
f'{bridge_entity} {sep_token} '
|
112 |
+
f'{question}')
|
113 |
+
|
114 |
+
|
115 |
+
def extract_numbers_from_str(s):
|
116 |
+
numbers = []
|
117 |
+
for token in s.split():
|
118 |
+
try:
|
119 |
+
num = int(token.replace(",", ""))
|
120 |
+
except:
|
121 |
+
try:
|
122 |
+
num = float(token)
|
123 |
+
except:
|
124 |
+
num = None
|
125 |
+
if num:
|
126 |
+
numbers.append(num)
|
127 |
+
return numbers
|
128 |
+
|
129 |
+
|
130 |
+
def read_jsonl(filename):
|
131 |
+
with open(filename, 'r') as f:
|
132 |
+
data = [json.loads(l.strip()) for l in f.readlines()]
|
133 |
+
return data
|
134 |
+
|
135 |
+
# From here through _match_numbers_if_present was originally copied from the evaluation code of DROP dataset:
|
136 |
+
# https://github.com/allenai/allennlp-reading-comprehension/blob/master/allennlp_rc/eval/drop_eval.py
|
137 |
+
|
138 |
+
def _remove_articles(text: str) -> str:
|
139 |
+
regex = re.compile(r"\b(a|an|the)\b", re.UNICODE)
|
140 |
+
return re.sub(regex, " ", text)
|
141 |
+
|
142 |
+
|
143 |
+
def _white_space_fix(text: str) -> str:
|
144 |
+
return " ".join(text.split())
|
145 |
+
|
146 |
+
|
147 |
+
EXCLUDE = set(string.punctuation)
|
148 |
+
|
149 |
+
|
150 |
+
def _remove_punc(text: str) -> str:
|
151 |
+
if not _is_number(text):
|
152 |
+
return "".join(ch for ch in text if ch not in EXCLUDE)
|
153 |
+
else:
|
154 |
+
return text
|
155 |
+
|
156 |
+
|
157 |
+
def _lower(text: str) -> str:
|
158 |
+
return text.lower()
|
159 |
+
|
160 |
+
|
161 |
+
def _tokenize(text: str) -> List[str]:
|
162 |
+
return re.split(" |-", text)
|
163 |
+
|
164 |
+
|
165 |
+
def _normalize_answer(text: str) -> str:
|
166 |
+
"""Lower text and remove punctuation, articles and extra whitespace."""
|
167 |
+
|
168 |
+
parts = [
|
169 |
+
_white_space_fix(_remove_articles(_normalize_number(_remove_punc(_lower(token)))))
|
170 |
+
for token in _tokenize(text)
|
171 |
+
]
|
172 |
+
parts = [part for part in parts if part.strip()]
|
173 |
+
normalized = " ".join(parts).strip()
|
174 |
+
return normalized
|
175 |
+
|
176 |
+
|
177 |
+
def _is_number(text: str) -> bool:
|
178 |
+
try:
|
179 |
+
float(text)
|
180 |
+
return True
|
181 |
+
except ValueError:
|
182 |
+
return False
|
183 |
+
|
184 |
+
|
185 |
+
def _is_word_number(text: str) -> bool:
|
186 |
+
try:
|
187 |
+
word_to_num(text)
|
188 |
+
return True
|
189 |
+
except ValueError:
|
190 |
+
return False
|
191 |
+
|
192 |
+
|
193 |
+
def _normalize_number(text: str) -> str:
|
194 |
+
if _is_number(text):
|
195 |
+
return str(float(text))
|
196 |
+
#TODO: this is not included in the original drop evaluation script, we need to have our own in the end anyways.
|
197 |
+
elif _is_word_number(text):
|
198 |
+
return str(float(word_to_num(text)))
|
199 |
+
else:
|
200 |
+
return text
|
201 |
+
|
202 |
+
|
203 |
+
def _answer_to_bags(
|
204 |
+
answer: Union[str, List[str], Tuple[str, ...]]
|
205 |
+
) -> Tuple[List[str], List[Set[str]]]:
|
206 |
+
if isinstance(answer, (list, tuple)):
|
207 |
+
raw_spans = answer
|
208 |
+
else:
|
209 |
+
raw_spans = [answer]
|
210 |
+
normalized_spans: List[str] = []
|
211 |
+
token_bags = []
|
212 |
+
for raw_span in raw_spans:
|
213 |
+
normalized_span = _normalize_answer(raw_span)
|
214 |
+
normalized_spans.append(normalized_span)
|
215 |
+
token_bags.append(set(normalized_span.split()))
|
216 |
+
return normalized_spans, token_bags
|
217 |
+
|
218 |
+
|
219 |
+
def _align_bags(predicted: List[Set[str]], gold: List[Set[str]]) -> List[float]:
|
220 |
+
"""
|
221 |
+
Takes gold and predicted answer sets and first finds the optimal 1-1 alignment
|
222 |
+
between them and gets maximum metric values over all the answers.
|
223 |
+
"""
|
224 |
+
scores = np.zeros([len(gold), len(predicted)])
|
225 |
+
for gold_index, gold_item in enumerate(gold):
|
226 |
+
for pred_index, pred_item in enumerate(predicted):
|
227 |
+
if _match_numbers_if_present(gold_item, pred_item):
|
228 |
+
scores[gold_index, pred_index] = _compute_f1(pred_item, gold_item)
|
229 |
+
row_ind, col_ind = linear_sum_assignment(-scores)
|
230 |
+
|
231 |
+
max_scores = np.zeros([max(len(gold), len(predicted))])
|
232 |
+
for row, column in zip(row_ind, col_ind):
|
233 |
+
max_scores[row] = max(max_scores[row], scores[row, column])
|
234 |
+
return max_scores
|
235 |
+
|
236 |
+
|
237 |
+
def _compute_f1(predicted_bag: Set[str], gold_bag: Set[str]) -> float:
|
238 |
+
intersection = len(gold_bag.intersection(predicted_bag))
|
239 |
+
if not predicted_bag:
|
240 |
+
precision = 1.0
|
241 |
+
else:
|
242 |
+
precision = intersection / float(len(predicted_bag))
|
243 |
+
if not gold_bag:
|
244 |
+
recall = 1.0
|
245 |
+
else:
|
246 |
+
recall = intersection / float(len(gold_bag))
|
247 |
+
f1 = (
|
248 |
+
(2 * precision * recall) / (precision + recall)
|
249 |
+
if not (precision == 0.0 and recall == 0.0)
|
250 |
+
else 0.0
|
251 |
+
)
|
252 |
+
return f1
|
253 |
+
|
254 |
+
|
255 |
+
def _match_numbers_if_present(gold_bag: Set[str], predicted_bag: Set[str]) -> bool:
|
256 |
+
gold_numbers = set()
|
257 |
+
predicted_numbers = set()
|
258 |
+
for word in gold_bag:
|
259 |
+
if _is_number(word):
|
260 |
+
gold_numbers.add(word)
|
261 |
+
for word in predicted_bag:
|
262 |
+
if _is_number(word):
|
263 |
+
predicted_numbers.add(word)
|
264 |
+
if (not gold_numbers) or gold_numbers.intersection(predicted_numbers):
|
265 |
+
return True
|
266 |
+
return False
|
267 |
+
|
268 |
+
|
269 |
+
|
270 |
+
def acc(predicted, gold):
|
271 |
+
predicted_bags = _answer_to_bags(predicted)
|
272 |
+
gold_bags = _answer_to_bags(gold)
|
273 |
+
if set(predicted_bags[0]) == set(gold_bags[0]) and len(predicted_bags[0]) == len(gold_bags[0]):
|
274 |
+
return 1.0
|
275 |
+
else:
|
276 |
+
return 0.0
|
277 |
+
|
278 |
+
|
279 |
+
def f1(predicted, gold):
|
280 |
+
predicted_bags = _answer_to_bags(predicted)
|
281 |
+
gold_bags = _answer_to_bags(gold)
|
282 |
+
f1_per_bag = _align_bags(predicted_bags[1], gold_bags[1])
|
283 |
+
f1 = np.mean(f1_per_bag)
|
284 |
+
f1 = round(f1, 2)
|
285 |
+
return f1
|
286 |
+
|
287 |
+
|
288 |
+
def metric_max_over_ground_truths(metric_fn, prediction, gold_answers):
|
289 |
+
scores_for_ground_truths = []
|
290 |
+
for gold_answer in gold_answers:
|
291 |
+
score = metric_fn(prediction, gold_answer)
|
292 |
+
scores_for_ground_truths.append(score)
|
293 |
+
return max(scores_for_ground_truths)
|
294 |
+
|
295 |
+
|
296 |
+
def evaluate_predictions(predictions, gold_answers, example_types=None):
|
297 |
+
"""To support multiple gold annotations, `gold_answers` should be a list,
|
298 |
+
with each item (either a string or a list) corresponding to one valid reference answer."""
|
299 |
+
instance_eval_results = {}
|
300 |
+
instance_eval_results_by_types = {}
|
301 |
+
eval_funcs = {
|
302 |
+
"acc": acc,
|
303 |
+
"f1": f1
|
304 |
+
}
|
305 |
+
for qas_id in gold_answers:
|
306 |
+
ref_answers = gold_answers[qas_id]
|
307 |
+
if qas_id not in predictions:
|
308 |
+
print(f"Missing prediction for question {qas_id}, and all scores for this question are set to zero")
|
309 |
+
instance_eval_results[qas_id] = {
|
310 |
+
metric: 0.0 for metric in eval_funcs.keys()
|
311 |
+
}
|
312 |
+
else:
|
313 |
+
pred_answer = predictions[qas_id]
|
314 |
+
instance_eval_results[qas_id] = {
|
315 |
+
metric: metric_max_over_ground_truths(
|
316 |
+
func, pred_answer, ref_answers
|
317 |
+
) for metric, func in eval_funcs.items()
|
318 |
+
}
|
319 |
+
if example_types is not None:
|
320 |
+
example_type = example_types[qas_id]
|
321 |
+
if example_type not in instance_eval_results_by_types:
|
322 |
+
instance_eval_results_by_types[example_type] = {}
|
323 |
+
instance_eval_results_by_types[example_type][qas_id] = instance_eval_results[qas_id]
|
324 |
+
|
325 |
+
eval_scores = {metric: np.mean([result[metric] for result in instance_eval_results.values()])
|
326 |
+
for metric in eval_funcs.keys()}
|
327 |
+
|
328 |
+
if example_types is not None:
|
329 |
+
eval_scores_by_types = {}
|
330 |
+
for example_type, type_instance_eval_results in instance_eval_results_by_types.items():
|
331 |
+
eval_scores_by_types[example_type] = {
|
332 |
+
metric: np.mean([result[metric] for result in type_instance_eval_results.values()]) for metric in eval_funcs.keys()
|
333 |
+
}
|
334 |
+
return eval_scores, instance_eval_results, eval_scores_by_types
|
335 |
+
else:
|
336 |
+
return eval_scores, instance_eval_results
|
337 |
+
|
338 |
+
|
339 |
+
def evaluate_prediction_file(prediction_path, gold_path):
|
340 |
+
predicted_answers = json.load(open(prediction_path, encoding="utf-8"))
|
341 |
+
examples = read_jsonl(gold_path)
|
342 |
+
gold_answers, answer_modalities, hop_types, question_types = {}, {}, {}, {}
|
343 |
+
for example in examples:
|
344 |
+
qid = example["qid"]
|
345 |
+
# Currently we only have one ground truth answer.
|
346 |
+
# Even if there are multiple entries in example["answers"], the whole list should be regarded as one ref answer.
|
347 |
+
# However, our script supports evaluation with multiple ref answers.
|
348 |
+
# So, we will use an outer bracket here to pretend we have a list of ref answers.
|
349 |
+
gold_answer = [str(item["answer"]) for item in example["answers"]]
|
350 |
+
gold_answers[qid] = [gold_answer]
|
351 |
+
answer_modality = set([item["modality"] for item in example["answers"]])
|
352 |
+
assert len(answer_modality) == 1
|
353 |
+
answer_modalities[qid] = answer_modality.pop()
|
354 |
+
question_types[qid] = example["metadata"]["type"]
|
355 |
+
hop_types[qid] = "Multi-hop" if example["metadata"]["type"] in MULTI_HOP_QUESTION_TYPES else "Single-hop"
|
356 |
+
|
357 |
+
eval_scores, instance_eval_results = evaluate_predictions(predicted_answers, gold_answers)
|
358 |
+
print("\n\nOverall result with different metrics: ")
|
359 |
+
for metric, value in eval_scores.items():
|
360 |
+
print(f"{metric}: {value}")
|
361 |
+
|
362 |
+
modality_counts = Counter(answer_modalities.values())
|
363 |
+
_, _, eval_scores_by_modalities = \
|
364 |
+
evaluate_predictions(predicted_answers, gold_answers, answer_modalities)
|
365 |
+
print("\n\nEval results for different modalities:")
|
366 |
+
for answer_modality in sorted(eval_scores_by_modalities.keys()):
|
367 |
+
result = eval_scores_by_modalities[answer_modality]
|
368 |
+
print(f"{answer_modality}")
|
369 |
+
print(f"# of examples: {modality_counts[answer_modality]}")
|
370 |
+
for metric, value in result.items():
|
371 |
+
print(f"{metric}: {value}")
|
372 |
+
|
373 |
+
hop_type_counts = Counter(hop_types.values())
|
374 |
+
_, _, eval_scores_by_hop_types = evaluate_predictions(predicted_answers, gold_answers, hop_types)
|
375 |
+
print("\n\nType\tCount\tEM\tF1")
|
376 |
+
for hop_type in sorted(eval_scores_by_hop_types.keys()):
|
377 |
+
result = eval_scores_by_hop_types[hop_type]
|
378 |
+
print(f"{hop_type}\t{hop_type_counts[hop_type]}\t{result['acc']}\t{result['f1']}")
|
379 |
+
|
380 |
+
question_type_counts = Counter(question_types.values())
|
381 |
+
_, _, eval_scores_by_qtypes = evaluate_predictions(predicted_answers, gold_answers, question_types)
|
382 |
+
print("\n\nType\tCount\tEM\tF1")
|
383 |
+
for question_type in sorted(eval_scores_by_qtypes.keys()):
|
384 |
+
result = eval_scores_by_qtypes[question_type]
|
385 |
+
print(f"{question_type}\t{question_type_counts[question_type]}\t{result['acc']}\t{result['f1']}")
|
386 |
+
return eval_scores
|
387 |
+
|
388 |
+
|
389 |
+
class EvaluateTool(object):
|
390 |
+
|
391 |
+
def __init__(self, args):
|
392 |
+
self.args = args
|
393 |
+
|
394 |
+
def evaluate(self, preds, golds, section):
|
395 |
+
summary = {}
|
396 |
+
|
397 |
+
gold_answers, predicted_answers = {}, {}
|
398 |
+
for pred, gold in zip(preds, golds):
|
399 |
+
qid = gold["id"]
|
400 |
+
gold_answer = [item.strip() for item in gold["answer_text"].split("|")]
|
401 |
+
gold_answers[qid] = [gold_answer]
|
402 |
+
predicted_answers[qid] = [item.strip() for item in pred.split("|")]
|
403 |
+
|
404 |
+
eval_scores, instance_eval_results = evaluate_predictions(predicted_answers, gold_answers)
|
405 |
+
|
406 |
+
for metric, value in eval_scores.items():
|
407 |
+
summary[metric] = value
|
408 |
+
return summary
|
utils/mmqa/image_stuff.py
ADDED
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import json
|
2 |
+
import os
|
3 |
+
|
4 |
+
ROOT_DIR = os.path.join(os.path.dirname(__file__), "../../")
|
5 |
+
|
6 |
+
|
7 |
+
def get_caption_map(file_path=None):
|
8 |
+
"""
|
9 |
+
Get the caption map.
|
10 |
+
"""
|
11 |
+
if not file_path:
|
12 |
+
file_path = os.path.join(ROOT_DIR, 'utils', 'mmqa', 'mmqa_captions.json')
|
13 |
+
|
14 |
+
with open(file_path, "r") as f:
|
15 |
+
caption_map = json.load(f)
|
16 |
+
return caption_map
|
17 |
+
|
18 |
+
|
19 |
+
def get_caption(id):
|
20 |
+
"""
|
21 |
+
Get the caption of the picture by id.
|
22 |
+
"""
|
23 |
+
with open(os.path.join(ROOT_DIR, 'utils', 'mmqa', "mmqa_captions.json"), "r") as f:
|
24 |
+
caption = json.load(f)
|
25 |
+
if id in caption.keys():
|
26 |
+
return caption[id]
|
27 |
+
else:
|
28 |
+
return ""
|
utils/mmqa/mmqa_captions.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|
utils/mmqa/qc_mmqa_dev.csv
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
,question,gold,prediction,id,all_answers,em,f1
|
2 |
+
0,QA: For which film did Ben Piazza play the role of Mr. Simms?,['no'],['no'],a33985b1e8b2502fc18cc8147dc27db8,"[""no""]",1.0,1.0
|
utils/mmqa/qimc.py
ADDED
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import json
|
2 |
+
import os
|
3 |
+
import pandas as pd
|
4 |
+
|
5 |
+
ROOT_DIR = os.path.join(os.path.dirname(__file__), "../../")
|
6 |
+
|
7 |
+
|
8 |
+
class Question_Image_Match_Classifier(object):
|
9 |
+
"""result are from a T5-3b model finetuned on train set of MMQA."""
|
10 |
+
|
11 |
+
def __init__(self):
|
12 |
+
self.whether_retrieve_image = None
|
13 |
+
self.qi_pairs_should_retrieve = None
|
14 |
+
self.load_retrieve_info()
|
15 |
+
self.caption_info = None
|
16 |
+
with open(os.path.join(ROOT_DIR, "utils", "mmqa", "mmqa_captions.json"), "r") as f:
|
17 |
+
self.caption_info = json.load(f)
|
18 |
+
|
19 |
+
def load_retrieve_info(self):
|
20 |
+
df_qc = pd.read_csv(os.path.join(ROOT_DIR, "utils", "mmqa", "qc_mmqa_dev.csv"))
|
21 |
+
whether_retrieve_image = {}
|
22 |
+
for index, row in df_qc.iterrows():
|
23 |
+
_id = row['id']
|
24 |
+
prediction = row['prediction']
|
25 |
+
whether_retrieve_image[_id] = True if prediction == "['yes']" else False
|
26 |
+
self.whether_retrieve_image = whether_retrieve_image
|
27 |
+
|
28 |
+
df_qimc = pd.read_csv(os.path.join(ROOT_DIR, "utils", "mmqa", "qimc_mmqa_dev.csv"))
|
29 |
+
qi_pairs_should_retrieve = {}
|
30 |
+
for index, row in df_qimc.iterrows():
|
31 |
+
qa = row['question'].lower()
|
32 |
+
prediction = row['prediction']
|
33 |
+
qi_pairs_should_retrieve[qa] = True if prediction == "['yes']" else False
|
34 |
+
self.qi_pairs_should_retrieve = qi_pairs_should_retrieve
|
35 |
+
|
36 |
+
def judge_match(self, _id, question, pic):
|
37 |
+
# fixme: hardcode since it is done in pipeline, change that in the future
|
38 |
+
if not self.whether_retrieve_image[_id]:
|
39 |
+
return False
|
40 |
+
image_caption = self.caption_info[os.path.split(pic)[-1].split(".")[0]]
|
41 |
+
return self.qi_pairs_should_retrieve['qa: {} \n{}'.format(question.lower(), image_caption.lower())]
|
utils/mmqa/qimc_mmqa_dev.csv
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
,question,gold,prediction,id,all_answers,em,f1
|
2 |
+
0,"QA: For which film did Ben Piazza play the role of Mr. Simms?
|
3 |
+
poster art for ``the concorde'' of the united states of america 00 00 00",['no'],['no'],a33985b1e8b2502fc18cc8147dc27db8,"[""no""]",1.0,1.0
|
utils/mmqa/qpmc.py
ADDED
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import pandas as pd
|
3 |
+
|
4 |
+
ROOT_DIR = os.path.join(os.path.dirname(__file__), "../../")
|
5 |
+
|
6 |
+
|
7 |
+
class Question_Passage_Match_Classifier(object):
|
8 |
+
"""result are from a T5-3b model finetuned on train set of MMQA."""
|
9 |
+
|
10 |
+
def __init__(self):
|
11 |
+
self.qa_pairs_should_retrieve = None
|
12 |
+
self.load_retrieve_info()
|
13 |
+
|
14 |
+
def load_retrieve_info(self):
|
15 |
+
df = pd.read_csv(os.path.join(ROOT_DIR, "utils", "mmqa", "qpmc_mmqa_dev.csv"))
|
16 |
+
qa_pairs_should_retrieve = {}
|
17 |
+
for index, row in df.iterrows():
|
18 |
+
qa = row['question'].lower()
|
19 |
+
prediction = row['prediction']
|
20 |
+
qa_pairs_should_retrieve[qa] = True if prediction == "['yes']" else False
|
21 |
+
self.qa_pairs_should_retrieve = qa_pairs_should_retrieve
|
22 |
+
|
23 |
+
def judge_match(self, question, passage):
|
24 |
+
return self.qa_pairs_should_retrieve['qa: {} \n {}'.format(question.lower(), passage.lower())]
|
utils/mmqa/qpmc_mmqa_dev.csv
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
,question,gold,prediction,id,all_answers,em,f1
|
2 |
+
0,"QA: For which film did Ben Piazza play the role of Mr. Simms?
|
3 |
+
Thomas Peter Shadyac (born December 11, 1958) is an American director, screenwriter, producer, and author. Shadyac, was the youngest joke-writer ever for comedian Bob Hope, is widely known for writing and directing the comedies """", ""The Nutty Professor"", ""Liar Liar"", ""Patch Adams"", and ""Bruce Almighty"". In 2010, Shadyac departed from comedic work to write, direct, and narrate his documentary film ""I Am"", in which he explores his abandonment of a materialistic lifestyle following a bicycle accident three years earlier.",['no'],['no'],a33985b1e8b2502fc18cc8147dc27db8,"[""no""]",1.0,1.0
|