# How to Test Document Classification Accuracy (2026)

> Test document classification accuracy on a loan packet: 480 generated pages, 3 baselines, confidence thresholds, a learning curve and a script to run.

**In short:** A Python harness generated 480 pages (8 classes including out of scope junk, 3 layouts each, 4 quality tiers, lookalike headers and continuation pages), read them with Tesseract 5.5.2 and scored three baselines written for the test, not any vendor or DocsAPI: keyword rules, TF-IDF logistic regression and naive Bayes, with five fold cross validation. Logistic regression was right on 95.0% of pages (100.0% clean, 87.5% noisy), naive Bayes 93.5% and the rules 88.3%. At a confidence of 0.50 the logistic regression accepted 441 pages with none wrong and sent 8.1% to review, while the rule confidence was not usable below 0.90. 21 of its 24 errors were pages where OCR found fewer than 10 words. About 10 labeled pages per class reached 92.4%, an unseen layout cost 5 to 10 points, and a 10 page packet at 95% per page is fully right about 60% of the time if pages are independent. Script, results CSVs and a method for scoring your own pages or a vendor are included.

**Canonical URL:** https://docsapi.co/resources/blogs/document-classification-accuracy-test
**Author:** Nupura Ughade, Content Marketing Lead, DocsAPI
**Author LinkedIn:** https://www.linkedin.com/in/nupura-ughade/
**Published:** 2026-12-02T00:00:00.000Z
**Updated:** December 2, 2026
**Primary topic:** document classification accuracy
**Site:** https://docsapi.co (DocsAPI, the document intelligence API for SMB lending and fintech)

---

To test document classification accuracy on a lending packet, label 200 to 500 pages, hold each page out of training once, and report four numbers: accuracy by scan quality, the confusion matrix, the error rate among pages the system accepts without a human, and how that error rate moves as you add labeled examples. Overall accuracy is the least useful of the four. On 480 generated pages in eight classes, a TF-IDF logistic regression baseline we wrote was right on 95.0% of them (456 of 480, 95% interval 92.7% to 96.6%), 100.0% on clean scans and 87.5% on noisy ones.

The number that mattered was different. With auto accept set at a confidence of 0.50, 441 pages (91.9%) were accepted and none of them was wrong, while 8.1% went to review. Twenty one of the baseline's 24 errors were pages where Tesseract found fewer than 10 words, so a lookalike layout was almost never the cause. Everything here was measured on generated pages, with classifiers we wrote for the test. These are not vendor results and not DocsAPI results, and we did not run DocsAPI through this harness.

This guide is about how to measure, with a script you can run on your own pages. For what classification software does and how to choose it, read our [document classification software guide](/resources/blogs/document-classification-software). For cutting a combined PDF into documents before you classify, see [how to split a loan packet PDF](/resources/blogs/split-loan-packet-pdf). The same method applied to extraction is in our [invoice OCR test for accounts payable](/resources/blogs/invoice-ocr-test-accounts-payable).

## How many pages do you need to test document classification?

Use 200 to 500 pages, with at least 30 in every class and about one page in eight from outside your scope. At 20 pages a result of 95% right could really be anywhere from 76% to 99%. The table gives the 95% Wilson interval for a measured accuracy at several sizes.

| Pages tested | 95% interval if 95% are right | 95% interval if 85% are right |
| --- | --- | --- |
| 20 | 76.4 to 99.1 | 64.0 to 94.8 |
| 60 | 86.3 to 98.3 | 73.9 to 91.9 |
| 120 | 89.5 to 97.7 | 77.5 to 90.3 |
| 240 | 91.5 to 97.1 | 79.9 to 89.0 |
| 480 | 92.7 to 96.6 | 81.5 to 87.9 |

Per class the numbers are smaller. Our 60 pages per class gave a recall of 55 of 60 for one class, which is 91.7% with an interval of 81.9% to 96.4%. Even 60 pages cannot separate a class at 92% from one at 97%, so read per class figures as a place to look and not as a ranking. If you need a decision on one class, such as IDs, test that class with more pages.

Make the set look like your inbox. If a quarter of what you receive is a phone photo, a quarter of the test should be phone photos, reported on their own line. Include the pages you are afraid of: page two of a bank statement with no logo, a receipt that says invoice, a fax cover sheet. An overall figure from a friendly sample is the easiest way to buy the wrong system.

## What was in the test set?

The generator draws eight classes, 60 pages each: seven document types a lender sees and one class of pages that belong in none of them. Each class has three layouts. Thirty percent of pages use a lookalike header meant to confuse the class with a neighbour, and 72 pages are continuation pages with the top of the page blanked, the way page two of a statement arrives. That leaves 255 standard pages, 153 lookalikes and 72 continuations.

| Class | What the generator draws | Lookalike variant (30% of pages) | Pages |
| --- | --- | --- | --- |
| Invoice | 3 layouts: bordered, serif, sans; bill to, PO, terms, line items | No title word, just a vendor name and an Inv # line, ends with a thank you line | 60 |
| Receipt | 3 narrow store receipts; items, subtotal, tax, paid by, thank you | Headed TAX INVOICE / RECEIPT and carries an invoice number | 60 |
| Bank statement | 3 layouts; opening and closing balance, debit and credit columns, payroll deposits | Titled Account Summary | 60 |
| Pay stub | 3 layouts; earnings, deductions, gross, net, YTD, direct deposit | Titled just Statement, with Period, Date and Account ending lines | 60 |
| Tax form | W-2 box grid, 1099-NEC boxes, 1040 summary lines | Form title cropped; only Copy B or Page 2 remains | 60 |
| ID card | Driver license, state ID card, passport data page, placed mid page | Back of a license (barcode and restrictions), passport without the machine readable lines | 60 |
| Utility bill | 3 layouts; meter reads, usage, delivery charge, total amount due | Titled Customer Invoice with an invoice number | 60 |
| Other (out of scope) | Cover letter, meeting agenda, sale flyer, fax cover sheet or contract terms page | Mentions an invoice, a statement or a payment in passing | 60 |

Every class is rendered at four quality tiers, 15 pages per class per tier, so each tier holds 120 pages. Clean is a 200 dpi render. Skewed rotates the page 1.5 to 3.5 degrees with light noise. Noisy adds blur, Gaussian noise and salt and pepper specks. Low resolution drops to 75 dpi and saves as a heavily compressed JPEG. The pages come from a seeded generator, so anyone with the same seed, fonts and Python version builds the same files. Names, numbers and addresses are random. Nothing is a real person's data.

## Which classifiers did we compare, and how did we keep the test fair?

We wrote three baselines. None is a vendor product.

- Keyword rules: 85 hand written phrase patterns with weights, for example opening balance for a bank statement and paid by for a receipt. The score is the weight of matched phrases, the confidence is top score over top plus second plus one, and a page scoring under 2 points is called other. The rules were written before the first run and not edited afterwards.
- TF-IDF logistic regression: word and word pair features with a minimum document frequency of 2, sublinear term counts, L2 regularization and 300 steps of Adam, in plain numpy. The confidence is the highest class probability.
- Multinomial naive Bayes on the same word and word pair counts, with 0.5 smoothing. Its confidence is the posterior of the top class.

Pages were read by Tesseract 5.5.2 in its default page segmentation mode. The two trained models were scored with five fold cross validation, stratified by class and tier, so every page was predicted by a model that never saw it, and the numbers below are pooled over all 480 pages. A separate 160 page set from a different seed was used only to debug the harness before the test set was generated. Environment: Python 3.9.6, numpy 2.0.2, Pillow 11.3.0. Scikit-learn was not used, which is why the classifiers are short enough to print at the end.

## How accurate were the baselines overall, and class by class?

| Baseline | Pages right | Accuracy | 95% interval |
| --- | --- | --- | --- |
| TF-IDF logistic regression | 456 of 480 | 95.0% | 92.7 to 96.6 |
| Naive Bayes | 449 of 480 | 93.5% | 91.0 to 95.4 |
| Keyword rules | 424 of 480 | 88.3% | 85.2 to 90.9 |

The ordering is no surprise, and the gaps are wider than the intervals. A model learned from examples beat hand rules by about 7 points, mostly because pages that OCR damaged still leave a few words a model can use. The per class table shows where each one lost points.

| Class | Pages | LR precision | LR recall | NB precision | NB recall | Rules precision | Rules recall |
| --- | --- | --- | --- | --- | --- | --- | --- |
| Invoice | 60 | 100.0 | 91.7 | 69.0 | 96.7 | 100.0 | 85.0 |
| Receipt | 60 | 72.3 | 100.0 | 100.0 | 80.0 | 84.0 | 70.0 |
| Bank statement | 60 | 100.0 | 100.0 | 100.0 | 100.0 | 100.0 | 100.0 |
| Pay stub | 60 | 98.2 | 91.7 | 100.0 | 91.7 | 98.2 | 91.7 |
| Tax form | 60 | 100.0 | 93.3 | 95.1 | 96.7 | 98.2 | 90.0 |
| ID card | 60 | 100.0 | 88.3 | 98.1 | 88.3 | 100.0 | 90.0 |
| Utility bill | 60 | 100.0 | 95.0 | 100.0 | 95.0 | 100.0 | 95.0 |
| Other (out of scope) | 60 | 100.0 | 100.0 | 98.4 | 100.0 | 52.6 | 85.0 |

The logistic regression's weakest number is receipt precision, 72.3%. It is not a receipt problem. Its confusion matrix shows where the other 24 errors went.

| True class (rows), predicted (columns) | Invoice | Receipt | Bank st. | Pay stub | Tax form | ID card | Utility | Other |
| --- | --- | --- | --- | --- | --- | --- | --- | --- |
| Invoice | 55 | 4 | 0 | 1 | 0 | 0 | 0 | 0 |
| Receipt | 0 | 60 | 0 | 0 | 0 | 0 | 0 | 0 |
| Bank statement | 0 | 0 | 60 | 0 | 0 | 0 | 0 | 0 |
| Pay stub | 0 | 5 | 0 | 55 | 0 | 0 | 0 | 0 |
| Tax form | 0 | 4 | 0 | 0 | 56 | 0 | 0 | 0 |
| ID card | 0 | 7 | 0 | 0 | 0 | 53 | 0 | 0 |
| Utility bill | 0 | 3 | 0 | 0 | 0 | 0 | 57 | 0 |
| Other (out of scope) | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 60 |

Every one of its 24 errors but one was labeled a receipt. Most of those pages came back from OCR with almost no text, and a model with nothing to read falls back on whichever class its intercept favours. Here that class was receipts. So a weak precision figure for one class can come from other classes' failures. The keyword rules failed another way: when OCR returned nothing they answered other, which is why their other precision is 52.6%.

For comparison, here is the keyword rules matrix.

| True class (rows), predicted (columns) | Invoice | Receipt | Bank st. | Pay stub | Tax form | ID card | Utility | Other |
| --- | --- | --- | --- | --- | --- | --- | --- | --- |
| Invoice | 51 | 0 | 0 | 0 | 0 | 0 | 0 | 9 |
| Receipt | 0 | 42 | 0 | 0 | 0 | 0 | 0 | 18 |
| Bank statement | 0 | 0 | 60 | 0 | 0 | 0 | 0 | 0 |
| Pay stub | 0 | 0 | 0 | 55 | 0 | 0 | 0 | 5 |
| Tax form | 0 | 0 | 0 | 1 | 54 | 0 | 0 | 5 |
| ID card | 0 | 0 | 0 | 0 | 0 | 54 | 0 | 6 |
| Utility bill | 0 | 0 | 0 | 0 | 0 | 0 | 57 | 3 |
| Other (out of scope) | 0 | 8 | 0 | 0 | 1 | 0 | 0 | 51 |

## Do lookalike layouts or OCR errors cause the mistakes?

In this test, OCR errors. We ran the same classifiers, with the same folds, on the text the generator printed instead of the text Tesseract read. That isolates template difficulty from OCR damage.

| Baseline | On the true text (no OCR) | On OCR text | Cost of OCR | Standard pages, true text to OCR | Lookalike and continuation pages, true text to OCR |
| --- | --- | --- | --- | --- | --- |
| TF-IDF logistic regression | 100.0% | 95.0% | 5.0 points | 100.0% to 96.9% | 100.0% to 92.9% |
| Naive Bayes | 100.0% | 93.5% | 6.5 points | 100.0% to 93.7% | 100.0% to 93.3% |
| Keyword rules | 98.3% | 88.3% | 10.0 points | 100.0% to 91.0% | 96.4% to 85.3% |

On true text, both trained models scored 100.0% on all 480 pages, including the lookalikes. The rules lost 1.7 points to the confusable layouts. Reading the pages with Tesseract cost the models 5.0 and 6.5 points and the rules 10.0. The pairs we built to confuse the classifiers did little: pay stubs and bank statements were never mixed up by any of the three, and the only invoice and receipt confusions were 4 invoices read as receipts by the logistic regression and 11 receipts read as invoices by naive Bayes.

That is a limit of this data, and we say so plainly. Our lookalike pages still carry some class vocabulary, such as earnings on the pay stub and opening balance on the statement. Real lookalikes are probably harder than ours, but that is a guess. The nearest thing to evidence we have is the section on unseen layouts below, which shows what happens when the model meets a layout it has not trained on. For a first test, the finding is practical: before you buy a better classifier, find out how many of your pages OCR cannot read.

## How much does scan quality change classification accuracy?

A lot, and it tracks how many words the OCR recovered. The word recovery column is the share of distinct words printed on the page that Tesseract found.

| Quality tier | Pages | Words OCR recovered | Tesseract mean confidence | LR | NB | Rules |
| --- | --- | --- | --- | --- | --- | --- |
| Clean, 200 dpi | 120 | 99.8% | 95.4 | 100.0% | 100.0% | 99.2% |
| Skewed 1.5 to 3.5 degrees | 120 | 96.1% | 93.5 | 99.2% | 99.2% | 97.5% |
| Low resolution, 75 dpi, JPEG | 120 | 51.7% | 54.4 | 93.3% | 93.3% | 80.0% |
| Scanner noise and blur | 120 | 75.5% | 65.7 | 87.5% | 81.7% | 76.7% |

Clean and skewed pages are nearly solved by every baseline. Noise and low resolution are where the models separate. Tesseract's own mean word confidence was 95.4 on clean pages and 54.4 on low resolution ones, so the OCR engine already knew those pages were bad. Time per page was 0.69 seconds on average inside six parallel workers on a 10 core Mac, and 1.59 seconds on noisy pages, since Tesseract spends longer on garbage.

The same set by page type shows what a missing header costs.

| Page type | Pages | LR | NB | Rules |
| --- | --- | --- | --- | --- |
| Standard page | 255 | 96.9% | 93.7% | 91.0% |
| Lookalike header | 153 | 94.8% | 95.4% | 86.9% |
| Continuation page, header missing | 72 | 88.9% | 88.9% | 81.9% |

Continuation pages are the weak spot for the logistic regression, 88.9% against 96.9% for standard pages. Most of that gap is noise: the 16 noisy continuation pages were right 68.8% of the time, since blanking the top leaves the OCR less to work with. If your packets contain statements, continuation pages deserve their own line in your scorecard, and splitting is a separate step covered in the [packet splitting guide](/resources/blogs/split-loan-packet-pdf).

## What confidence threshold should you set, and what does it cost?

Pick the threshold from the error rate among the pages you accept, not from overall accuracy. A system with 95% accuracy that can tell which 5% it is unsure of is worth more than one at 97% that cannot. For each threshold the script reports the share accepted, the share sent to review, the wrong pages among the accepted ones with a Wilson interval, and the share of all errors that review caught.

| Accept at confidence of at least | Auto accepted | Sent to review | Wrong among accepted | Error rate among accepted | 95% interval | Wrong pages caught by review |
| --- | --- | --- | --- | --- | --- | --- |
| 0.00 | 100.0% | 0.0% | 24 of 480 | 5.0% | 3.4 to 7.3 | 0.0% |
| 0.30 | 100.0% | 0.0% | 24 of 480 | 5.0% | 3.4 to 7.3 | 0.0% |
| 0.40 | 94.0% | 6.0% | 6 of 451 | 1.3% | 0.6 to 2.9 | 75.0% |
| 0.50 | 91.9% | 8.1% | 0 of 441 | 0.0% | 0.0 to 0.9 | 100.0% |
| 0.60 | 91.2% | 8.8% | 0 of 438 | 0.0% | 0.0 to 0.9 | 100.0% |
| 0.70 | 90.0% | 10.0% | 0 of 432 | 0.0% | 0.0 to 0.9 | 100.0% |
| 0.80 | 88.8% | 11.2% | 0 of 426 | 0.0% | 0.0 to 0.9 | 100.0% |
| 0.90 | 85.2% | 14.8% | 0 of 409 | 0.0% | 0.0 to 0.9 | 100.0% |
| 0.95 | 78.8% | 21.2% | 0 of 378 | 0.0% | 0.0 to 1.0 | 100.0% |

Between 0.50 and 0.95 no accepted page was wrong. That is 0 of 441 at 0.50, and the interval means the true rate could be as high as 0.9%. At 0.40, six wrong pages slipped through. At 0.30 the threshold did nothing at all, because nothing scored below it. The price of safety rose slowly, from 8.1% of pages in review at 0.50 to 21.2% at 0.95. In this data a threshold of 0.50 to 0.60 was the sensible range. On real documents, with real lookalikes, the right value will be elsewhere, and the only way to find it is to run this sweep.

Naive Bayes and the keyword rules behave differently with the same pages.

| Accept at confidence of at least | Auto accepted | Sent to review | Wrong among accepted | Error rate among accepted | 95% interval | Wrong pages caught by review |
| --- | --- | --- | --- | --- | --- | --- |
| 0.00 | 100.0% | 0.0% | 31 of 480 | 6.5% | 4.6 to 9.0 | 0.0% |
| 0.30 | 94.0% | 6.0% | 5 of 451 | 1.1% | 0.5 to 2.6 | 83.9% |
| 0.40 | 93.3% | 6.7% | 2 of 448 | 0.4% | 0.1 to 1.6 | 93.5% |
| 0.50 | 93.3% | 6.7% | 2 of 448 | 0.4% | 0.1 to 1.6 | 93.5% |
| 0.60 | 93.1% | 6.9% | 1 of 447 | 0.2% | 0.0 to 1.3 | 96.8% |
| 0.70 | 92.9% | 7.1% | 1 of 446 | 0.2% | 0.0 to 1.3 | 96.8% |
| 0.80 | 92.7% | 7.3% | 0 of 445 | 0.0% | 0.0 to 0.9 | 100.0% |
| 0.90 | 92.7% | 7.3% | 0 of 445 | 0.0% | 0.0 to 0.9 | 100.0% |
| 0.95 | 92.5% | 7.5% | 0 of 444 | 0.0% | 0.0 to 0.9 | 100.0% |

Naive Bayes had 31 errors with no threshold and needed 0.80 to reach none among accepted pages, at a cost of 7.3% in review. The keyword rules are the cautionary table.

| Accept at confidence of at least | Auto accepted | Sent to review | Wrong among accepted | Error rate among accepted | 95% interval | Wrong pages caught by review |
| --- | --- | --- | --- | --- | --- | --- |
| 0.00 | 100.0% | 0.0% | 56 of 480 | 11.7% | 9.1 to 14.8 | 0.0% |
| 0.30 | 100.0% | 0.0% | 56 of 480 | 11.7% | 9.1 to 14.8 | 0.0% |
| 0.40 | 100.0% | 0.0% | 56 of 480 | 11.7% | 9.1 to 14.8 | 0.0% |
| 0.50 | 99.6% | 0.4% | 56 of 478 | 11.7% | 9.1 to 14.9 | 0.0% |
| 0.60 | 95.8% | 4.2% | 48 of 460 | 10.4% | 8.0 to 13.6 | 14.3% |
| 0.70 | 89.6% | 10.4% | 46 of 430 | 10.7% | 8.1 to 14.0 | 17.9% |
| 0.80 | 78.3% | 21.7% | 46 of 376 | 12.2% | 9.3 to 15.9 | 17.9% |
| 0.90 | 19.8% | 80.2% | 1 of 95 | 1.1% | 0.2 to 5.7 | 98.2% |
| 0.95 | 3.8% | 96.2% | 0 of 18 | 0.0% | 0.0 to 17.6 | 100.0% |

The rule confidence is not a probability. At 0.80 the error rate among accepted pages was 12.2%, higher than with no threshold at all, because pages with no OCR text were answered other at a confidence of about 0.88, which passes every threshold up to that value. Only at 0.90 did they drop out, and by then 80.2% of pages were in review. If your vendor or your own rules return a score, check what it means against labeled pages before routing on it.

The calibration view makes the same point by band.

| Confidence band | LR | NB | Rules |
| --- | --- | --- | --- |
| 0.0-0.3 | no pages | 29 pages, 10.3% right | no pages |
| 0.3-0.5 | 39 pages, 38.5% right | 3 pages, 0.0% right | 2 pages, 100.0% right |
| 0.5-0.7 | 9 pages, 100.0% right | 2 pages, 50.0% right | 48 pages, 79.2% right |
| 0.7-0.9 | 23 pages, 100.0% right | 1 pages, 0.0% right | 335 pages, 86.6% right |
| 0.9-1.0 | 409 pages, 100.0% right | 445 pages, 100.0% right | 95 pages, 98.9% right |

Confidence from the logistic regression was well ordered: its 409 pages above 0.9 were all right, and the 39 pages between 0.3 and 0.5 were right 38.5% of the time. Naive Bayes put 445 pages at 0.9 or above, all right, and its 29 pages below 0.3 were right 10.3% of the time. Only 6 pages fell in between. Its posterior is bunched at the two ends, so it works more as a flag for pages with nothing to read than as a graded score. Check that on your own pages and do not assume it from a table that happens to work.

### Is a word count rule just as good as a confidence threshold?

Here it was. We counted pages where OCR found fewer than 10 words: 34 of 480, 25 of them in the noisy tier. A rule that sends those to review needs no classifier at all.

| Baseline | Errors in all 480 pages | Errors on the 34 pages with fewer than 10 words | Accuracy on those 34 pages | Errors left if those 34 go to review |
| --- | --- | --- | --- | --- |
| TF-IDF logistic regression | 24 | 21 | 38.2% | 3 |
| Naive Bayes | 31 | 29 | 14.7% | 2 |
| Keyword rules | 56 | 30 | 11.8% | 26 |

Sending those 34 pages to review would have left the logistic regression with 3 errors out of 24, and naive Bayes with 2 out of 31. It cost 7.1% of pages in review, against 8.1% for the 0.50 threshold. The rules are a different story, with 26 errors left, which shows the word count catches blanks but not the rules' real weakness, which is losing key phrases to OCR. Use both signals if you can: the classifier's confidence and a plain check that the page had text.

## How many labeled examples does each class need?

About 10 per class gets you most of the way, and 20 to 40 to make sure no class is left behind. We trained on k pages per class, sampled from each training fold, three draws per fold, and scored on the held out fold. Each figure is the mean of 15 runs.

| Labeled pages per class | Training pages | LR accuracy | LR worst class recall | NB accuracy | NB worst class recall |
| --- | --- | --- | --- | --- | --- |
| 2 | 16 | 81.6% | 43.9% | 83.3% | 37.8% |
| 5 | 40 | 89.7% | 63.3% | 90.6% | 66.1% |
| 10 | 80 | 92.4% | 74.4% | 92.6% | 74.4% |
| 20 | 160 | 94.2% | 80.6% | 93.4% | 78.3% |
| 40 | 320 | 95.0% | 82.2% | 93.5% | 77.8% |

Accuracy rose from 81.6% at 2 pages per class to 92.4% at 10 and 95.0% at 40, which is the full cross validation level. The standard deviation across runs shrank from 4.6 points to 1.8. The worst class is the better guide to how many examples you need: its recall was 74.4% at 10 pages and 82.2% at 40, so one class was still lagging after 320 training pages. Naive Bayes stopped improving at about 20 per class. On a second generated set (seed 2027) the logistic regression went 83.1%, 87.4%, 91.3%, 93.6% and 94.9% across the same five sizes, so the shape holds, with a different wobble.

The ceiling here is set by OCR, not by examples. More labeled pages would not bring back the text from the pages Tesseract could not read. The practical advice: label 10 to 20 pages per class, run the test, read the confusion matrix and the pages in the worst class, and add labeled examples where it fails and not evenly.

## What happens when the layout is one the model has never seen?

Accuracy falls. We trained on two of the three layouts of every class and tested on the third. A real intake sees new layouts every week, so this is closer to how classification fails in production than cross validation is.

| Test pages | LR, seed 2026 | NB, seed 2026 | LR, seed 2027 | NB, seed 2027 |
| --- | --- | --- | --- | --- |
| Template 0 | 90.6% | 91.9% | 85.0% | 88.8% |
| Template 1 | 88.1% | 88.8% | 88.1% | 87.5% |
| Template 2 | 82.5% | 80.0% | 78.1% | 78.8% |
| Random held out pages, templates seen in training | 92.5% | not run | 96.2% | not run |

On the main set the logistic regression scored 90.6%, 88.1% and 82.5% on a layout it had never seen, against 92.5% on random pages from layouts it had seen, with the same number of training pages. The second set showed a wider gap (85.0%, 88.1%, 78.1% against 96.2%). With 160 pages per cell, each result has an interval of roughly 5 to 6 points either side, so the gap is real in direction and rough in size. Keep out a layout or an issuer at test time, and test on it. If the drop is big, your classifier is reading layout, not meaning.

## Why does 95% per page become 60% per packet?

Because a packet needs every page to be right, and errors do not spread evenly. Take a 10 page packet. If page results were independent, the chance of every page being right is the page accuracy to the tenth power.

| Pages in the packet come from | Pages right | Page accuracy | Chance all 10 pages are right (independence) |
| --- | --- | --- | --- |
| Clean, 200 dpi | 120 of 120 | 100.0% | 100.0% |
| Skewed 1.5 to 3.5 degrees | 119 of 120 | 99.2% | 92.0% |
| Low resolution, 75 dpi, JPEG | 112 of 120 | 93.3% | 50.2% |
| Scanner noise and blur | 105 of 120 | 87.5% | 26.3% |
| All pages pooled | 456 of 480 | 95.0% | 59.9% |

At 95.0% per page that is 59.9%. The pooled figure hides the packets that matter: a packet scanned entirely at clean quality passes at 100.0%, one scanned entirely with scanner noise passes at 26.3%. This is an independence calculation on measured page results, not a measurement of real packets, and we also simulated 20,000 packets from the page results to confirm the arithmetic: 60.0% for random mixes, 67.2% when all ten pages share a quality tier. What it supports is a reporting rule. Report accuracy by tier and keep a review path for the pages from bad scans, because an average accuracy figure will not tell you how many packets arrive complete.

## Do the results hold on a second, independent set?

We generated a second 480 page set from a different seed and ran the identical pipeline.

| Measure | Seed 2026 (main run) | Seed 2027 (second set) |
| --- | --- | --- |
| TF-IDF logistic regression | 95.0% | 95.2% |
| Naive Bayes | 93.5% | 93.8% |
| Keyword rules | 88.3% | 86.9% |
| LR, wrong among pages accepted at 0.50 | 0 of 441 | 0 of 441 |
| NB, wrong among pages accepted at 0.50 | 2 of 448 | 3 of 449 |
| Rules, wrong among pages accepted at 0.90 | 1 of 95 | 4 of 101 |
| Pages with fewer than 10 OCR words | 34 | 38 |

The logistic regression moved 0.2 points, naive Bayes 0.3 and the rules 1.4. The threshold result repeated: no wrong pages among 441 accepted at 0.50 for the logistic regression. It is two sets of one generator, not two sources of data, so it checks random variation and not that the result carries over to real pages.

## How do you run this on your own documents?

Put page images or PDF pages exported as images in a folder and write a manifest with three columns: id, file and label. The labels must come from your own staff, one label per page, using the classes you actually route on. Then run two commands.

```
python3 doc_class_test.py ocr my_pages python3 doc_class_test.py score my_pages
```

The script reads each page with Tesseract, cross validates the two trained baselines and the rules, and writes a pages CSV with every page's predicted class and confidence, and a results JSON with the tables in this guide. Template, tier and hard columns are optional. Fill in the tier by hand, such as phone photo, flatbed scan or digital PDF, if you want accuracy by quality. The rules in the script are written for the eight classes above, so edit the RULES table for yours, or ignore the rules baseline.

To score a vendor or your own classifier on the same pages, write its answers to a CSV with the columns id, label and confidence, and pass it on:

```
python3 doc_class_test.py score my_pages --external vendor_answers.csv
```

It prints the same overall, per class and threshold tables for the external answers. The score and the threshold sweep do not change, which is the point. Ask any vendor for a confidence per page, and test that it means something using the sweep above.

DocsAPI includes classification in its per-page price, which starts at $0.02 a page, see [pricing](/pricing). We have not published a classification accuracy figure for it from this harness. If you want to test it, run it on your own labeled pages and score its answers with `--external`.

If you are also weighing OCR engines, our [OCR accuracy benchmark](/resources/blogs/ocr-accuracy-benchmark-2026) compares them on real documents, and classification accuracy will follow whichever one reads your worst scans.

## What this test cannot tell you

The pages are generated, in one language, in a few fonts, with no handwriting, stamps, staples, folds or photographs. The layouts and the lookalike variants were written by the same person who wrote the classifiers, and class vocabulary survives in them. One OCR engine was used. There are 480 pages per set and 60 per class, so per class numbers are rough. The baselines are small. A layout aware model may treat lookalikes and blank pages differently, and this test does not say how. None of this says how any commercial product performs. It says how to measure one, and how large the traps are when you do.

## The script and the results

The whole test is one Python file. It needs Python 3.9 or later, numpy, Pillow and Tesseract 5 on the path. A different set of installed fonts or a different Tesseract version will move the numbers a little.

```
python3 doc_class_test.py generate data --seed 2026 --per-cell 15 python3 doc_class_test.py ocr data python3 doc_class_test.py score data
```

Download the [script](/downloads/document-classification-test/doc_class_test.py), the per page results for the [main run](/downloads/document-classification-test/pages_seed2026.csv) and the [second set](/downloads/document-classification-test/pages_seed2027.csv), and the figures behind every table as JSON for [seed 2026](/downloads/document-classification-test/results_seed2026.json) and [seed 2027](/downloads/document-classification-test/results_seed2027.json). Each CSV has one row per page with the label, template, tier, OCR word count, and the predicted class, confidence and correctness for each baseline. Here is the whole script:

```
#!/usr/bin/env python3 """Document classification test harness for a lending packet: generate, OCR, classify, score. python3 doc_class_test.py generate DIR --seed 2026 --per-cell 15 python3 doc_class_test.py ocr DIR python3 doc_class_test.py score DIR [--external predictions.csv] Own documents: put images in DIR, write DIR/manifest.csv with columns id,file,label (template, tier and hard may be left blank), then run ocr and score. Writes DIR/ocr.json, DIR/pages.csv (one row per page, out-of-fold predictions) and DIR/results.json (every figure used in the post). Needs Python 3.9+, numpy, pillow and tesseract 5 on PATH. No scikit-learn: the TF-IDF + logistic regression and naive Bayes baselines are written here. All three classifiers are baselines written for this test. They are not any vendor's product. To test a vendor, write its answers to a CSV with columns id,label,confidence and pass it as --external; the scoring does not change. """ import argparse, csv, io, json, math, os, random, re, subprocess, sys, time from collections import Counter, defaultdict from multiprocessing import Pool from pathlib import Path import numpy as np from PIL import Image, ImageDraw, ImageFilter, ImageFont CLASSES = ["invoice", "receipt", "bank_statement", "pay_stub", "tax_form", "id_card", "utility_bill", "other"] TIERS = ["clean", "noise", "skew", "low"] TEMPLATES = [0, 1, 2] HARD_P = 0.30 # share of pages that use the confusable header variant of their class CONT_P = 0.20 # share that are continuation pages: the header block is missing CUT = {"invoice": 880, "receipt": 480, "bank_statement": 600, "pay_stub": 640, "tax_form": 330, "utility_bill": 600, "other": 400, "id_card": 0} FOLDS = 5 DPI = 200 W, H = int(8.5 * DPI), int(11 * DPI) # ------------------------------------------------------------------ fonts and canvas FONT_DIRS = ["/System/Library/Fonts/Supplemental/", "/Library/Fonts/", "/usr/share/fonts/truetype/msttcorefonts/", "/usr/share/fonts/truetype/dejavu/", "C:/Windows/Fonts/"] FONT_FILES = {"sans": ["Arial.ttf", "arial.ttf", "DejaVuSans.ttf"], "sansb": ["Arial Bold.ttf", "arialbd.ttf", "DejaVuSans-Bold.ttf"], "serif": ["Times New Roman.ttf", "times.ttf", "DejaVuSerif.ttf"], "serifb": ["Times New Roman Bold.ttf", "timesbd.ttf", "DejaVuSerif-Bold.ttf"], "mono": ["Courier New.ttf", "cour.ttf", "DejaVuSansMono.ttf"], "monob": ["Courier New Bold.ttf", "courbd.ttf", "DejaVuSansMono-Bold.ttf"], "geo": ["Georgia.ttf", "georgia.ttf", "DejaVuSerif.ttf"], "geob": ["Georgia Bold.ttf", "georgiab.ttf", "DejaVuSerif-Bold.ttf"], "verd": ["Verdana.ttf", "verdana.ttf", "DejaVuSans.ttf"], "verdb": ["Verdana Bold.ttf", "verdanab.ttf", "DejaVuSans-Bold.ttf"]} _FC = {} def font(name, pt): px = max(8, int(round(pt * DPI / 72))) key = (name, px) if key not in _FC: f = None for fn in FONT_FILES[name]: for d in FONT_DIRS: if os.path.exists(d + fn): f = ImageFont.truetype(d + fn, px) break if f: break _FC[key] = f or ImageFont.load_default(px) return _FC[key] class Page: """A page that remembers every string drawn on it (the oracle text).""" def __init__(self): self.im = Image.new("L", (W, H), 255) self.d = ImageDraw.Draw(self.im) self.words = [] self.ys = [] def blank_above(self, y): """Continuation page: white out everything above y and forget those words.""" if y > 0: self.d.rectangle((0, 0, W, y), fill=255) self.words = [w for w, yy in zip(self.words, self.ys) if yy >= y] self.ys = [yy for yy in self.ys if yy >= y] def t(self, x, y, s, f="sans", pt=10, right=False, center=False): s = str(s) self.ys.append(y) fo = font(f, pt) w = self.d.textlength(s, font=fo) xx = x - w if right else (x - w / 2 if center else x) self.d.text((xx, y), s, font=fo, fill=0) self.words.append(s) def line(self, x1, y1, x2, y2, w=2): self.d.line((x1, y1, x2, y2), fill=0, width=w) def box(self, x1, y1, x2, y2, w=2): self.d.rectangle((x1, y1, x2, y2), outline=0, width=w) def fill(self, x1, y1, x2, y2, v=0): self.d.rectangle((x1, y1, x2, y2), fill=v) def I(pt): return int(pt * DPI / 72) # ------------------------------------------------------------------ content pools CO1 = ["Northwind", "Alder", "Birch", "Cobalt", "Dunmore", "Everly", "Fairhaven", "Granite", "Harlow", "Ironbridge", "Juniper", "Kestrel", "Larkspur", "Mercer", "Norfolk", "Oakridge", "Pinecrest", "Quillon", "Ridgeway", "Stonebrook"] CO2 = ["Supply Co.", "Logistics Ltd", "Industrial Inc.", "Office Goods", "Packaging LLC", "Tools and Parts", "Freight Services", "Foods Market", "Hardware"] FIRST = ["Maria", "James", "Priya", "Daniel", "Aisha", "Tomas", "Grace", "Omar", "Elena", "Kevin", "Linh", "Robert", "Sofia", "Marcus", "Hannah", "Victor"] LAST = ["Alvarez", "Brooks", "Chen", "Dawson", "Edwards", "Fischer", "Gupta", "Hughes", "Ibrahim", "Jensen", "Kowalski", "Lopez", "Morgan", "Nguyen", "Okafor", "Patel"] STREET = ["Mill Road", "Station Lane", "Harbor Street", "Foundry Way", "Elm Avenue", "Canal Row", "Maple Drive", "Cedar Court"] CITY = ["Springfield", "Riverton", "Lakeview", "Fairmont", "Ashland", "Brookline", "Glenwood", "Westbury"] ST = ["CA", "TX", "NY", "OH", "WA", "IL", "FL", "GA"] ITEMS = ["Thermal paper rolls", "Pipe fittings", "Label ribbon", "Safety gloves", "Pallet wrap", "Bearing set", "Cable ties", "Filter cartridges", "Hex bolts", "Storage bins", "Work lamps", "Drill bits", "Printer toner", "Copy paper", "Cleaning supplies"] GROC = ["Whole milk", "Brown bread", "Eggs dozen", "Bananas", "Chicken breast", "Coffee beans", "Orange juice", "Pasta", "Tomatoes", "Cheddar", "Dish soap", "Batteries AA"] MON = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] MERCH = ["POS DEBIT GROCERY", "ATM WITHDRAWAL", "ONLINE TRANSFER", "CHECK DEPOSIT", "UTILITY AUTOPAY", "FUEL STATION", "RESTAURANT", "PHARMACY", "INSURANCE PREMIUM", "RENT PAYMENT"] PROSE = ("we would like to thank you for taking the time to meet with us last week and for the clear overview you gave of the project timeline " "the team has reviewed the points raised and agrees with most of them there are a few open questions about scope and about who will own the next " "steps please let us know a convenient time to talk again this month so that we can confirm the plan and share it with everyone involved " "in the meantime we will continue to gather the background material and prepare a short summary for the group").split() def nm(r): return f"{r.choice(FIRST)} {r.choice(LAST)}" def co(r): return f"{r.choice(CO1)} {r.choice(CO2)}" def addr(r): return f"{r.randint(2, 980)} {r.choice(STREET)}, {r.choice(CITY)} {r.choice(ST)} {r.randint(10000, 99999)}" def money(r, a, b): return f"{r.randint(a, b)}.{r.randint(0, 99):02d}" def mdy(r): return f"{r.randint(1, 12):02d}/{r.randint(1, 28):02d}/2026" def dmy(r): return f"{r.randint(1, 28)} {r.choice(MON)} 2026" def acct(r): return "".join(str(r.randint(0, 9)) for _ in range(r.choice([8, 10]))) def fm(x): return f"{x:,.2f}" def prose(r, n): out = [] for _ in range(n): out.append(r.choice(PROSE)) s = " ".join(out) return s[0].upper() + s[1:] + "." def wrap(s, n): words, lines, cur = s.split(), [], "" for w in words: if len(cur) + len(w) + 1 > n: lines.append(cur) cur = w else: cur = (cur + " " + w).strip() return lines + [cur] # ------------------------------------------------------------------ page templates: each returns a Page def draw_invoice(r, tpl, hard): p = Page() f, fb = [("sans", "sansb"), ("serif", "serifb"), ("verd", "verdb")][tpl] vendor, no = co(r), f"{r.choice(['INV', 'BC', 'SI'])}-{r.randint(10000, 99999)}" x0 = 150 p.t(x0, 150, vendor, fb, 20) p.t(x0, 150 + I(26), addr(r), f, 10) if hard: # no big title word; looks like a shop slip p.t(W - 150, 160, f"Inv # {no}", f, 11, right=True) else: p.t(W - 150, 150, "INVOICE" if tpl != 1 else "Tax Invoice", fb, 26, right=True) p.t(W - 150, 150 + I(34), f"Invoice No: {no}", f, 11, right=True) p.t(W - 150, 150 + I(52), f"Date: {mdy(r) if tpl != 1 else dmy(r)}", f, 11, right=True) y = 520 p.t(x0, y, "Bill To", fb, 11) p.t(x0, y + I(16), nm(r), f, 11) p.t(x0, y + I(30), addr(r), f, 10) if not hard or r.random()  H - 300: break y += 40 p.t(x0, y, "Closing balance", fb, 11) p.t(x0 + 520, y, fm(bal), fb, 11, right=True) p.t(x0, H - 160, "Member FDIC. Questions about this statement? Call the number on your card.", f, 8) return p def draw_stub(r, tpl, hard): p = Page() f, fb = [("sans", "sansb"), ("mono", "monob"), ("geo", "geob")][tpl] emp = co(r) x0 = 150 p.t(x0, 150, emp, fb, 18) p.t(x0, 150 + I(24), addr(r), f, 10) title = "Statement" if hard else r.choice(["Earnings Statement", "Pay Stub", "Payslip"]) if tpl == 0 else ("Earnings Statement" if tpl == 1 else "Payslip") p.t(W - 150, 150, title, fb, 20, right=True) y = 420 p.t(x0, y, f"Employee: {nm(r)}", f, 11) p.t(x0, y + I(15), f"Employee ID: {r.randint(1000, 99999)}", f, 10) d = r.randint(1, 12) p.t(W - 150, y, f"{'Period' if hard else 'Pay period'}: {d:02d}/01/2026 - {d:02d}/15/2026", f, 10, right=True) p.t(W - 150, y + I(15), f"{'Date' if hard else 'Pay date'}: {d:02d}/20/2026", f, 10, right=True) if hard: p.t(W - 150, y + I(30), f"Account ending {r.randint(1000, 9999)}", f, 10, right=True) y += 180 p.fill(x0, y, W - 150, y + 56, 215) for cx, lab, rt in [(x0 + 10, "Earnings", False), (900, "Rate", True), (1100, "Hours", True), (1350, "Current", True), (W - 160, "YTD", True)]: p.t(cx, y + 10, lab, fb, 11, right=rt) y += 76 rate = r.randint(1800, 6500) / 100 hrs = r.choice([80, 80, 72, 86.5]) gross = rate * hrs for lab, a in [("Regular", gross), ("Overtime", rate * 1.5 * r.randint(0, 6))]: p.t(x0 + 10, y, lab, f, 11) p.t(900, y, fm(rate), f, 11, right=True) p.t(1100, y, str(hrs), f, 11, right=True) p.t(1350, y, fm(a), f, 11, right=True) p.t(W - 160, y, fm(a * r.randint(3, 20)), f, 11, right=True) y += 52 y += 40 p.t(x0 + 10, y, "Deductions", fb, 11) y += 56 ded = 0 for lab, pc in [("Federal income tax", 0.12), ("Social Security", 0.062), ("Medicare", 0.0145), ("State tax", 0.04), ("401k", 0.05)]: a = gross * pc ded += a p.t(x0 + 10, y, lab, f, 11) p.t(1350, y, fm(a), f, 11, right=True) p.t(W - 160, y, fm(a * r.randint(3, 20)), f, 11, right=True) y += 52 y += 40 p.t(x0 + 10, y, "Gross pay", fb, 12) p.t(1350, y, fm(gross), fb, 12, right=True) p.t(x0 + 10, y + 56, "Net pay", fb, 12) p.t(1350, y + 56, fm(gross - ded), fb, 12, right=True) p.t(x0 + 10, y + 150, f"Direct deposit to account ****{r.randint(1000, 9999)}", f, 10) return p def draw_tax(r, tpl, hard): p = Page() x0 = 150 yr = 2025 if tpl == 0: # W-2 style grid if not hard: p.t(x0, 150, "Form W-2 Wage and Tax Statement", "sansb", 18) p.t(x0, 150 + I(24), f"Department of the Treasury Internal Revenue Service {yr}", "sans", 10) else: p.t(x0, 150, f"Copy B To be filed with employee's federal tax return {yr}", "sans", 11) labs = ["a Employee's social security number", "b Employer identification number (EIN)", "c Employer's name, address, and ZIP code", "1 Wages, tips, other compensation", "2 Federal income tax withheld", "3 Social security wages", "4 Social security tax withheld", "5 Medicare wages and tips", "6 Medicare tax withheld", "e Employee's first name and initial Last name", "15 State Employer's state ID number", "16 State wages, tips, etc.", "17 State income tax"] y = 330 for i, lab in enumerate(labs): cx = x0 + (i % 2) * 760 yy = y + (i // 2) * 190 p.box(cx, yy, cx + 740, yy + 170, 2) p.t(cx + 12, yy + 10, lab, "sans", 8) val = f"{r.randint(100, 999)}-{r.randint(10, 99)}-{r.randint(1000, 9999)}" if i == 0 else (f"{r.randint(10, 99)}-{r.randint(1000000, 9999999)}" if i == 1 else (co(r) if i == 2 else (nm(r) if i == 9 else money(r, 1000, 95000)))) p.t(cx + 30, yy + 90, val, "mono", 12) elif tpl == 1: # 1099-NEC style if not hard: p.t(x0, 150, f"Form 1099-NEC Nonemployee Compensation {yr}", "sansb", 18) p.t(x0, 150 + I(24), "Department of the Treasury Internal Revenue Service", "sans", 10) else: p.t(x0, 150, f"Copy 1 For state tax department {yr}", "sans", 11) y = 330 for i, (lab, v) in enumerate([("PAYER'S name, street address, city, state, ZIP code", co(r)), ("PAYER'S TIN", f"{r.randint(10, 99)}-{r.randint(1000000, 9999999)}"), ("RECIPIENT'S TIN", f"{r.randint(100, 999)}-{r.randint(10, 99)}-{r.randint(1000, 9999)}"), ("RECIPIENT'S name", nm(r)), ("1 Nonemployee compensation", "$ " + money(r, 2000, 90000)), ("4 Federal income tax withheld", "$ " + money(r, 0, 5000)), ("5 State tax withheld", "$ " + money(r, 0, 3000)), ("Account number (see instructions)", acct(r))]): yy = y + i * 190 p.box(x0, yy, W - 150, yy + 170, 2) p.t(x0 + 12, yy + 10, lab, "sans", 8) p.t(x0 + 30, yy + 90, v, "mono", 12) else: # 1040 summary lines if not hard: p.t(x0, 150, f"Form 1040 U.S. Individual Income Tax Return {yr}", "sansb", 17) else: p.t(x0, 150, f"Page 2 {yr}", "sans", 12) p.t(x0, 150 + I(26), f"Filing status: {r.choice(['Single', 'Married filing jointly', 'Head of household'])}", "sans", 11) p.t(x0, 150 + I(42), f"Your social security number {r.randint(100, 999)}-{r.randint(10, 99)}-{r.randint(1000, 9999)}", "sans", 11) y = 420 for lab in ["1a Total amount from Form(s) W-2, box 1", "2b Taxable interest", "3b Ordinary dividends", "9 Total income", "11 Adjusted gross income", "12 Standard deduction or itemized deductions", "15 Taxable income", "16 Tax", "24 Total tax", "25a Federal income tax withheld from Form(s) W-2", "33 Total payments", "34 Amount you overpaid"]: p.t(x0, y, lab, "sans", 11) p.t(W - 150, y, money(r, 0, 120000), "mono", 11, right=True) p.line(x0, y + 44, W - 150, y + 44, 1) y += 100 p.t(x0, y + 30, "Sign here. Under penalties of perjury, I declare that I have examined this return.", "sans", 9) return p def draw_id(r, tpl, hard): p = Page() cw, ch = 1020, 640 x0, y0 = 340 + r.randint(-60, 60), 500 + r.randint(-80, 120) p.box(x0, y0, x0 + cw, y0 + ch, 4) state = r.choice(["California", "Texas", "New York", "Ohio", "Washington", "Illinois"]) if tpl == 0: p.fill(x0 + 4, y0 + 4, x0 + cw - 4, y0 + 90, 200) if hard: # back side: barcode and restrictions p.t(x0 + 30, y0 + 20, f"{state.upper()}", "sansb", 14) for i in range(60): xx = x0 + 40 + i * 15 p.fill(xx, y0 + 130, xx + r.choice([3, 6, 9]), y0 + 330, 0) p.t(x0 + 40, y0 + 370, f"RESTRICTIONS NONE ENDORSEMENTS NONE", "sans", 8) p.t(x0 + 40, y0 + 420, f"ORGAN DONOR {r.randint(1000, 9999)}-{r.randint(1000, 9999)}", "sans", 8) else: p.t(x0 + 30, y0 + 20, f"{state.upper()} DRIVER LICENSE", "sansb", 14) p.box(x0 + 30, y0 + 130, x0 + 300, y0 + 470, 2) p.t(x0 + 165, y0 + 280, "PHOTO", "sans", 10, center=True) n = nm(r).split() for i, (lab, v) in enumerate([("DL", f"{r.choice('ABCD')}{r.randint(1000000, 9999999)}"), ("LN", n[1].upper()), ("FN", n[0].upper()), ("DOB", mdy(r).replace("/2026", f"/{r.randint(1950, 2002)}")), ("EXP", mdy(r).replace("/2026", "/2030")), ("CLASS", "C"), ("SEX", r.choice("MF")), ("HGT", f"{r.randint(5, 6)}-{r.randint(0, 11):02d}"), ("EYES", r.choice(["BRN", "BLU", "GRN"]))]): p.t(x0 + 340, y0 + 110 + i * 46, f"{lab} {v}", "sansb" if i  0.996] = 255 return Image.fromarray(np.clip(a, 0, 255).astype(np.uint8)), DPI if tier == "skew": ang = nr.uniform(1.5, 3.5) * nr.choice([-1, 1]) img = im.rotate(ang, resample=Image.BICUBIC, expand=False, fillcolor=255).filter(ImageFilter.GaussianBlur(0.6)) a = np.asarray(img, dtype=np.float32) + nr.normal(0, 9, (H, W)) return Image.fromarray(np.clip(a, 0, 255).astype(np.uint8)), DPI img = im.filter(ImageFilter.GaussianBlur(1.2)).resize((W * 3 // 8, H * 3 // 8), Image.BILINEAR) a = np.asarray(img, dtype=np.float32) * 0.93 + 10 + nr.normal(0, 18, (H * 3 // 8, W * 3 // 8)) img = Image.fromarray(np.clip(a, 0, 255).astype(np.uint8)) buf = io.BytesIO() img.save(buf, "JPEG", quality=35) return Image.open(io.BytesIO(buf.getvalue())).convert("L"), DPI * 3 // 8 def generate(a): out = Path(a.dir) (out / "img").mkdir(parents=True, exist_ok=True) rows = [] n = 0 for ci, cl in enumerate(CLASSES): for ti, tier in enumerate(TIERS): for k in range(a.per_cell): seed = a.seed * 100000 + ci * 10000 + ti * 1000 + k r = random.Random(seed) nr = np.random.RandomState(seed % (2 ** 31)) tpl = k % 3 u = r.random() hard = 1 if u = 12 and c[0] == "5" and c[11].strip(): words.append(c[11]) try: confs.append(float(c[10])) except ValueError: pass return {"text": " ".join(words), "n_words": len(words), "mean_conf": round(float(np.mean(confs)), 1) if confs else 0.0, "seconds": round(time.time() - t0, 3)} def read_manifest(d): with open(Path(d) / "manifest.csv", newline="") as fh: rows = list(csv.DictReader(fh)) for r in rows: r.setdefault("template", "") r.setdefault("tier", "") r.setdefault("hard", "") r.setdefault("oracle", "") r["tier"] = r["tier"] or "na" r["hard"] = r["hard"] or "na" return rows def run_ocr(a): d = Path(a.dir) rows = read_manifest(d) jobs = [(d / r["file"], int(r.get("dpi") or DPI)) for r in rows] with Pool(a.procs) as pool: res = pool.map(tess, jobs, chunksize=4) ver = subprocess.run(["tesseract", "--version"], capture_output=True, text=True).stdout.splitlines()[0] json.dump({"tesseract": ver, "pages": {r["id"]: x for r, x in zip(rows, res)}}, open(d / "ocr.json", "w")) print("ocr done", len(res), ver) # ------------------------------------------------------------------ text features def toks(text): t = re.sub(r"\d+", "0", text.lower()) return re.findall(r"[a-z0]{2,}", t) def grams(text): w = toks(text) return w + [w[i] + "_" + w[i + 1] for i in range(len(w) - 1)] class Tfidf: def __init__(self, min_df=2): self.min_df = min_df def fit(self, docs): df = Counter() for d in docs: df.update(set(grams(d))) self.vocab = {t: i for i, t in enumerate(sorted(t for t, c in df.items() if c >= self.min_df))} n = len(docs) self.idf = np.zeros(len(self.vocab)) for t, i in self.vocab.items(): self.idf[i] = math.log((1 + n) / (1 + df[t])) + 1 return self def counts(self, docs): X = np.zeros((len(docs), len(self.vocab))) for i, d in enumerate(docs): for t, c in Counter(grams(d)).items(): j = self.vocab.get(t) if j is not None: X[i, j] = c return X def transform(self, docs): X = self.counts(docs) X = np.where(X > 0, 1 + np.log(np.maximum(X, 1)), 0) * self.idf nrm = np.linalg.norm(X, axis=1, keepdims=True) return X / np.maximum(nrm, 1e-9) def softmax(z): z = z - z.max(1, keepdims=True) e = np.exp(z) return e / e.sum(1, keepdims=True) class LogReg: """Multinomial logistic regression on TF-IDF, L2, full-batch Adam, fixed 300 steps.""" def __init__(self, lam=1e-4, steps=300, lr=0.1): self.lam, self.steps, self.lr = lam, steps, lr def fit(self, docs, y): self.tf = Tfidf().fit(docs) X = self.tf.transform(docs) Y = np.eye(len(CLASSES))[y] n, d = X.shape Wt = np.zeros((d, len(CLASSES))) b = np.zeros(len(CLASSES)) m = np.zeros_like(Wt); v = np.zeros_like(Wt); mb = np.zeros_like(b); vb = np.zeros_like(b) for s in range(1, self.steps + 1): P = softmax(X @ Wt + b) G = X.T @ (P - Y) / n + self.lam * Wt gb = (P - Y).mean(0) for (p_, g_, m_, v_) in ((Wt, G, m, v), (b, gb, mb, vb)): m_ *= 0.9; m_ += 0.1 * g_ v_ *= 0.999; v_ += 0.001 * g_ * g_ p_ -= self.lr * (m_ / (1 - 0.9 ** s)) / (np.sqrt(v_ / (1 - 0.999 ** s)) + 1e-8) self.W, self.b = Wt, b return self def proba(self, docs): return softmax(self.tf.transform(docs) @ self.W + self.b) class NB: """Multinomial naive Bayes on word counts, add 0.5 smoothing.""" def fit(self, docs, y, alpha=0.5): self.tf = Tfidf(min_df=2).fit(docs) X = self.tf.counts(docs) y = np.asarray(y) self.logp = np.zeros((len(CLASSES), X.shape[1])) self.prior = np.zeros(len(CLASSES)) for c in range(len(CLASSES)): xc = X[y == c] self.prior[c] = math.log((len(xc) + 1) / (len(y) + len(CLASSES))) s = xc.sum(0) + alpha self.logp[c] = np.log(s / s.sum()) return self def proba(self, docs): return softmax(self.tf.counts(docs) @ self.logp.T + self.prior) # keyword rules, written by hand and frozen on a development set (seed 1) before the test set was generated RULES = { "invoice": [(r"\binvoice\b", 2), (r"bill to", 2), (r"due date", 2), (r"net 30", 2), (r"po number", 2), (r"unit price", 1.5), (r"\bqty\b", 1), (r"amount", .5), (r"total due", 1), (r"remit", 1.5), (r"terms", 1), (r"thank you for your business", .5)], "receipt": [(r"receipt", 3), (r"paid by", 2.5), (r"visa|mastercard|debit|cash", 1), (r"trans\b", 1.5), (r"thank you for shopping", 3), (r"returns", 1.5), (r"\breg\b", 1.5), (r"subtotal", .5), (r"\btel\b", 1)], "bank_statement": [(r"opening balance", 3), (r"closing balance", 3), (r"statement period", 2), (r"account statement|statement of account", 2), (r"\bdebit\b", 1), (r"\bcredit\b", .5), (r"\bbalance\b", 1), (r"\bfdic\b", 2), (r"account summary", 2), (r"bank|credit union|trust", 1), (r"atm|pos debit|transfer", 1)], "pay_stub": [(r"earnings", 2.5), (r"pay stub|payslip", 3), (r"pay period", 2.5), (r"pay date", 2), (r"gross pay", 2.5), (r"net pay", 2.5), (r"\bytd\b", 2), (r"deductions", 2), (r"federal income tax", 1), (r"medicare", 1.5), (r"social security", 1), (r"employee", 1.5), (r"401k", 1.5)], "tax_form": [(r"internal revenue", 3), (r"\bform w", 3), (r"1099", 3), (r"1040", 3), (r"employer identification", 2.5), (r"withheld", 1.5), (r"wages, tips", 3), (r"filing status", 2.5), (r"taxable income", 2), (r"\btin\b", 2), (r"nonemployee", 3), (r"copy [b1]", 2), (r"treasury", 2), (r"adjusted gross", 2.5)], "id_card": [(r"driver", 2.5), (r"license", 2.5), (r"identification card", 3), (r"passport", 3), (r"\bdob\b|date of birth", 2), (r"\bexp\b|expires|date of expiry", 1.5), (r"\bsex\b", 1.5), (r"\bhgt\b", 2), (r"eyes", 2), (r"nationality", 2), (r"organ donor|restrictions|endorsements", 2.5), (r"surname|given names", 2), (r"signature", .5), (r"p= t n = int(acc.sum()) err = int(((pred != y) & acc).sum()) junk = int(((y == CLASSES.index("other")) & acc & (pred != y)).sum()) out.append({"threshold": t, "auto": n, "auto_pct": pct(n, len(y)), "review_pct": pct(len(y) - n, len(y)), "errors_in_auto": err, "auto_error_pct": pct(err, n), "auto_error_ci": wilson(err, n), "errors_caught_pct": pct(int((pred != y).sum()) - err, int((pred != y).sum())), "junk_accepted_as_class": junk}) return out def score(a): d = Path(a.dir) rows = read_manifest(d) ocr = json.load(open(d / "ocr.json")) ids = [r["id"] for r in rows] docs = [ocr["pages"][i]["text"] for i in ids] y = np.array([CLASSES.index(r["label"]) for r in rows]) tier = np.array([r["tier"] for r in rows]) tpl = np.array([r["template"] for r in rows]) hard = np.array([r["hard"] for r in rows]) fold = folds_for(rows, a.seed) res = {"n_pages": len(rows), "tesseract": ocr["tesseract"], "numpy": np.__version__, "python": sys.version.split()[0], "folds": FOLDS, "class_counts": {c: int((y == i).sum()) for i, c in enumerate(CLASSES)}} kinds = ["rules", "tfidf_lr", "naive_bayes"] kmap = {"rules": "rules", "tfidf_lr": "tfidf_lr", "naive_bayes": "nb"} P = {k: crossval(kmap[k], docs, y, fold) for k in kinds} if a.external: ext = {r["id"]: r for r in csv.DictReader(open(a.external))} Pe = np.full((len(rows), len(CLASSES)), 0.0) for i, rid in enumerate(ids): c = float(ext[rid]["confidence"]) Pe[i] = (1 - c) / (len(CLASSES) - 1) Pe[i, CLASSES.index(ext[rid]["label"])] = c P["external"] = Pe res["overall"], res["per_class"], res["confusion"], res["by_tier"], res["by_hard"] = {}, {}, {}, {}, {} for k, Pk in P.items(): pred = Pk.argmax(1) ok = int((pred == y).sum()) res["overall"][k] = {"correct": ok, "n": len(y), "acc": pct(ok, len(y)), "ci": wilson(ok, len(y))} M = confusion(y, pred) res["confusion"][k] = M.tolist() res["per_class"][k] = per_class(M) res["by_tier"][k] = {t: {"n": int((tier == t).sum()), "acc": pct(int(((pred == y) & (tier == t)).sum()), int((tier == t).sum()))} for t in sorted(set(tier))} res["by_hard"][k] = {h: {"n": int((hard == h).sum()), "acc": pct(int(((pred == y) & (hard == h)).sum()), int((hard == h).sum()))} for h in sorted(set(hard))} res["by_hard"][k]["_by_tier_hard"] = {f"{t}|{h}": pct(int(((pred == y) & (tier == t) & (hard == h)).sum()), int(((tier == t) & (hard == h)).sum())) for t in sorted(set(tier)) for h in sorted(set(hard)) if ((tier == t) & (hard == h)).sum()} # confusable pairs pairs = [("invoice", "receipt"), ("invoice", "utility_bill"), ("pay_stub", "bank_statement"), ("other", "invoice"), ("other", "bank_statement")] res["pairs"] = {} for k in kinds: pred = P[k].argmax(1) res["pairs"][k] = {f"{a_}->{b_}": int(((y == CLASSES.index(a_)) & (pred == CLASSES.index(b_))).sum()) + 0 for a_, b_ in pairs} res["pairs"][k].update({f"{b_}->{a_}": int(((y == CLASSES.index(b_)) & (pred == CLASSES.index(a_))).sum()) for a_, b_ in pairs}) # OCR quality: share of oracle word tokens that OCR found if rows[0]["oracle"]: rec = [] for r, dd in zip(rows, docs): o = set(toks(r["oracle"])) rec.append(len(o & set(toks(dd))) / max(1, len(o))) rec = np.array(rec) res["ocr_token_recall"] = {t: round(100 * float(rec[tier == t].mean()), 1) for t in sorted(set(tier))} res["ocr_token_recall"]["all"] = round(100 * float(rec.mean()), 1) # same classifiers on the generator's own text: isolates template difficulty from OCR damage oracle_docs = [r["oracle"] for r in rows] res["oracle"] = {} for k in kinds: Po = crossval(kmap[k], oracle_docs, y, fold) pred = Po.argmax(1) res["oracle"][k] = {"acc": pct(int((pred == y).sum()), len(y)), "n": len(y), "easy": pct(int(((pred == y) & (hard == "0")).sum()), int((hard == "0").sum())), "hard": pct(int(((pred == y) & (hard != "0")).sum()), int((hard != "0").sum())), "n_easy": int((hard == "0").sum()), "n_hard": int((hard != "0").sum()), "ocr_easy": pct(int(((P[k].argmax(1) == y) & (hard == "0")).sum()), int((hard == "0").sum())), "ocr_hard": pct(int(((P[k].argmax(1) == y) & (hard != "0")).sum()), int((hard != "0").sum()))} # threshold sweep thr = [0.0, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 0.95] res["sweep"] = {k: sweep(P[k], y, thr) for k in P} # calibration bins bins = [0, 0.3, 0.5, 0.7, 0.9, 1.01] res["calibration"] = {} for k in P: conf, pred = P[k].max(1), P[k].argmax(1) res["calibration"][k] = [{"bin": f"{bins[i]:.1f}-{min(bins[i + 1], 1):.1f}", "n": int(((conf >= bins[i]) & (conf = bins[i]) & (conf = bins[i]) & (conf = t) & (tier == tt)).sum()), int((tier == tt).sum())), "auto_errors": int(((conf >= t) & (tier == tt) & (pred != y)).sum()), "auto": int(((conf >= t) & (tier == tt)).sum())} for tt in sorted(set(tier))} # learning curve: k labeled pages per class, evaluated on the held-out fold rs = random.Random(a.seed + 7) ks = [2, 5, 10, 20, 40] res["learning_curve"] = {"ks": ks, "reps": 3, "tfidf_lr": {}, "naive_bayes": {}} for kind, nm_ in [("tfidf_lr", "tfidf_lr"), ("nb", "naive_bayes")]: for k in ks: accs, worst = [], [] for f in range(FOLDS): tr_all = np.where(fold != f)[0] te = np.where(fold == f)[0] for _ in range(3): tr = [] for c in range(len(CLASSES)): pool_ = [i for i in tr_all if y[i] == c] tr += rs.sample(pool_, min(k, len(pool_))) Pk = fit_predict(kind, [docs[i] for i in tr], y[tr], [docs[i] for i in te]) pr = Pk.argmax(1) accs.append(float((pr == y[te]).mean())) worst.append(min(float((pr[y[te] == c] == c).mean()) for c in range(len(CLASSES)) if (y[te] == c).sum())) res["learning_curve"][nm_][str(k)] = {"acc": round(100 * float(np.mean(accs)), 1), "worst_class_recall": round(100 * float(np.mean(worst)), 1), "sd": round(100 * float(np.std(accs)), 1)} # unseen template: train on two templates of each class, test on the third tpl_i = np.array([int(t) if t not in ("", "na") else -1 for t in tpl]) if (tpl_i >= 0).all(): res["unseen_template"] = {"tfidf_lr": {}, "naive_bayes": {}, "seen_same_size": {}} for kind, nm_ in [("tfidf_lr", "tfidf_lr"), ("nb", "naive_bayes")]: for t in TEMPLATES: tr, te = np.where(tpl_i != t)[0], np.where(tpl_i == t)[0] pr = fit_predict(kind, [docs[i] for i in tr], y[tr], [docs[i] for i in te]).argmax(1) res["unseen_template"][nm_][str(t)] = {"acc": pct(int((pr == y[te]).sum()), len(te)), "n": int(len(te))} rnd = random.Random(a.seed + 11) te_all = np.where(tpl_i == 2)[0] tr_pool = np.where(tpl_i != 2)[0].tolist() tr = rnd.sample(tr_pool, len(tr_pool))[:len(tr_pool)] # same training size, but test pages come from templates that were in training (random held-out pages) idx = list(range(len(rows))) rnd.shuffle(idx) te2, tr2 = idx[:len(te_all)], idx[len(te_all):][:len(tr_pool)] pr2 = fit_predict("tfidf_lr", [docs[i] for i in tr2], y[tr2], [docs[i] for i in te2]).argmax(1) res["unseen_template"]["seen_same_size"] = {"tfidf_lr_acc": pct(int((pr2 == y[te2]).sum()), len(te2)), "n_test": len(te2), "n_train": len(tr2)} # packet check: 10-page packets, independence assumption vs what the predictions do res["packet"] = {} pr = P["tfidf_lr"].argmax(1) okp = (pr == y) p_all = float(okp.mean()) rr = random.Random(a.seed + 13) N, L = 20000, 10 mixed = sum(all(okp[rr.randrange(len(okp))] for _ in range(L)) for _ in range(N)) / N by_t = {t: np.where(tier == t)[0].tolist() for t in sorted(set(tier))} same = 0 for _ in range(N): pool_ = by_t[rr.choice(sorted(by_t))] same += all(okp[rr.choice(pool_)] for _ in range(L)) res["packet"] = {"page_acc": round(100 * p_all, 1), "len": L, "independent_formula": round(100 * p_all ** L, 1), "mixed_tier_packets": round(100 * mixed, 1), "same_tier_packets": round(100 * same / N, 1), "draws": N} per_tier_p = {t: float(okp[tier == t].mean()) for t in by_t} res["packet"]["same_tier_independent_formula"] = round(100 * sum(v ** L for v in per_tier_p.values()) / len(per_tier_p), 1) # pages where OCR found almost nothing: a cheap review trigger that needs no classifier at all nw = np.array([ocr["pages"][i]["n_words"] for i in ids]) res["few_words"] = {"min_words": 10, "n_pages": int((nw < 10).sum())} for k in kinds: pr_ = P[k].argmax(1) err_all = int((pr_ != y).sum()) err_few = int(((pr_ != y) & (nw < 10)).sum()) res["few_words"][k] = {"errors_total": err_all, "errors_on_few_word_pages": err_few, "acc_on_few_word_pages": pct(int(((pr_ == y) & (nw < 10)).sum()), int((nw < 10).sum())), "errors_left_after_review_of_them": err_all - err_few} # timing secs = np.array([ocr["pages"][i]["seconds"] for i in ids]) res["ocr_seconds_per_page"] = {"mean": round(float(secs.mean()), 2), "by_tier": {t: round(float(secs[tier == t].mean()), 2) for t in sorted(set(tier))}} res["ocr_mean_conf"] = {t: round(float(np.mean([ocr["pages"][i]["mean_conf"] for i, tt in zip(ids, tier) if tt == t])), 1) for t in sorted(set(tier))} json.dump(res, open(d / "results.json", "w"), indent=1) with open(d / "pages.csv", "w", newline="") as fh: w = csv.writer(fh) head = ["id", "label", "template", "tier", "hard", "ocr_words", "ocr_mean_conf", "ocr_seconds"] for k in P: head += [f"{k}_pred", f"{k}_conf", f"{k}_ok"] w.writerow(head) for i, r in enumerate(rows): o = ocr["pages"][r["id"]] line = [r["id"], r["label"], r["template"], r["tier"], r["hard"], o["n_words"], o["mean_conf"], o["seconds"]] for k in P: pi = int(P[k][i].argmax()) line += [CLASSES[pi], round(float(P[k][i].max()), 3), int(pi == y[i])] w.writerow(line) for k in P: print(k, res["overall"][k]) def main(): ap = argparse.ArgumentParser() sub = ap.add_subparsers(dest="cmd", required=True) g = sub.add_parser("generate"); g.add_argument("dir"); g.add_argument("--seed", type=int, default=2026); g.add_argument("--per-cell", type=int, default=15) o = sub.add_parser("ocr"); o.add_argument("dir"); o.add_argument("--procs", type=int, default=6) s = sub.add_parser("score"); s.add_argument("dir"); s.add_argument("--seed", type=int, default=2026); s.add_argument("--external") a = ap.parse_args() {"generate": generate, "ocr": run_ocr, "score": score}[a.cmd](a) if __name__ == "__main__": main()
```

## Frequently Asked Questions

### How many pages do you need to test document classification accuracy?

Use 200 to 500 labeled pages with at least 30 per class and about one page in eight from outside your scope. At 20 pages a measured 95% could really be anywhere from 76% to 99%. At 480 pages the same result has a 95% interval of 92.7% to 96.6%. Per class results from 60 pages are rough, so test any class you care about most with more.

### What is the most useful metric for document classification?

The error rate among pages accepted without review at your chosen confidence threshold. In our test a logistic regression baseline was right on 95.0% of 480 pages overall, but at a confidence of 0.50 it accepted 441 pages with none wrong (95% upper bound 0.9%) and sent 8.1% to review. Overall accuracy cannot tell you that.

### Is OCR or the classifier responsible for most classification errors?

In our test, OCR. On the text the generator printed, both trained baselines were right on all 480 pages. On Tesseract's text they were right on 95.0% and 93.5%. 21 of the logistic regression's 24 errors were pages where OCR found fewer than 10 words. These are generated pages and baselines we wrote, so check the split on your own scans.

### How many labeled examples per class does a classifier need?

In our test, 10 per class reached 92.4% accuracy and 40 reached 95.0%, but the worst class was at 74.4% recall with 10 and 82.2% with 40. Label 10 to 20 per class to start, read the confusion matrix, and add examples where a class fails. Results are for a simple TF-IDF logistic regression on generated pages.

### Can you trust a classifier's confidence score for routing to review?

Only after you measure it. In our test the logistic regression confidence ordered pages well, with no errors among accepted pages from 0.50 up. The keyword rule score did not: at 0.80 the error rate among accepted pages was 12.2%, higher than with no threshold. Run a threshold sweep on labeled pages before routing on any vendor or in house score.

### How do you test a vendor's document classification on your own pages?

Label your pages, ask the vendor for a class and a confidence for every page, and score the answers with the same tables: overall accuracy, per class precision and recall, confusion matrix, accuracy by scan quality and the error rate among accepted pages at each threshold. The script in this guide takes a CSV of id, label and confidence through its external option.


---

**Source URL (cite this):** https://docsapi.co/resources/blogs/document-classification-accuracy-test
**Author profile:** https://docsapi.co/author/nupura-ughade
**Published by:** DocsAPI (https://docsapi.co)
