Scoring Parsed Payroll Form Output Against Ground Truth
Arrays & HashingModel answerLast updated
Write a scorer that compares fields extracted from tax forms to a ground-truth mapping, normalizing keys and currency, then reporting match rate, missing and mismatched fields, and precision/recall.
Scoring a Tax-Form Extractor
A machine-learning service reads scanned wage-and-tax statement PDFs and emits one Python dictionary per form it recognized. You are asked to build the offline scorer that checks those outputs against a human-verified answer key.
Inputs
extracted_records: a list of 1 to 50 dictionaries produced by the service. Keys may be capitalized or spelled differently from the answer key, and values may be strings such as"$1,200.50", numbers, orNone. Entries may lack some fields entirely.reference_data: a dictionary that maps each employer identifier (an EIN such as"12-3456789") to a dictionary of the true field values, e.g.{'wages': 50000.00, 'tax': 5000.00}.
Task
Implement evaluate_extraction(extracted_records, reference_data) -> dict so that it does the following.
- Link records to the key. Pair each extracted record with a reference entry using the employer identifier. When several extracted records share one identifier, combine them into a single view of that employer (or choose the best candidate) and say how you decided.
- Normalize before comparing.
- Lowercase all keys, and map known alternative names to the canonical name (for example
tax_withheldmeanstax). - Turn currency strings like
"$1,200.50"into floats. - Treat
Noneand blank values as "not extracted."
- Lowercase all keys, and map known alternative names to the canonical name (for example
- Measure quality. For each reference employer, list the expected fields that are missing and the ones whose values differ. Also compute the overall match rate (the fraction of reference employers that received at least one extracted record), plus precision and recall at the field level.
Signature
def evaluate_extraction(extracted_records: list[dict], reference_data: dict) -> dict:
...
Example
extracted = [{'ein': '12-3456789', 'wages': '$50,000.00'}]
reference = {'12-3456789': {'wages': 50000.00, 'tax': 5000.00}}
Expected result:
{
'match_rate': 1.0,
'errors': {'12-3456789': {'missing_fields': ['tax'], 'mismatched_values': {}}}
}
Rules and edge cases
- Handle
Nonevalues and absent keys without raising. - If the extractor used a different name for a field (e.g.
tax_withheldfortax), it should still be credited once the name is normalized. - If an extracted record contains fields that the reference schema does not define (possible leakage of unrelated data), they must not count as correct; decide how to report them and how they affect precision.
- Be explicit about what happens with records whose identifier is absent or unknown, and about division by zero in the metrics.
You may add extra keys to the report (such as precision and recall) as long as the structure in the example is preserved.
Hints
Hint 1
Split the work into three independent stages: normalize keys and values, match and merge records by identifier, then score field by field.
Hint 2
Index the reference by a digit-only version of the EIN so that '12-3456789' and '123456789' land on the same entry, but report errors under the original key.
Hint 3
Every expected field should fall in exactly one bucket: correct, missing, or mismatched. Extra fields only affect precision, and empty denominators should return 1.0 instead of dividing by zero.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is a reconciliation problem. I would keep three stages separate, since each has its own failure modes and is easy to test alone.
1. Normalize
- Keys: strip, lowercase, convert spaces and hyphens to underscores, then map through an alias table (
tax_withheld,federal_income_tax_withheld,federal_taxall becometax;employer_einbecomesein). A renamed field is then scored as correct instead of as one missing plus one extra field. - Values:
None, empty, and whitespace-only values become "not extracted."- Numbers become floats.
- Currency strings are parsed after removing
$, commas, and spaces. Negatives in the forms-$5,$-5, and(5.00)become negative. - Anything that is not clearly numeric is lowercased and whitespace-collapsed and compared as text. This stops a control number like
12-3456789from being mangled into a number.
- EIN: reduce to digits only for lookup.
2. Match and merge
- Build
ein_index: digit-only EIN to the reference's original key. Lookup is O(1). - Bucket each extracted record under its reference EIN, collecting a list of candidate values per field.
- Records with no EIN, or an EIN not in the reference, go to
unmatched_eins. Their fields still count as extracted, so they lower precision. - When several records share an EIN, merge field by field: choose the candidate that equals the reference value if one exists, otherwise the first. This is slightly optimistic, because it uses the answer key to resolve conflicts. State this trade-off. A stricter evaluator would flag conflicting duplicates as an error or take the first/highest-confidence value without peeking.
3. Score
For each reference EIN, compare the merged fields with the expected ones:
- missing: expected but absent.
- mismatched: present with a different value, reported as
{field: {'expected': ..., 'got': ...}}. - extra: present but not in the reference schema (the leakage case).
- correct: equal values. Numbers use a half-cent tolerance (
abs(a-b) < 0.005) so float noise does not create false mismatches.
Metrics:
match_rate= reference EINs with at least one extracted record / total reference EINs.precision= correct fields / all extracted fields, including extras and fields from unmatched records.recall= correct fields / all expected fields.- A zero denominator returns 1.0 (vacuously perfect), so there is no division by zero.
Because each expected field lands in exactly one of correct, missing, or mismatched, the counts always add up. Extra fields hurt precision but never recall.
Code
import re
from typing import Any
ALIASES = {
"employer_ein": "ein",
"tax_withheld": "tax",
"federal_income_tax_withheld": "tax",
"federal_tax": "tax",
"wages_tips_other_compensation": "wages",
}
NUM_RE = re.compile(r"^\(?-?\$?-?[\d,]*\.?\d+\)?$")
TOL = 0.005
def norm_key(k):
k = str(k).strip().lower().replace(" ", "_").replace("-", "_")
return ALIASES.get(k, k)
def norm_ein(v):
if v is None:
return None
d = re.sub(r"\D", "", str(v))
return d or None
def norm_value(v):
if v is None:
return None
if isinstance(v, bool):
return v
if isinstance(v, (int, float)):
return float(v)
s = str(v).strip()
if not s:
return None
c = s.replace(" ", "")
if NUM_RE.match(c):
neg = (c.startswith("(") and c.endswith(")")) or "-" in c
try:
x = float(re.sub(r"[^\d.]", "", c))
return -x if neg else x
except ValueError:
pass
return " ".join(s.lower().split())
def equal(a, b):
if isinstance(a, float) and isinstance(b, float):
return abs(a - b) < TOL
return a == b
def ratio(n, d):
return n / d if d else 1.0
def evaluate_extraction(extracted_records, reference_data):
ref, ein_index = {}, {}
for ref_ein, fields in (reference_data or {}).items():
key = norm_ein(ref_ein)
if key is None:
continue
ein_index[key] = ref_ein
clean = {}
for k, v in (fields or {}).items():
nk, nv = norm_key(k), norm_value(v)
if nk != "ein" and nv is not None:
clean[nk] = nv
ref[ref_ein] = clean
candidates, unmatched, unmatched_cnt = {}, [], 0
for rec in extracted_records or []:
if not isinstance(rec, dict):
continue
raw_ein, norm = None, {}
for k, v in rec.items():
nk = norm_key(k)
if nk == "ein":
raw_ein = raw_ein if raw_ein is not None else v
continue
nv = norm_value(v)
if nv is not None and nk not in norm:
norm[nk] = nv
target = ein_index.get(norm_ein(raw_ein))
if target is None:
unmatched.append(raw_ein)
unmatched_cnt += len(norm)
continue
bucket = candidates.setdefault(target, {})
for f, v in norm.items():
bucket.setdefault(f, []).append(v)
errors, extra_fields = {}, {}
matched = correct = expected_total = 0
extracted_total = unmatched_cnt
for ref_ein, expected in ref.items():
cand = candidates.get(ref_ein)
if cand is not None:
matched += 1
got = {}
for f, vals in (cand or {}).items():
exp = expected.get(f)
got[f] = next((v for v in vals if exp is not None and equal(v, exp)), vals[0])
missing = sorted(f for f in expected if f not in got)
mismatched = {f: {"expected": expected[f], "got": got[f]}
for f in expected if f in got and not equal(got[f], expected[f])}
extras = sorted(f for f in got if f not in expected)
correct += len(expected) - len(missing) - len(mismatched)
expected_total += len(expected)
extracted_total += len(got)
errors[ref_ein] = {"missing_fields": missing, "mismatched_values": mismatched}
if extras:
extra_fields[ref_ein] = extras
return {
"match_rate": ratio(matched, len(ref)),
"errors": errors,
"precision": ratio(correct, extracted_total),
"recall": ratio(correct, expected_total),
"extra_fields": extra_fields,
"unmatched_eins": unmatched,
}
On the example, this returns match_rate 1.0 and reports tax as missing, as required, with recall 0.5 and precision 1.0 added.
Complexity
With N extracted records, R reference EINs and F fields per record: time O((N + R)·F), plus O(F log F) per EIN for sorting the error lists; space O((N + R)·F).
Common mistakes
- Comparing raw strings, so
"$50,000.00"never equals50000.0. - Using exact float equality instead of a tolerance.
- Matching on the raw EIN string, so formatting differences cause false "unmatched" results.
- Counting alias-renamed fields as one missing and one extra.
- Letting extra or unmatched-record fields inflate precision, or crashing on
Noneand empty denominators. - Not mentioning that using the reference to pick among duplicates is optimistic.
Follow-ups to be ready for
- Per-field tolerances or weights (wages matter more than a box code).
- Reporting duplicate conflicts explicitly rather than resolving them.
- Macro versus micro averaging of precision and recall across employers.