Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

utils_qa.py 12 KB

You have to be logged in to leave a comment. Sign In
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
364
365
366
367
368
369
370
371
  1. import json,time
  2. import numpy as np
  3. import pandas as pd
  4. import os
  5. import subprocess
  6. import operator
  7. import random
  8. import logging
  9. import collections
  10. from collections import Counter, OrderedDict
  11. from transformers.data.processors.squad import SquadExample
  12. import pdb
  13. logger = logging.getLogger(__name__)
  14. def transform_n2b_yesno(nbest_path, output_path):
  15. ### Setting basic strings
  16. #### Checking nbest_BioASQ-test prediction.json
  17. if not os.path.exists(nbest_path):
  18. print("No file exists!\n#### Fatal Error : Abort!")
  19. raise
  20. #### Reading Pred File
  21. with open(nbest_path, "r") as reader:
  22. test=json.load(reader)
  23. qidDict=dict()
  24. if True: # multi output
  25. for multiQid in test:
  26. assert len(multiQid)==(24+4) # all multiQid should have length of 24 + 3
  27. if not multiQid[:-4] in qidDict:
  28. qidDict[multiQid[:-4]]=[test[multiQid]]
  29. else :
  30. qidDict[multiQid[:-4]].append(test[multiQid])
  31. else: # single output
  32. qidDict={qid:[test[qid]] for qid in test}
  33. entryList=[]
  34. print(len(qidDict), 'number of questions')
  35. for qid in qidDict:
  36. yesno_prob = {'yes': [], 'no': []}
  37. yesno_cnt = 0
  38. for ans, prob in qidDict[qid]:
  39. yesno_prob['yes'] += [float('{:.3f}'.format(prob[0]))] # For sigmoid
  40. yesno_cnt += 1
  41. mean = lambda x: sum(x)/len(x)
  42. final_answer = 'yes' if mean(yesno_prob['yes']) > 0.5 else 'no'
  43. entry={u"type": "yesno",
  44. u"id": qid,
  45. u"ideal_answer": ["Dummy"],
  46. u"exact_answer": final_answer,
  47. }
  48. entryList.append(entry)
  49. finalformat={u'questions':entryList}
  50. if os.path.isdir(output_path):
  51. outfilepath=os.path.join(output_path, "BioASQform_BioASQ-answer.json") # For unified output name
  52. else:
  53. outfilepath=output_path
  54. with open(outfilepath, "w") as outfile:
  55. json.dump(finalformat, outfile, indent=2)
  56. print("outfilepath={}".format(outfilepath))
  57. def textrip(text):
  58. if text=="":
  59. return text
  60. if text[-1]==',' or text[-1]=='.' or text[-1]==' ':
  61. return text[:-1]
  62. if len(text)>2 and text[0]=='(' and text[-1]==')':
  63. if text.count('(')==1 and text.count(')')==1:
  64. return text[1:-1]
  65. if ('(' in text) and (')' not in text):
  66. return ""
  67. if ('(' not in text) and (')' in text):
  68. return ""
  69. return text
  70. def transform_n2b_factoid(nbest_path, output_path):
  71. #### Checking nbest_BioASQ-test prediction.json
  72. if not os.path.exists(nbest_path):
  73. print("No file exists!\n#### Fatal Error : Abort!")
  74. raise
  75. #### Reading Pred File
  76. with open(nbest_path, "r") as reader:
  77. test=json.load(reader)
  78. qidDict=dict()
  79. if True:
  80. for multiQid in test:
  81. assert len(multiQid)==(24+4) # all multiQid should have length of 24 + 3
  82. if not multiQid[:-4] in qidDict:
  83. qidDict[multiQid[:-4]]=[test[multiQid]]
  84. else :
  85. qidDict[multiQid[:-4]].append(test[multiQid])
  86. else: # single output
  87. qidDict={qid:[test[qid]] for qid in test}
  88. entryList=[]
  89. entryListWithProb=[]
  90. for qid in qidDict:
  91. jsonList=[]
  92. for jsonele in qidDict[qid]: # value of qidDict is a list
  93. jsonList+=jsonele
  94. qidDf=pd.DataFrame().from_dict(jsonList)
  95. sortedDf=qidDf.sort_values(by='probability', axis=0, ascending=False)
  96. sortedSumDict=OrderedDict()
  97. sortedSumDictKeyDict=dict() # key : noramlized key
  98. for index in sortedDf.index:
  99. text=sortedDf.loc[index]["text"]
  100. text=textrip(text)
  101. if text=="":
  102. pass
  103. elif len(text)>100:
  104. pass
  105. elif text.lower() in sortedSumDictKeyDict:
  106. sortedSumDict[sortedSumDictKeyDict[text.lower()]] += sortedDf.loc[index]["probability"]
  107. else:
  108. sortedSumDictKeyDict[text.lower()]=text
  109. sortedSumDict[sortedSumDictKeyDict[text.lower()]] = sortedDf.loc[index]["probability"]
  110. finalSorted=sorted(sortedSumDict.items(), key=operator.itemgetter(1), reverse=True) # for python 2, use sortedSumDict.iteritems() instead of sortedSumDict.items()
  111. entry={u"type":"factoid",
  112. #u"body":qas,
  113. u"id":qid, # must be 24 char
  114. u"ideal_answer":["Dummy"],
  115. u"exact_answer":[[ans[0]] for ans in finalSorted[:5]],
  116. # I think enough?
  117. }
  118. entryList.append(entry)
  119. entryWithProb={u"type":"factoid",
  120. u"id":qid, # must be 24 char
  121. u"ideal_answer":["Dummy"],
  122. u"exact_answer":[ans for ans in finalSorted[:20]],
  123. }
  124. entryListWithProb.append(entryWithProb)
  125. finalformat={u'questions':entryList}
  126. finalformatWithProb={u'questions':entryListWithProb}
  127. if os.path.isdir(output_path):
  128. outfilepath=os.path.join(output_path, "BioASQform_BioASQ-answer.json")
  129. outWithProbfilepath=os.path.join(output_path, "WithProb_BioASQform_BioASQ-answer.json")
  130. else:
  131. outfilepath=output_path
  132. outWithProbfilepath= output_path+"_WithProb"
  133. with open(outfilepath, "w") as outfile:
  134. json.dump(finalformat, outfile, indent=2)
  135. with open(outWithProbfilepath, "w") as outfile_prob:
  136. json.dump(finalformatWithProb, outfile_prob, indent=2)
  137. def eval_bioasq_standard(task_num, outfile, golden, cwd):
  138. # 1: [1, 2], 3: [3, 4], 5: [5, 6, 7, 8]
  139. task_e = {
  140. '1': 1, '2': 1,
  141. '3': 3, '4': 3,
  142. '5': 5, '6': 5, '7': 5, '8': 5
  143. }
  144. golden = os.path.join(os.getcwd(), golden)
  145. outfile = os.path.join(os.getcwd(), outfile)
  146. evalproc1 = subprocess.Popen(
  147. ['java', '-Xmx10G', '-cp',
  148. '$CLASSPATH:./flat/BioASQEvaluation/dist/BioASQEvaluation.jar',
  149. 'evaluation.EvaluatorTask1b', '-phaseB',
  150. '-e', '{}'.format(task_e[task_num]),
  151. golden,
  152. outfile],
  153. cwd=cwd,
  154. stdout=subprocess.PIPE
  155. )
  156. stdout1, _ = evalproc1.communicate()
  157. result = [float(v) for v in stdout1.decode('utf-8').split(' ')]
  158. return result
  159. def read_squad_examples(input_file, is_training):
  160. """Read a SQuAD json file into a list of SquadExample."""
  161. is_bioasq=True # for BioASQ
  162. with open(input_file, "r") as reader:
  163. input_data = json.load(reader)["data"]
  164. def is_whitespace(c):
  165. if c == " " or c == "\t" or c == "\r" or c == "\n" or ord(c) == 0x202F:
  166. return True
  167. return False
  168. examples = []
  169. for entry in input_data:
  170. for paragraph in entry["paragraphs"]:
  171. paragraph_text = paragraph["context"]
  172. doc_tokens = []
  173. char_to_word_offset = []
  174. prev_is_whitespace = True
  175. if is_bioasq:
  176. paragraph_text.replace('/',' ') # need review
  177. for c in paragraph_text:
  178. if is_whitespace(c):
  179. prev_is_whitespace = True
  180. else:
  181. if prev_is_whitespace:
  182. doc_tokens.append(c)
  183. else:
  184. doc_tokens[-1] += c
  185. prev_is_whitespace = False
  186. char_to_word_offset.append(len(doc_tokens) - 1)
  187. for qa in paragraph["qas"]:
  188. qas_id = qa["id"]
  189. question_text = qa["question"]
  190. answer = None
  191. is_impossible = False
  192. if is_training:
  193. assert (qa["is_impossible"] == True) != (qa["answers"] == "yes")
  194. assert qa["answers"] in ["yes", "no"]
  195. # answer = 1 if qa["answers"] == 'yes' else 0
  196. is_impossible = qa["is_impossible"]
  197. example = SquadExample(
  198. qas_id=qas_id,
  199. question_text=question_text,
  200. context_text=paragraph_text,
  201. answer_text='',
  202. start_position_character=None,
  203. title='',
  204. answers=[],
  205. is_impossible=is_impossible,
  206. )
  207. examples.append(example)
  208. # target_cnt = 500
  209. if is_training:
  210. pos_cnt = sum([1 for example in examples if example.is_impossible == False])
  211. neg_cnt = sum([1 for example in examples if example.is_impossible == True])
  212. target_cnt = min(pos_cnt,neg_cnt)
  213. print()
  214. print('Imbalance btw {} vs {}'.format(pos_cnt, neg_cnt))
  215. random.shuffle(examples)
  216. new_examples = []
  217. new_pos_cnt = 0
  218. new_neg_cnt = 0
  219. for example in examples:
  220. if example.is_impossible == False and new_pos_cnt >= target_cnt:
  221. continue
  222. if example.is_impossible == True and new_neg_cnt >= target_cnt:
  223. continue
  224. else:
  225. new_examples.append(example)
  226. new_pos_cnt += (1 if example.is_impossible == False else 0)
  227. new_neg_cnt += (1 if example.is_impossible == True else 0)
  228. pos_cnt = sum([1 for example in new_examples if example.is_impossible == False])
  229. neg_cnt = sum([1 for example in new_examples if example.is_impossible == True])
  230. random.shuffle(new_examples)
  231. print('Balanced as {} vs {}'.format(pos_cnt, neg_cnt))
  232. print('Sample: {}'.format(new_examples[0]))
  233. return new_examples
  234. else:
  235. return examples
  236. def write_predictions(all_examples, all_features, all_results, output_prediction_file):
  237. """Write final predictions to the json file and log-odds of null if needed."""
  238. logger.info("Writing predictions to: %s" % (output_prediction_file))
  239. example_index_to_features = collections.defaultdict(list)
  240. for feature in all_features:
  241. example_index_to_features[feature.example_index].append(feature)
  242. unique_id_to_result = {}
  243. for result in all_results:
  244. unique_id_to_result[result.unique_id] = result
  245. _PrelimPrediction = collections.namedtuple( # pylint: disable=invalid-name
  246. "PrelimPrediction",
  247. ["feature_index", "answer", "logit"])
  248. all_predictions = collections.OrderedDict()
  249. all_nbest_json = collections.OrderedDict()
  250. scores_diff_json = collections.OrderedDict()
  251. for (example_index, example) in enumerate(all_examples):
  252. features = example_index_to_features[example_index]
  253. prelim_predictions = []
  254. # keep track of the minimum score of null start+end of position 0
  255. score_null = 1000000 # large and positive
  256. for (feature_index, feature) in enumerate(features):
  257. result = unique_id_to_result[feature.unique_id]
  258. logits = result.logits
  259. answer = 'yes' if logits[0] > 0.5 else 'no'
  260. prelim_predictions.append(
  261. _PrelimPrediction(
  262. feature_index=feature_index,
  263. answer=answer,
  264. logit=logits))
  265. break
  266. assert len(prelim_predictions) == 1
  267. probs = logits
  268. all_predictions[example.qas_id] = [prelim_predictions[0].answer, probs]
  269. with open(output_prediction_file, "w") as writer:
  270. writer.write(json.dumps(all_predictions, indent=4) + "\n")
  271. if __name__ == '__main__':
  272. import argparse
  273. parser = argparse.ArgumentParser()
  274. parser.add_argument(
  275. "--output_dir",
  276. default=None,
  277. type=str,
  278. required=True,
  279. help="The output directory where the model checkpoints will be written."
  280. )
  281. parser.add_argument(
  282. "--nbest_path",
  283. default=None,
  284. type=str,
  285. help="The output directory where the model checkpoints will be written."
  286. )
  287. parser.add_argument(
  288. "--golden_file",
  289. default=None,
  290. type=str,
  291. help="BioASQ official golden answer file"
  292. )
  293. parser.add_argument(
  294. "--official_eval_dir",
  295. default='./scripts/bioasq_eval',
  296. type=str,
  297. help="BioASQ official evaluation code"
  298. )
  299. args = parser.parse_args()
  300. transform_n2b_factoid(args.nbest_path, args.output_dir)
  301. """ Evaluation - Measure
  302. pred_file = os.path.join(args.output_dir, "BioASQform_BioASQ-answer.json")
  303. eval_bioasq_standard(str(5),
  304. pred_file,
  305. args.golden_file,
  306. args.official_eval_dir)
  307. """
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...