MCPcopy Create free account
hub / github.com/pytorch/tutorials / compute_metrics

Function compute_metrics

advanced_source/semi_structured_sparse.py:299–356  ·  view source on GitHub ↗
(start_logits, end_logits, features, examples)

Source from the content-addressed store, hash-verified

297
298
299def compute_metrics(start_logits, end_logits, features, examples):
300 n_best = 20
301 max_answer_length = 30
302 metric = evaluate.load("squad")
303
304 example_to_features = collections.defaultdict(list)
305 for idx, feature in enumerate(features):
306 example_to_features[feature["example_id"]].append(idx)
307
308 predicted_answers = []
309 # for example in ``tqdm`` (examples):
310 for example in examples:
311 example_id = example["id"]
312 context = example["context"]
313 answers = []
314
315 # Loop through all features associated with that example
316 for feature_index in example_to_features[example_id]:
317 start_logit = start_logits[feature_index]
318 end_logit = end_logits[feature_index]
319 offsets = features[feature_index]["offset_mapping"]
320
321 start_indexes = np.argsort(start_logit)[-1 : -n_best - 1 : -1].tolist()
322 end_indexes = np.argsort(end_logit)[-1 : -n_best - 1 : -1].tolist()
323 for start_index in start_indexes:
324 for end_index in end_indexes:
325 # Skip answers that are not fully in the context
326 if offsets[start_index] is None or offsets[end_index] is None:
327 continue
328 # Skip answers with a length that is either < 0
329 # or > max_answer_length
330 if (
331 end_index < start_index
332 or end_index - start_index + 1 > max_answer_length
333 ):
334 continue
335
336 answer = {
337 "text": context[
338 offsets[start_index][0] : offsets[end_index][1]
339 ],
340 "logit_score": start_logit[start_index] + end_logit[end_index],
341 }
342 answers.append(answer)
343
344 # Select the answer with the best score
345 if len(answers) > 0:
346 best_answer = max(answers, key=lambda x: x["logit_score"])
347 predicted_answers.append(
348 {"id": example_id, "prediction_text": best_answer["text"]}
349 )
350 else:
351 predicted_answers.append({"id": example_id, "prediction_text": ""})
352
353 theoretical_answers = [
354 {"id": ex["id"], "answers": ex["answers"]} for ex in examples
355 ]
356 return metric.compute(predictions=predicted_answers, references=theoretical_answers)

Callers 1

Calls

no outgoing calls

Tested by

no test coverage detected