Suryanand/ Bootcamp
suryanand.com ↗Let's talk
Frame · dsa / ai-algorithms / 16-exact-match-and-token-f1.jsJavaScript

Exact Match and Token-Level F1 for QA Evals

Use the tabs to read the prompt, implementation, and tests separately. Syntax uses Shiki; tests can be executed on the server with node --test.

Same file as in the repo · ~20s timeout

From file header (JSDoc)

Exact Match and Token-Level F1 for QA Evals

Problem: Implement the SQuAD-style metrics used to score extractive and
generative question answering.
- `normalizeAnswer(s)`: lowercase, remove punctuation, remove the articles
  "a", "an", "the", and collapse whitespace.
- `exactMatch(prediction, gold)`: 1 if normalised strings are equal, else 0.
- `tokenF1(prediction, gold)`: treat normalised answers as bags of tokens;
  overlap = size of the multiset intersection; precision = overlap / |pred|,
  recall = overlap / |gold|, F1 = 2PR / (P + R) (0 when overlap is 0; if
  both are empty, 1).
- `scoreQA(prediction, golds)`: `{ em, f1 }`, each the max over all gold
  answers.

Constraints:
- answers up to 10^4 characters, 1 <= golds.length <= 20

Example:
  prediction "The Eiffel Tower!", gold "eiffel tower"  -> em 1, f1 1
  prediction "in Paris France", gold "Paris"           -> em 0, f1 0.5

Approach: Normalise both strings, count gold tokens in a map, then walk the
prediction tokens decrementing counts to compute the overlap. Time
O(|pred| + |gold|) per pair, space O(|gold|).
@param {string} prediction
@param {string[]} golds
@returns {{ em: number, f1: number }}
Why this exists README

I learn best by explaining things, so I record the explanations. Everything here is free, with no sign-up. If a lesson helps you ship something, I'd love to hear about it.