Scoring Extracted W-2 Tax Records Against Ground Truth

Medium · Software Engineering Fundamentals · Software Engineer · Technical Screen

Problem Statement

Automated document parsers that read scanned IRS Form W-2 wage statements often return messy dictionaries: field labels vary across form templates, dollar amounts arrive formatted with currency symbols or accounting parentheses, a single employer's statement can split across continuation pages, and noisy parses may hallucinate extra keys or omit the employer identifier altogether.

Implement evaluate_extraction(extracted_records, reference_data) to benchmark a batch of parser outputs against verified ground truth at field granularity.

from typing import Dict, List


def evaluate_extraction(extracted_records: List[dict], reference_data: dict) -> dict:
    ...

Canonicalization & Matching Rules

  1. Key canonicalization: Convert any key to lowercase, collapse every contiguous sequence of non-alphanumeric characters or underscores into one '_', strip leading/trailing '_', and resolve standard W-2 aliases:
    • 'employer_ein', 'employer_id' -> 'ein'
    • 'wages_tips_other_compensation' -> 'wages'
    • 'tax_withheld', 'federal_tax_withheld', 'federal_income_tax_withheld' -> 'tax'
  2. EIN formatting & record grouping:
    • Normalize an Employer Identification Number (EIN) by keeping only ASCII digits '0'–'9' (ignoring None and bool values). Return None when zero digits exist, format 9-digit strings as 'XX-XXXXXXX', and keep any other non-empty digit string unchanged. (If an outer key of reference_data yields no digits, fall back to str(key).strip().lower().)
    • Skip None or non-dict items inside extracted_records. Within each extracted dictionary, take the first key whose canonical name is 'ein' as the record identifier (and ignore redundant 'ein' keys inside reference_data inner dictionaries).
    • Extracted dictionaries whose normalized EIN is None cannot be linked to an employer: increment 'records_without_ein' for each such dictionary, while still counting its non-blank fields toward total predicted fields.
    • When multiple extracted dictionaries normalize to the same EIN, merge them in input order so the first non-blank normalized value for each canonical field wins.
  3. Value normalization & equality:
    • Treat None, float('nan'), "", and whitespace-only strings as absent (None), omitting them from normalized field maps.
    • Keep bool values as bool (never coercing True to 1.0). Convert finite int and float inputs to float.
    • For strings and other objects, collapse internal whitespace runs to single spaces (" ".join(str(v).split())). Remove '$', ',', and spaces; if wrapped in accounting parentheses (...) without an inner leading '-', strip the parentheses and negate the parsed number. Parse as float only when the candidate consists strictly of ASCII digits '0'–'9' with an optional leading '-' and at most one '.' (so strings such as 'Nan' stay text); otherwise normalize to the whitespace-collapsed lowercase string.
    • Two float values match when abs(expected - extracted) <= 0.005 (half a cent). Booleans only match booleans, and all other types compare with exact equality.
  4. Returned dictionary schema:
    • 'match_rate': matched reference EINs divided by len(reference_data).
    • 'precision': correct_fields / predicted_total, where predicted_total sums non-blank normalized fields across every merged extracted EIN (matched or unmatched) plus every no-EIN dictionary.
    • 'recall': correct_fields / expected_total, where expected_total sums non-blank normalized fields across reference_data.
    • Any ratio whose denominator is 0 evaluates to 1.0.
    • 'errors': mapping each raw reference_data key that has at least one missing or wrong field to {'missing_fields': sorted_missing_keys, 'mismatched_values': {field: {'expected': expected_val, 'extracted': extracted_val}}}.
    • 'unexpected_fields': mapping each raw reference_data key whose matched extraction includes extra canonical keys absent from ground truth to a sorted list of those extra keys.
    • 'unmatched_eins': sorted list of normalized extracted EINs not present in reference_data.
    • 'records_without_ein': integer count of extracted dictionaries lacking a usable EIN.

Examples

Example 1

Input:

extracted_records = [
    {
        "employer_ein": "74-8291036",
        "Wages": "$84,500.00",
        "Tax Withheld": "$11,200.00",
    }
]
reference_data = {
    "74-8291036": {"wages": 84500.0, "tax": 11500.0, "state_tax": 4200.0}
}

Output:

{
    "match_rate": 1.0,
    "precision": 0.5,
    "recall": 0.3333333333333333,
    "errors": {
        "74-8291036": {
            "missing_fields": ["state_tax"],
            "mismatched_values": {
                "tax": {"expected": 11500.0, "extracted": 11200.0}
            },
        }
    },
    "unexpected_fields": {},
    "unmatched_eins": [],
    "records_without_ein": 0,
}

Walk-through: "employer_ein" maps to "ein", matching the sole reference employer "74-8291036" (match_rate = 1.0). Out of 2 predicted fields (wages = 84500.0 and tax = 11200.0) and 3 reference fields, only wages matches (precision = 1 / 2 = 0.5, recall = 1 / 3), while tax is mismatched and state_tax is missing.

Example 2

Input:

extracted_records = [
    {"ein": "31-6049285", "Wages, tips, other compensation": "$62,000.00", "box_14": "union"},
    {"employer_id": "316049285", "federal_tax_withheld": "$7,400.00", "wages": "$999.00"},
    {"ein": "58-9102734", "wages": "$19,000.00"},
    {"wages": "$45,000.00"},
]
reference_data = {
    "31-6049285": {"wages": 62000.0, "tax": 7400.0},
    "86-2041597": {"wages": 45000.0},
}

Output:

{
    "match_rate": 0.5,
    "precision": 0.4,
    "recall": 0.6666666666666666,
    "errors": {
        "86-2041597": {"missing_fields": ["wages"], "mismatched_values": {}}
    },
    "unexpected_fields": {"31-6049285": ["box_14"]},
    "unmatched_eins": ["58-9102734"],
    "records_without_ein": 1,
}

Walk-through: The first two dictionaries both normalize to "31-6049285" and merge in order (wages = 62000.0 from page 1 wins over $999.00, tax = 7400.0 comes from page 2, and box_14 is flagged in unexpected_fields). Reference employer "86-2041597" goes unmatched (match_rate = 1 / 2 = 0.5). Two fields (wages and tax on "31-6049285") are right out of 5 total predicted non-blank fields (3 merged + 1 on unmatched "58-9102734" + 1 on the EIN-less dictionary) and 3 expected fields, yielding precision = 2 / 5 = 0.4 and recall = 2 / 3.

Constraints

  • 0 <= len(extracted_records) <= 50
  • extracted_records may include None entries, missing keys, empty strings, float('nan'), booleans, integers, floats, or formatted currency/accounting strings.
  • reference_data maps 0 to 50 employer keys to field dictionaries.
  • Target time and auxiliary space complexity: linear in the total number of extracted and ground-truth key-value pairs (up to sorting diagnostic key lists).

Step-by-step walkthrough

  1. Clarify the contract and report structure

    We receive extracted_records (a list of dictionaries produced by a W-2 form parser, possibly spanning multiple pages per employer) and reference_data ({ein: {field: value}} ground truth). We need to link records by Employer Identification Number (EIN), canonicalize field names and values, and return a structured evaluation summary:

    {
        "match_rate": 1.0,                 # matched reference EINs / total reference EINs
        "precision": 0.5,                  # correct fields / non-blank extracted fields
        "recall": 0.3333333333333333,      # correct fields / expected reference fields
        "errors": {
            "74-8291036": {
                "missing_fields": ["state_tax"],
                "mismatched_values": {
                    "tax": {"expected": 11500.0, "extracted": 11200.0}
                },
            }
        },
        "unexpected_fields": {},           # {ein: [extra fields not in reference]}
        "unmatched_eins": [],              # normalized extracted EINs absent from reference_data
        "records_without_ein": 0,          # extracted dicts with no usable EIN
    }
    

    Lock down three core invariants up front:

    • Order-preserving multi-page merge: When several extracted dictionaries normalize to the same EIN, combine them in input order so the first non-blank value for each canonical field wins. Never peek at reference_data to pick a closer duplicate—consulting ground truth during record assembly leaks labels into evaluation.
    • Blank inputs mean "absent": None, "", whitespace-only strings, and float("nan") normalize to None and are omitted rather than recorded as wrong values.
    • Empty-denominator convention: Whenever a ratio's denominator is 0 (for example, 0 predicted fields so nothing was predicted wrong), return 1.0.
  2. Define field-level precision and recall

    Evaluate accuracy at field granularity across the entire batch. After matching an extracted record to its reference EIN and normalizing keys and values, each field lands in one of four cells:

                            In Extracted Record?
                            Yes                      No
                       +------------------------+------------------------+
    In Reference       | Equal value -> CORRECT |                        |
    Schema?       Yes  |   (True Positive)      |       MISSING          |
                       | Diff value  -> MISMATCH|   (False Negative)     |
                       |   (FP + FN!)           |                        |
                       +------------------------+------------------------+
                  No   |     UNEXPECTED         |         (N/A)          |
                       |   (False Positive)     |                        |
                       +------------------------+------------------------+
    

    From those counts:

    • precision = correct_fields / predicted_total, where predicted_total sums every non-blank normalized field emitted by the parser—including fields on unmatched EINs and EIN-less dictionaries, because spurious outputs are false positives.
    • recall = correct_fields / expected_total, where expected_total sums every non-blank normalized field in reference_data.

    Quick check on three fields: suppose ground truth expects wages=84500, tax=11500 (expected_total = 2), while the parser emits wages="$83,900.00", tax="$11,500.00", box_14="union" (predicted_total = 3):

    tax:    11500.0 == 11500.0 -> correct (correct_fields = 1)
    wages:  83900.0 != 84500.0 -> mismatched (hurts both precision and recall)
    box_14: not in reference   -> unexpected (hurts precision)
    
    precision = 1 / 3 ~= 0.333
    recall    = 1 / 2  = 0.500
    
  3. Standardize field names and schema aliases

    Parsers emit raw form captions like "Wages", "Tax Withheld", "employer-ein", or the printed Box 1 title "Wages, tips, other compensation".

    Replacing only single spaces with underscores would leave commas intact ("wages,_tips,_other_compensation") and miss our alias map. Instead, lowercase the string, replace every contiguous run of non-alphanumeric characters or underscores (r"[\W_]+") with one "_", strip leading/trailing underscores, and consult FIELD_ALIASES:

    from typing import Any
    import re
    
    FIELD_ALIASES = {
        "employer_ein": "ein",
        "employer_id": "ein",
        "wages_tips_other_compensation": "wages",
        "tax_withheld": "tax",
        "federal_tax_withheld": "tax",
        "federal_income_tax_withheld": "tax",
    }
    
    
    def normalize_key(key: Any) -> str:
        # Collapse any run of punctuation, spaces, or underscores into a single '_'.
        snake = re.sub(r"[\W_]+", "_", str(key).lower()).strip("_")
        return FIELD_ALIASES.get(snake, snake)
    

    Running normalize_key on both extracted_records and reference_data maps "Wages" in ground truth and "Wages, tips, other compensation" in the extraction to the same "wages" key.

  4. Parse currency, accounting negatives, and text safely

    Value canonicalization must avoid four subtle bugs:

    1. Over-eager digit stripping: Stripping every non-digit turns "$3,450.75" into 345075 and erases the minus sign on "-240". Remove only "$", ",", and spaces.
    2. Accounting parentheses: Negative adjustments appear as "($3,450.75)" or "$(3,450.75)". Removing "$", ",", and spaces before testing for outer (...) turns both into "(3450.75)" -> -3450.75.
    3. Unchecked float(text): Python's float("Nan") and float("inf") succeed! A worker named Nan would turn into NaN, and since NaN != NaN under IEEE 754 rules, an exact match would fail. Check explicitly that the candidate has only ASCII digits '0'–'9', at most one ".", and an optional leading "-".
    4. Python bool and NaN edge cases: Test isinstance(value, bool) before (int, float) because bool subclasses int in Python, prevent True == 1.0 in values_equal, map float("nan") to None, and allow half-cent rounding slack (MONEY_TOLERANCE = 0.005).
    from typing import Any
    import math
    
    MONEY_TOLERANCE = 0.005
    
    
    def is_number_text(text: str) -> bool:
        if text.startswith("-"):
            text = text[1:]
        if text.count(".") > 1:
            return False
        digits_only = text.replace(".", "")
        if digits_only == "":
            return False
        for ch in digits_only:
            if ch not in "0123456789":
                return False
        return True
    
    
    def normalize_value(value: Any) -> Any:
        # Check `bool` before `(int, float)` because `bool` is a subclass of `int` in Python.
        if value is None or isinstance(value, bool):
            return value
        if isinstance(value, (int, float)):
            if math.isnan(value):
                return None
            return float(value)
    
        collapsed_text = " ".join(str(value).split())
        if collapsed_text == "":
            return None
    
        cleaned = collapsed_text.replace("$", "").replace(",", "").replace(" ", "")
        is_parenthesized_negative = (
            cleaned.startswith("(")
            and cleaned.endswith(")")
            and not cleaned[1:-1].startswith("-")
        )
        candidate = cleaned[1:-1] if is_parenthesized_negative else cleaned
    
        if is_number_text(candidate):
            number = float(candidate)
            return -number if is_parenthesized_negative else number
    
        return collapsed_text.lower()
    
    
    def values_equal(expected: Any, got: Any) -> bool:
        if isinstance(expected, bool) != isinstance(got, bool):
            return False
        if isinstance(expected, float) and isinstance(got, float):
            return abs(expected - got) <= MONEY_TOLERANCE
        return expected == got
    
  5. Normalize EINs and merge multi-page records

    Standard US employer IDs hold 9 digits written as XX-XXXXXXX, though raw outputs might read "316049285" or "EIN: 31 6049285". Keeping ASCII digits and inserting a hyphen after two digits for 9-digit strings gives both sides identical dictionary keys for O(1) average hash lookups.

    While normalizing reference_data, store original_ein[norm_ein] = raw_ein so errors and unexpected_fields preserve the caller's exact key spelling, and skip any redundant inner "ein" field:

    from typing import Any, Dict, List, Optional, Tuple
    
    
    def normalize_ein(value: Any) -> Optional[str]:
        if value is None or isinstance(value, bool):
            return None
        digits = ""
        for ch in str(value):
            if ch in "0123456789":
                digits += ch
        if digits == "":
            return None
        if len(digits) == 9:
            return digits[:2] + "-" + digits[2:]
        return digits
    
    
    def normalize_record(record: dict) -> Tuple[Optional[str], Dict[str, Any]]:
        ein: Optional[str] = None
        fields: Dict[str, Any] = {}
    
        for raw_key, raw_value in record.items():
            key = normalize_key(raw_key)
            if key == "ein":
                if ein is None:
                    ein = normalize_ein(raw_value)
                continue
            value = normalize_value(raw_value)
            if value is not None and key not in fields:
                fields[key] = value
    
        return ein, fields
    
    
    def normalize_reference(
        reference_data: dict,
    ) -> Tuple[Dict[str, Dict[str, Any]], Dict[str, Any]]:
        reference: Dict[str, Dict[str, Any]] = {}
        original_ein: Dict[str, Any] = {}
    
        for raw_ein, raw_fields in (reference_data or {}).items():
            norm_ein = normalize_ein(raw_ein)
            if norm_ein is None:
                norm_ein = str(raw_ein).strip().lower()
    
            fields: Dict[str, Any] = {}
            for raw_key, raw_value in (raw_fields or {}).items():
                key = normalize_key(raw_key)
                if key == "ein":
                    continue
                value = normalize_value(raw_value)
                if value is not None:
                    fields[key] = value
    
            reference[norm_ein] = fields
            original_ein[norm_ein] = raw_ein
    
        return reference, original_ein
    
    
    def merge_extracted(
        extracted_records: List[dict],
    ) -> Tuple[Dict[str, Dict[str, Any]], List[Dict[str, Any]]]:
        merged: Dict[str, Dict[str, Any]] = {}
        without_ein: List[Dict[str, Any]] = []
    
        for record in extracted_records or []:
            if not isinstance(record, dict):
                continue
            ein, fields = normalize_record(record)
            if ein is None:
                without_ein.append(fields)
                continue
            if ein not in merged:
                merged[ein] = {}
            for key, value in fields.items():
                if key not in merged[ein]:
                    merged[ein][key] = value
    
        return merged, without_ein
    
  6. Score across ground-truth and extracted fields

    Evaluation runs in two linear passes:

    1. Scan reference: Look up merged.get(ein). Inspect truth_fields to mark each expected field as missing, correct, or mismatched; then scan extracted_fields to collect extra keys absent from truth_fields.
    2. Scan merged and without_ein: Accumulate len(fields) across all merged EINs and EIN-less records into predicted_total, recording any extracted EIN missing from reference in unmatched_eins.
    def ratio(numerator: int, denominator: int) -> float:
        if denominator == 0:
            return 1.0
        return numerator / denominator
    
  7. Walk through Example 1 and Example 2

    Trace 1 (Example 1): - extracted_records = [{"employer_ein": "74-8291036", "Wages": "$84,500.00", "Tax Withheld": "$11,200.00"}] - reference_data = {"74-8291036": {"wages": 84500.0, "tax": 11500.0, "state_tax": 4200.0}}

    Normalized reference:  '74-8291036' -> {'wages': 84500.0, 'tax': 11500.0, 'state_tax': 4200.0}  (expected_total = 3)
    Normalized extracted:  '74-8291036' -> {'wages': 84500.0, 'tax': 11200.0}                       (predicted_total = 2)
    
    Compare '74-8291036':
      - 'wages':     84500.0 == 84500.0 -> correct_fields = 1
      - 'tax':       11200.0 != 11500.0 -> mismatched_values['tax'] = {'expected': 11500.0, 'extracted': 11200.0}
      - 'state_tax': absent in extracted -> missing_fields = ['state_tax']
    
    match_rate = 1 / 1 = 1.0
    precision  = 1 / 2 = 0.5
    recall     = 1 / 3 ~= 0.3333
    

    Trace 2 (Example 2 — multi-page merge, extra key, unmatched & no-EIN records): - reference_data = {"31-6049285": {"wages": 62000.0, "tax": 7400.0}, "86-2041597": {"wages": 45000.0}} - extracted_records has two pages for "31-6049285" (wages=62000.0, box_14="union" then tax=7400.0, wages=999.0), one record for "58-9102734" (wages=19000.0), and one EIN-less dict (wages=45000.0):

    merged['31-6049285'] = {'wages': 62000.0, 'box_14': 'union', 'tax': 7400.0}  (page 1 wages wins!)
    matched_eins    = 1 of 2 ('31-6049285' matched, '86-2041597' missed) -> match_rate = 0.5
    correct_fields  = 2 ('31-6049285'.wages and '31-6049285'.tax)
    expected_total  = 3 (2 on '31-6049285' + 1 on '86-2041597')          -> recall     = 2 / 3
    predicted_total = 5 (3 merged + 1 unmatched + 1 without EIN)         -> precision  = 2 / 5 = 0.4
    unexpected_fields = {'31-6049285': ['box_14']}, unmatched_eins = ['58-9102734'], records_without_ein = 1
    

    Even though {"wages": "$45,000.00"} equals "86-2041597"'s wage figure, without an EIN it cannot be safely attributed to that employer—records_without_ein = 1 pinpoints why recall fell.

  8. Complete solution

    from typing import Any, Dict, List, Optional, Tuple
    import math
    import re
    
    # Canonical field aliases after punctuation/case normalization.
    # Maps alternate W-2 box titles and extractor key names -> standard schema keys.
    FIELD_ALIASES = {
        "employer_ein": "ein",
        "employer_id": "ein",
        "wages_tips_other_compensation": "wages",
        "tax_withheld": "tax",
        "federal_tax_withheld": "tax",
        "federal_income_tax_withheld": "tax",
    }
    
    # Half-cent tolerance avoids false mismatches from binary floating-point rounding.
    MONEY_TOLERANCE = 0.005
    
    
    def normalize_key(key: Any) -> str:
        """Turn 'Wages, tips, other compensation' into 'wages' via snake_case + alias lookup."""
        # Collapse any run of punctuation, spaces, or underscores into a single '_'.
        snake = re.sub(r"[\W_]+", "_", str(key).lower()).strip("_")
        return FIELD_ALIASES.get(snake, snake)
    
    
    def is_number_text(text: str) -> bool:
        """Return True only for plain decimal strings like '84500', '-18.5', or '3450.75'."""
        if text.startswith("-"):
            text = text[1:]
        if text.count(".") > 1:
            return False
        digits_only = text.replace(".", "")
        if digits_only == "":
            return False
        for ch in digits_only:
            if ch not in "0123456789":
                return False
        return True
    
    
    def normalize_value(value: Any) -> Any:
        """Convert numbers/currency to float, clean text to lowercase, and blanks/NaN to None."""
        # Check `bool` before `(int, float)` because `bool` is a subclass of `int` in Python.
        if value is None or isinstance(value, bool):
            return value
        if isinstance(value, (int, float)):
            # Treat float('nan') from upstream DataFrames/JSON parsers as missing.
            if math.isnan(value):
                return None
            return float(value)
    
        # Collapse internal whitespace runs and treat empty strings as missing (`None`).
        collapsed_text = " ".join(str(value).split())
        if collapsed_text == "":
            return None
    
        # Strip currency symbols, thousands commas, and spaces before checking accounting
        # parentheses so both "($3,450.75)" and "$(3,450.75)" parse as -3450.75.
        cleaned = collapsed_text.replace("$", "").replace(",", "").replace(" ", "")
        is_parenthesized_negative = (
            cleaned.startswith("(")
            and cleaned.endswith(")")
            and not cleaned[1:-1].startswith("-")
        )
        candidate = cleaned[1:-1] if is_parenthesized_negative else cleaned
    
        # Validate digits explicitly instead of `float(...)` so names like "Nan" stay text.
        if is_number_text(candidate):
            number = float(candidate)
            return -number if is_parenthesized_negative else number
    
        return collapsed_text.lower()
    
    
    def normalize_ein(value: Any) -> Optional[str]:
        """Extract ASCII digits and format 9-digit EINs as 'XX-XXXXXXX'; return None if blank."""
        if value is None or isinstance(value, bool):
            return None
        digits = ""
        for ch in str(value):
            if ch in "0123456789":
                digits += ch
        if digits == "":
            return None
        if len(digits) == 9:
            return digits[:2] + "-" + digits[2:]
        return digits
    
    
    def values_equal(expected: Any, got: Any) -> bool:
        """Compare normalized values with half-cent float tolerance and strict bool typing."""
        # Guard against Python's `True == 1.0` and `False == 0.0` evaluating to True.
        if isinstance(expected, bool) != isinstance(got, bool):
            return False
        if isinstance(expected, float) and isinstance(got, float):
            return abs(expected - got) <= MONEY_TOLERANCE
        return expected == got
    
    
    def normalize_record(record: dict) -> Tuple[Optional[str], Dict[str, Any]]:
        """Normalize one extracted dict into `(normalized_ein, {field_key: normalized_value})`."""
        ein: Optional[str] = None
        # fields: {canonical_key: normalized_non_blank_value}; first non-blank value wins
        fields: Dict[str, Any] = {}
    
        for raw_key, raw_value in record.items():
            key = normalize_key(raw_key)
            if key == "ein":
                if ein is None:
                    ein = normalize_ein(raw_value)
                continue
            value = normalize_value(raw_value)
            if value is not None and key not in fields:
                fields[key] = value
    
        return ein, fields
    
    
    def ratio(numerator: int, denominator: int) -> float:
        """Compute `numerator / denominator`, returning 1.0 when `denominator == 0`."""
        if denominator == 0:
            return 1.0
        return numerator / denominator
    
    
    def normalize_reference(
        reference_data: dict,
    ) -> Tuple[Dict[str, Dict[str, Any]], Dict[str, Any]]:
        """Normalize reference ground truth and remember each EIN's original display key."""
        # reference: {normalized_ein: {canonical_field: normalized_value}}
        reference: Dict[str, Dict[str, Any]] = {}
        # original_ein: {normalized_ein: raw_ein_key_from_input}
        original_ein: Dict[str, Any] = {}
    
        for raw_ein, raw_fields in (reference_data or {}).items():
            norm_ein = normalize_ein(raw_ein)
            if norm_ein is None:
                norm_ein = str(raw_ein).strip().lower()
    
            fields: Dict[str, Any] = {}
            for raw_key, raw_value in (raw_fields or {}).items():
                key = normalize_key(raw_key)
                # Skip redundant EIN fields inside the inner dict since EIN is the record key.
                if key == "ein":
                    continue
                value = normalize_value(raw_value)
                if value is not None:
                    fields[key] = value
    
            reference[norm_ein] = fields
            original_ein[norm_ein] = raw_ein
    
        return reference, original_ein
    
    
    def merge_extracted(
        extracted_records: List[dict],
    ) -> Tuple[Dict[str, Dict[str, Any]], List[Dict[str, Any]]]:
        """Group extracted records by normalized EIN, keeping the first non-blank value per field."""
        # merged: {normalized_ein: {canonical_field: first_non_blank_value}}
        merged: Dict[str, Dict[str, Any]] = {}
        # without_ein: list of normalized field dicts from records lacking a usable EIN
        without_ein: List[Dict[str, Any]] = []
    
        for record in extracted_records or []:
            # Gracefully ignore None or malformed non-dict entries in the extracted list.
            if not isinstance(record, dict):
                continue
            ein, fields = normalize_record(record)
            if ein is None:
                without_ein.append(fields)
                continue
            if ein not in merged:
                merged[ein] = {}
            for key, value in fields.items():
                if key not in merged[ein]:
                    merged[ein][key] = value
    
        return merged, without_ein
    
    
    def evaluate_extraction(extracted_records: List[dict], reference_data: dict) -> dict:
        """Evaluate extracted W-2 records against reference ground truth at field granularity."""
        reference, original_ein = normalize_reference(reference_data)
        merged, without_ein = merge_extracted(extracted_records)
    
        correct_fields = 0    # True positives: field in both reference and extracted with equal value
        expected_total = 0    # Ground-truth denominator for recall
        predicted_total = 0   # Extracted non-blank denominator for precision
        matched_eins = 0      # Number of reference EINs present in `merged`
    
        # errors: {raw_ref_ein: {'missing_fields': [...], 'mismatched_values': {...}}}
        errors: Dict[Any, Dict[str, Any]] = {}
        # unexpected: {raw_ref_ein: [sorted extra field names not in ground truth]}
        unexpected: Dict[Any, List[str]] = {}
    
        # Phase 1: Compare every reference EIN against its merged extraction (if any).
        for ein, truth_fields in reference.items():
            expected_total += len(truth_fields)
            extracted_fields = merged.get(ein)
            if extracted_fields is None:
                extracted_fields = {}
            else:
                matched_eins += 1
    
            missing: List[str] = []
            mismatched: Dict[str, Dict[str, Any]] = {}
            for key, expected_val in truth_fields.items():
                if key not in extracted_fields:
                    missing.append(key)
                elif values_equal(expected_val, extracted_fields[key]):
                    correct_fields += 1
                else:
                    mismatched[key] = {
                        "expected": expected_val,
                        "extracted": extracted_fields[key],
                    }
    
            extra_fields: List[str] = []
            for key in extracted_fields:
                if key not in truth_fields:
                    extra_fields.append(key)
    
            if missing or mismatched:
                errors[original_ein[ein]] = {
                    "missing_fields": sorted(missing),
                    "mismatched_values": mismatched,
                }
            if extra_fields:
                unexpected[original_ein[ein]] = sorted(extra_fields)
    
        # Phase 2: Count all predicted non-blank fields, including unmatched and no-EIN records.
        unmatched_eins: List[str] = []
        for ein, fields in merged.items():
            predicted_total += len(fields)
            if ein not in reference:
                unmatched_eins.append(ein)
        for fields in without_ein:
            predicted_total += len(fields)
    
        return {
            "match_rate": ratio(matched_eins, len(reference)),
            "precision": ratio(correct_fields, predicted_total),
            "recall": ratio(correct_fields, expected_total),
            "errors": errors,
            "unexpected_fields": unexpected,
            "unmatched_eins": sorted(unmatched_eins),
            "records_without_ein": len(without_ein),
        }
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of grading hand-completed tax worksheets against an answer sheet when examinees copied numbers onto slightly different form layouts: one worksheet reads "Tax Withheld: $11,200.00" across two scanned pages, whereas the answer sheet stores {"tax": 11500.0}. Before marking anything right or wrong, you first transcribe both sides onto one uniform template—aligning field names, standardizing every Employer Identification Number (EIN) (the 9-digit US employer tax ID written XX-XXXXXXX), and turning currency strings into plain floats. That standardization pass is called canonicalization (converting equivalent surface formats into one canonical representation prior to comparison).

Why does a direct dictionary check (extracted == reference) fail? First, raw types and key spellings almost never match ("$84,500.00" != 84500.0, "316049285" != "31-6049285", "Tax Withheld" != "tax"), so direct equality marks valid parses wrong. Second, a single pass/fail flag hides what broke: improving an extraction system requires separating precision (the share of predicted non-blank fields that are actually right, penalizing hallucinated or wrong fields) from recall (the share of ground-truth expected fields recovered, penalizing missed boxes).

Trace a concrete single-employer check:

Reference:  {"74-8291036": {"Wages": 84500.0, "tax": 11500.0, "state_tax": 4200.0}}
Extracted:  [{"employer_ein": "748291036", "Wages, tips, other compensation": "$84,500.00",
              "Tax Withheld": "$11,200.00", "box_14": "union"}]

1. Canonicalize EIN & keys:
   Both sides key onto EIN "74-8291036".
   Extracted fields -> {"wages": 84500.0, "tax": 11200.0, "box_14": "union"}
   Reference fields -> {"wages": 84500.0, "tax": 11500.0, "state_tax": 4200.0}

2. Classify every field:
   - wages:     84500.0 == 84500.0 -> correct (1 true positive)
   - tax:       11200.0 != 11500.0 -> mismatched_values["tax"]
   - state_tax: not extracted      -> missing_fields = ["state_tax"]
   - box_14:    not in reference   -> unexpected_fields = ["box_14"]

3. Compute metrics:
   match_rate = 1 / 1 = 1.0,  precision = 1 / 3 ~= 0.333,  recall = 1 / 3 ~= 0.333

Complexity

Let F be the total number of key-value entries across extracted_records, G be the total number of ground-truth entries in reference_data, and L be the average character length of keys and string values.

  • Time: O((F + G) * L) average (or O(F + G) treating bounded field strings as constant length). Every extracted entry is normalized once and inserted into the merged hash table in O(1) average time per entry, avoiding quadratic all-pairs record comparisons. Scoring visits each ground-truth entry and each merged/no-EIN entry once, plus O(k log k) to sort diagnostic lists of size k.
  • Space: O(F + G). The normalized reference map, merged map, without_ein list, and returned diagnostic dictionaries store at most one entry per input field.

Edge cases

  • Blank and NaN entries (None, "", " ", float("nan")): Normalized to None ("not extracted"), so they land in missing_fields rather than mismatched_values and never inflate predicted_total.
  • Non-dictionary elements (None inside extracted_records): Ignored safely via isinstance(record, dict).
  • Continuation pages sharing an EIN: Merged in input order so the first non-blank value per field wins, without consulting reference_data.
  • Varied EIN punctuation ("31-6049285", "316049285", "EIN 31 6049285"): All map to "31-6049285", while errors and unexpected_fields preserve the caller's exact key string from reference_data. Upstream parsers should emit EINs as strings rather than integers so leading zeros ("01-2345678") survive intact.
  • Accounting parentheses ("(240.00)", "($3,450.75)", "$(3,450.75)") and float slack: Parsed as negative floats and compared within a floating-point tolerance (a small allowed absolute difference, here 0.005 or half a cent, preventing binary float rounding noise from causing false mismatches).
  • Names matching float literals ("Nan", "Infinity"): Explicit ASCII digit checks keep "Nan" as "nan" rather than NaN.
  • Boolean vs numeric values (True vs 1.0): Because bool subclasses int in Python (True == 1.0 evaluates to True), checking isinstance(..., bool) explicitly prevents "$1.00" from matching True.
  • Unmatched EINs and EIN-less dictionaries: Reported in unmatched_eins and records_without_ein, while their non-blank fields still count in predicted_total as false positives (unverified predicted fields).

Common mistakes

  • Removing all non-digits with re.sub(r"\D", "", s): Strips decimal points ("$3,450.75" -> 345075) and minus signs ("-240" -> 240).
  • Checking numeric strings via try: float(s): Converts valid person names like "Nan" or "Inf" into IEEE special floats where NaN != NaN breaks comparisons.
  • Replacing only single spaces in key names: Leaves commas and double spaces untouched ("wages,_tips,_other_compensation"), missing the alias lookup table.
  • Excluding extra or unmatched fields from predicted_total: Lets a noisy extractor that dumps every word on the page claim 100% precision.
  • Selecting the "closest" duplicate record using reference_data: Leaks ground-truth answers into merging logic and inflates offline benchmark numbers.

Alternative approaches

  • Schema-typed field parsers: Attaching explicit field types (ein, currency, state_code, text) in a schema keeps leading-zero postal codes ("02139") as strings while parsing Box 1–20 currency amounts into exact Decimal cents.
  • Micro-averaging vs macro-averaging: Pooling field counts across all W-2s (micro-averaging) weights dense forms proportionally, whereas averaging per-form precision and recall (macro-averaging) treats every employer equally.
  • Per-box error slices: Computing precision, recall, and mismatch rates per canonical field (wages, tax, state_tax) highlights which specific W-2 box drives model errors.

Follow-up questions

  • What strategies would mitigate optical character recognition confusions—such as swapping the letter 'O' with the digit '0'—inside numeric or identifier boxes? Apply character-level lookalike substitutions (O -> 0, I/l -> 1, S -> 5, B -> 8) strictly to fields typed as identifiers or currency (ein, ssn, dollar boxes), never to free-text names or cities. If a normalized EIN still misses exact hash lookup in reference_data, check whether a unique reference EIN sits within edit distance 1 (the minimum count of single-character insertions, deletions, or replacements needed to transform one string into another) and record ocr_repaired_eins separately in the report so raw OCR regressions stay visible.
  • When a single filing spans several scanned pages, what metadata should each extracted dictionary carry so continuation fields attach to the right employer without colliding across employees? Have the extractor attach page numbers, layout bounding boxes, and employee identifiers to every emitted dictionary, such as {"page": 2, "form_instance_id": "p1_upper", "ein": ..., "employee_ssn": ..., "fields": {...}}. Group primarily by (normalized_ein, normalized_ssn) so two spouses working for the same company in a joint return never overwrite each other's wages, use layout continuity (form_instance_id or matching employer header blocks on consecutive pages) when a continuation sheet omits the EIN, and log conflicting non-blank values for the same box as merge conflicts rather than silently dropping the second figure.
  • How could you adapt value comparison to tolerate minor formatting or spelling differences in street addresses without weakening numeric checks? Route comparisons by field category: keep half-cent tolerance on currency fields and exact matching on identifiers, state codes, and 5-digit ZIP codes, while canonicalizing address lines first (lowercasing, stripping punctuation, and expanding USPS street suffixes such as st -> street and ave -> avenue). Then compare street and city text using a normalized character or token similarity score (such as 1 - edit_distance / max_len or difflib.SequenceMatcher ratio) against a threshold like 0.90 calibrated on labeled validation pairs, reporting both the pass/fail decision and raw similarity score.

Follow-up questions

Similar questions

More Additive Ai interview questions

All 2 Additive Ai questions →