Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 17 additions & 24 deletions metrics/squad_v2/compute_score.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@


ARTICLES_REGEX = re.compile(r"\b(a|an|the)\b", re.UNICODE)
PUNCTUATION_TABLE = str.maketrans("", "", string.punctuation)

OPTS = None

Expand Down Expand Up @@ -59,21 +60,8 @@ def make_qid_to_has_ans(dataset):

def normalize_answer(s):
"""Lower text and remove punctuation, articles and extra whitespace."""

def remove_articles(text):
return ARTICLES_REGEX.sub(" ", 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))))
text = s.lower().translate(PUNCTUATION_TABLE)
return " ".join(ARTICLES_REGEX.sub(" ", text).split())


def get_tokens(s):
Expand All @@ -89,11 +77,15 @@ def compute_exact(a_gold, a_pred):
def compute_f1(a_gold, a_pred):
gold_toks = get_tokens(a_gold)
pred_toks = get_tokens(a_pred)
common = collections.Counter(gold_toks) & collections.Counter(pred_toks)
num_same = sum(common.values())
return _token_f1(gold_toks, pred_toks, collections.Counter(pred_toks))


def _token_f1(gold_toks, pred_toks, pred_counts):
if len(gold_toks) == 0 or len(pred_toks) == 0:
# If either is no-answer, then F1 is 1 if they agree, 0 otherwise
return int(gold_toks == pred_toks)
common = collections.Counter(gold_toks) & pred_counts
num_same = sum(common.values())
if num_same == 0:
return 0
precision = 1.0 * num_same / len(pred_toks)
Expand All @@ -109,17 +101,18 @@ def get_raw_scores(dataset, preds):
for p in article["paragraphs"]:
for qa in p["qas"]:
qid = qa["id"]
gold_answers = [t for t in qa["answers"]["text"] if normalize_answer(t)]
if not gold_answers:
# For unanswerable questions, only correct answer is empty string
gold_answers = [""]
if qid not in preds:
print(f"Missing prediction for {qid}")
continue
a_pred = preds[qid]
gold_answers = (normalize_answer(text) for text in qa["answers"]["text"])
# An empty answer is correct only when there are no valid gold answers.
gold_answers = [answer for answer in gold_answers if answer] or [""]
a_pred = normalize_answer(preds[qid])
pred_toks = a_pred.split()
pred_counts = collections.Counter(pred_toks)
# Take max over all gold answers
exact_scores[qid] = max(compute_exact(a, a_pred) for a in gold_answers)
f1_scores[qid] = max(compute_f1(a, a_pred) for a in gold_answers)
exact_scores[qid] = int(a_pred in gold_answers)
f1_scores[qid] = max(_token_f1(answer.split(), pred_toks, pred_counts) for answer in gold_answers)
return exact_scores, f1_scores


Expand Down
29 changes: 29 additions & 0 deletions tests/test_squad_v2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
from pathlib import Path

import pytest

import evaluate


SQUAD_V2_PATH = Path(__file__).resolve().parents[1] / "metrics" / "squad_v2"


@pytest.mark.parametrize(
"prediction, answers, expected_exact, expected_f1",
[
("the co-op co-op alpha", ["coop beta", "a co-op co-op", "THE!"], 0.0, 80.0),
(" The co-op's plan.\t", ["a plan", "COOPS plan"], 100.0, 100.0),
("the !", [], 100.0, 100.0),
("something", ["The!", ""], 0.0, 0.0),
],
)
def test_squad_v2_scores(prediction, answers, expected_exact, expected_f1, tmp_path):
metric = evaluate.load(str(SQUAD_V2_PATH), cache_dir=str(tmp_path), keep_in_memory=True)
result = metric.compute(
predictions=[{"id": "question", "prediction_text": prediction, "no_answer_probability": 0.0}],
references=[{"id": "question", "answers": {"text": answers, "answer_start": [0] * len(answers)}}],
)

assert result["exact"] == expected_exact
assert result["f1"] == pytest.approx(expected_f1)
assert result["total"] == 1