Human Review and Confidence Calibration: Check Accuracy by Type and Field Before You Stop Looking
An invoice extractor is 93% accurate, so the team wants to stop human review. Split by type and field, handwritten invoices are at 70% and handwritten due dates at 1 of 4. Two small Python files find the weak spot, pick a confidence cut-off from labelled data and keep a stratified sample under review.
What you will learn
- Split one overall accuracy number by document type and by field to find the weak spot
- Calibrate field confidence on a labelled set and let the data pick the cut-off
- Route low-confidence or conflicting fields to a person and accept the rest
- Draw a stratified random sample from every document type, including the confident ones
Before you start
- Validation-retry loops for Claude extraction
- Basic Python and CSV files
Your invoice extractor reads three fields from every invoice, and 93% of them are right. Fifty-six out of sixty. Someone on the team says: good enough, let's stop human review.
But 93% of what? Look inside and handwritten invoices are right only 7 times out of 10. Handwritten due dates are right 1 time out of 4. A single average can hide a document type, or a field, that is failing. This article shows four habits that find it before you automate: check by type, check by field, calibrate the confidence, and keep sampling.
One school, three classes
A school reports an average grade of 93%. A great school, it seems. Now look class by class. Class A is at 100%, class B at 93%, class C at 70%. One class is failing, and the average never shows it. Before you say the school is fine, you look at each class.
An extractor is the same. The "classes" are document types (printed, scanned, handwritten) and fields (invoice number, total, due date).
The data
The project has a file results.csv with 60 extractions that a person has checked. Each row says which document type it came from, which field, how confident the extractor was, and whether the value was right. A few rows:
doc_type,field,confidence,correct
printed,invoice_number,0.99,yes
scanned,due_date,0.62,no
handwritten,due_date,0.92,no
handwritten,due_date,0.83,yes
All the numbers are made-up example numbers, and both files are plain Python: no model call and no API key. The checks are what matter here, and they work the same on real labelled data.
accuracy.py: split the average
"""Overall accuracy can hide a weak spot. Example numbers."""
import csv
from collections import defaultdict
def load(path="results.csv"):
with open(path, newline="") as f:
return list(csv.DictReader(f))
def score(rows):
hits = sum(r["correct"] == "yes" for r in rows)
return hits, len(rows)
def group(rows, *keys):
groups = defaultdict(list)
for r in rows:
groups[tuple(r[k] for k in keys)].append(r)
return groups
if __name__ == "__main__":
rows = load()
hits, n = score(rows)
print(f"overall: {hits}/{n} = {hits / n:.0%} correct")
print("by document type:")
for (doc,), g in sorted(group(rows, "doc_type").items()):
h, m = score(g)
print(f" {doc:12} {h:>2}/{m:<2} = {h / m:.0%}")
print("by document type and field:")
for (doc, field), g in sorted(group(rows, "doc_type", "field").items()):
h, m = score(g)
flag = " <-- weak" if h / m < 0.8 else ""
print(f" {doc:12} {field:15} {h}/{m} = {h / m:.0%}{flag}")
score counts the right answers. group sorts rows by any keys you give it, so the same function cuts by document type, then by document type and field. Any segment under 80% gets a weak flag.
Running python accuracy.py:
overall: 56/60 = 93% correct
by document type:
handwritten 7/10 = 70%
printed 36/36 = 100%
scanned 13/14 = 93%
by document type and field:
handwritten due_date 1/4 = 25% <-- weak
handwritten invoice_number 3/3 = 100%
handwritten total 3/3 = 100%
printed due_date 12/12 = 100%
printed invoice_number 12/12 = 100%
printed total 12/12 = 100%
scanned due_date 3/4 = 75% <-- weak
scanned invoice_number 5/5 = 100%
scanned total 5/5 = 100%
The overall line says it is safe to stop review. The type lines say handwritten is at 70%. The field lines point at the exact cell: handwritten due dates, 1 of 4. Scanned due dates are weak too, 3 of 4. These groups are small, four rows each, but they are exactly where a person still needs to look.
This is the same idea as testing a RAG bot slice by slice before release (see a release gate per slice): a pass rate only means something for the slice it was measured on.
Is the confidence honest?
The extractor gives every field a confidence score. It's tempting to say "accept anything above 0.9" and move on. But a score is just another output of the model. Until you check it against labelled data, you don't know what 0.9 means. As with any confident output, you check it against something you can look up; here, that something is the labelled set.
Calibration asks: when the model says 0.9 and up, how often is it right? When it says 0.8 to 0.89? Below 0.8? And then the cut-off comes from those answers, not from a guess.
route.py: let the data pick the cut-off
"""Send doubt to people first, and spot-check the rest. Example data."""
import random
from accuracy import load, score
GOAL = 0.97 # share of auto-accepted fields that must be right
def pick_cutoff(rows):
"""Lowest confidence cut-off that meets the goal on the labelled set."""
for cut in (0.5, 0.6, 0.7, 0.8, 0.9):
kept = [r for r in rows if float(r["confidence"]) >= cut]
hits, n = score(kept)
if n and hits / n >= GOAL:
return cut, hits, n
return 1.0, 0, 0
def calibration(rows):
"""How often is the model right when it says 0.9, 0.8, and so on?"""
for name, lo, hi in (("0.90 and up", 0.9, 1.01),
("0.80 to 0.89", 0.8, 0.9),
("below 0.80", 0.0, 0.8)):
part = [r for r in rows if lo <= float(r["confidence"]) < hi]
hits, n = score(part)
print(f" says {name:12} right {hits}/{n} = {hits / n:.0%}")
pick_cutoff starts low and moves up. At each cut-off it keeps only the rows at or above it and asks: are at least 97% of these right? The first cut-off that meets the goal wins. The 97% goal is the project's own number; yours comes from what a wrong field costs you.
Then ten new invoice fields arrive. Each has an id, a document type, a field, a confidence and a conflict_detected flag:
NEW = [ # id, doc_type, field, confidence, conflict_detected
("inv-01", "printed", "total", 0.98, False),
("inv-02", "printed", "due_date", 0.95, False),
("inv-03", "handwritten", "due_date", 0.91, False),
("inv-04", "scanned", "total", 0.93, False),
("inv-05", "handwritten", "total", 0.84, False),
("inv-06", "printed", "invoice_number", 0.97, False),
("inv-07", "scanned", "due_date", 0.64, False),
("inv-08", "printed", "total", 0.96, True),
("inv-09", "scanned", "invoice_number", 0.92, False),
("inv-10", "handwritten", "due_date", 0.66, False),
]
def route(new, cut):
human = [x for x in new if x[3] < cut or x[4]]
auto = [x for x in new if x not in human]
return human, auto
def sample(auto, rng):
"""Stratified: one random auto-accepted row from every doc type."""
picked = []
for doc in sorted({x[1] for x in auto}):
picked.append(rng.choice([x for x in auto if x[1] == doc]))
return picked
route has one rule with two parts: low confidence or a detected conflict goes to a person. A conflict means the extraction itself found the document disagreeing with itself, as in validation-retry loops. High confidence doesn't cancel that. sample draws one random accepted row from every document type.
Running python route.py:
calibration on the labelled set:
says 0.90 and up right 44/45 = 98%
says 0.80 to 0.89 right 10/10 = 100%
says below 0.80 right 2/5 = 40%
cut-off 0.8: 54/55 = 98% right (goal 97%)
to a person (3):
inv-07 scanned due_date 0.64 low confidence
inv-08 printed total 0.96 conflict
inv-10 handwritten due_date 0.66 low confidence
auto-accepted (7), spot-checked (3):
inv-03 handwritten due_date 0.91 sampled
inv-01 printed total 0.98 sampled
inv-04 scanned total 0.93 sampled
- Calibration: below 0.80, the model is right only 2 times in 5. At 0.80 and above it holds up.
- Cut-off: the data picks 0.8. Fields at or above it are right 54 times out of 55, which is 98% and meets the 97% goal.
- To a person: two fields with low confidence, and inv-08, a printed total at 0.96 with a detected conflict.
- Accepted: the other seven, with one from each type spot-checked. One of them is a handwritten due date at 0.91.
Why sample the confident ones?
Because high confidence is not proof. Look back at the labelled set: one handwritten due date was wrong at 0.92. That row sits in the "0.90 and up" band, the band everyone wants to trust.
So the accepted fields are grouped by document type, and one is drawn at random from each group for a person to check. That does two jobs:
- It measures the real error rate of what you accepted, segment by segment, as the documents change over time.
- A wrong value is a clue to a new error pattern. When the sample finds one, you fix the rule for that segment.
Stratified means every type gets drawn, including printed invoices that have been at 100%. A purely random sample from all accepted fields would mostly pick printed invoices, because they are most of the volume, and the small handwritten group could go unchecked for weeks.
Common mistakes
- Automating on the average. 93% overall hid a field at 25%. Always split by document type and by field first.
- Trusting the raw score. A confidence of 0.9 means nothing until the labelled set says how often 0.9 is right.
- Guessing the cut-off. Pick it from the labelled set against a goal you chose on purpose.
- Letting confidence override a conflict. inv-08 was at 0.96 and still went to a person, because the document disagreed with itself.
- Sampling only the weak spots. Errors can appear in any segment, so sample every type, the good-looking ones too.
Recap
| Habit | In this project | What it caught |
|---|---|---|
| Accuracy by type | group(rows, "doc_type") | Handwritten at 7/10 = 70% |
| Accuracy by field | group(rows, "doc_type", "field") | Handwritten due date at 1/4 |
| Calibrate | calibration(), pick_cutoff() | Below 0.80 only 2/5 right; cut-off 0.8 gives 54/55 |
| Route doubt | route() | 2 low-confidence fields and 1 conflict to a person |
| Stratified sample | sample() | One accepted field per type, including a 0.91 handwritten due date |
On the exam, before automating high-confidence extractions, pick the answer that validates accuracy by document type and field and keeps a stratified sample under review; an overall average is not enough.
Try it yourself
Lower GOAL in route.py to 0.95 and run it again. Which cut-off does the data pick now, and do the same three fields still go to a person? Then raise it to 0.99. No cut-off meets that goal, pick_cutoff returns 1.0, 0, 0, and the print line has nothing to divide by. Add a guard that says "no cut-off meets the goal: review everything", because that is the honest answer when the labelled set can't support automation.
Related course on Udemy
Claude Certified Architect - Foundations (CCAR-F) Exam Prep
Agentic loops, tools, MCP, Claude Code, prompts, structured output and context.View on Udemy ↗: Claude Certified Architect - Foundations (CCAR-F) Exam Prep (paid course, opens in a new tab)Related posts
The Claude Messages API: Your First Call, Field by Field
One request in, one Message out. The four fields of a Messages API call (model, max_tokens, system, messages), how to read content blocks, stop_reason and usage, and why every turn resends the history.
Claude Tool Use: How tool_use and tool_result Work in the Messages API
Follow one order question through Claude's tool round trip: define a tool, read the tool_use block, run your own function and send a matching tool_result back, including parallel calls and is_error.
Claude Client SDKs Wrap One REST API: Raw HTTP, Python, TypeScript and Async Calls Compared
Every Claude client SDK wraps the same REST request: a POST to /v1/messages with a JSON body. See it built by hand, through the Python and TypeScript SDKs, as typed errors, and as async calls that wait together.
Anthropic SDK Timeouts, Retries and Error Classes: Configure the Client Once, Then Give 429, 529, 400 and Timeouts Their Own Move
Configure the Anthropic SDK client (timeout, max_retries, with_options, async, pagination), see which errors it retries by itself, then repair a retry wrapper so a 429, a 529, a 400 and a timeout each get the move the docs support.
