Classifying Documents Without Labelled Training Data
Most document classifiers start with a labelled dataset. Many real projects start with a folder of PDFs and a request to sort them. A construction bundle is typical: specifications, drawing registers, bills of quantities, contracts and programmes arrive together, untagged. Waiting for labels can block the whole pipeline.
A classifier that needs no labelled training data is possible, but it is more a design problem than a model problem. In earlier work on a document-intelligence platform for construction, I built a zero-shot document classifier that needs no labelled data. This post is general technique, not a description of that system: the label set, the scoring options, abstention, evaluation, and the point where training becomes worthwhile.
Version notice. Written and run with Python 3.13, model2vec 0.11.0, numpy 2.5.5 and scikit-learn 1.9.1 (installed, but only its documentation is cited here). The model is minishlab/potion-base-8M. All figures below come from synthetic snippets (a 22-snippet toy set and a 120-snippet generated set), not from real documents.
In short
- Zero-label classification is mostly label design: mutually exclusive classes, a catch-all "other", and a short description for each.
- Embedding similarity needs one small local model and no API calls; NLI zero-shot and LLMs cost more per document, so use them only where the cheap pass is unsure. On a synthetic set, three examples per class scored 0.91 against 0.80 for descriptions alone, within noise.
- Abstaining on low-margin cases trades coverage for precision; the unsure pile goes to a human. Description precision fell short of both dev targets on test, so choose thresholds on a dev split, check them on a separate test split, and expect shrinkage.
- Hand-label a small stratified set, report per-class precision and recall, and graduate to a trained model only once weak labels and the evaluation set justify it.
Design the label set first
With no training data, the labels are the model. A vague label set cannot be rescued by a better encoder. Four rules help.
- Make labels mutually exclusive. If a document can be both a "specification" and a "contract appendix", decide which one wins and write that down. Otherwise one document is correct under two labels and the metrics are meaningless.
- Add a catch-all "other". Real bundles contain cover letters, minutes and leaflets. Without it, every stray document is forced into a wrong class.
- Write a description per label. A single word such as "schedule" is ambiguous (a programme of works or a schedule of rates); a sentence of what the document contains removes that, and every method below uses it.
- Keep the set small at first. Split a class later if the evaluation shows it hides two kinds of document.
Describe what appears on the page: "priced items with unit, quantity, rate and amount" beats "documents about costs".
Four ways to score a document
Once labels have descriptions, there are four common ways to pick one. They differ in cost, in how they fail, and in what you must supply.
| Method | How it scores | Cost per document | Main weakness |
|---|---|---|---|
| Embedding similarity | Cosine similarity to each label description, or to a prototype (mean embedding of a few example documents) | One encode of the document; label vectors are computed once | Similar-sounding classes blur; scores are not probabilities |
| NLI zero-shot | An entailment model judges a hypothesis built from each label | One model pass per document and label pair | Cost grows with the label count; the hypothesis wording matters |
| LLM with constrained output | A prompt with the label descriptions and the document start; reply restricted to the label set | One generation call, billed by tokens | Slowest and most expensive; wording and model version change answers |
| Cascade | Embedding pass first; LLM only on low-margin cases | Cheap for most documents, expensive for a few | Two systems to evaluate and maintain |
Embedding similarity builds on the idea that a sentence encoder maps text to vectors that can be compared with cosine similarity; Sentence-BERT made this practical. A prototype can replace the description once you have a few trusted examples, because it reflects your documents' vocabulary.
NLI means natural language inference: deciding whether a premise entails a hypothesis. Yin, Hay and Roth (2019) framed zero-shot text classification as an entailment task. The Hugging Face zero-shot-classification pipeline implements it: per its documentation, "each combination will be posed as a premise/hypothesis pair and passed to the pretrained model". The default hypothesis template is "This example is {}." With multi_label=False the scores are softmaxed across labels and sum to 1. The cost follows: documents times labels model passes, each on a transformer far larger than a static embedding table.
For LLM classification, constrain the output. Provider structured-output features restrict the reply to a JSON schema; Anthropic's documentation describes "constrained decoding" with enum support for strings. Constrained decoding keeps the reply inside the schema, but it does not make the label correct. The same page lists cases where the output may not match the schema: a refusal, a reply cut off at max_tokens, and enum values that differ from the schema only in capitalisation.
Embedding similarity with abstention
The runnable example below is a toy. The 22 snippets are synthetic text written for this post, to look like the first lines of six document types, with three deliberately awkward cases. It uses Model2Vec, a technique that turns a sentence transformer into a small static embedding model, so no torch is needed. The model potion-base-8M is, per its model card, distilled from bge-base-en-v1.5. Per the Model2Vec README, the idea is to "forward pass a vocabulary through a sentence transformer model", "creating static embeddings for the indiviudal tokens" (sic). Each token therefore has one fixed vector and context is not modelled, which suits sorting by vocabulary and hides anything subtler. The label descriptions are embedded once, each snippet is compared to them, and the classifier returns "unsure" when the best similarity is low or the gap to the second best is small.
"""Toy zero-label classifier: embedding similarity to label descriptions, with abstention.
The snippets are synthetic and invented for this post. The scores are a toy example,
not a benchmark.
"""
from __future__ import annotations
from dataclasses import dataclass
import numpy as np
from model2vec import StaticModel
LABELS: dict[str, str] = {
"specification": "Technical specification: clauses on materials, workmanship, "
"standards and testing requirements for the works.",
"drawing_list": "Drawing register: a list of drawing numbers, titles, "
"revisions and issue dates.",
"bill_of_quantities": "Bill of quantities: priced items with unit, quantity, "
"rate and amount, with section totals.",
"contract": "Contract conditions: parties, obligations, payment terms, "
"liability, termination and dispute resolution.",
"schedule": "Programme of works: activities, durations, start and finish "
"dates, milestones and critical path.",
"other": "Other document: correspondence, meeting minutes, cover letters "
"or anything that is none of the above.",
}
# (text, true label). Written by hand; the 'hard' ones are deliberately awkward.
DATA: list[tuple[str, str]] = [
("Section 03 30 00 Cast-in-place concrete. Part 2 Products: cement shall comply with the "
"relevant standard. Aggregates shall be clean and free from deleterious matter.", "specification"),
("Clause 5.2 Workmanship. All brickwork shall be laid in stretcher bond. Mortar mix and "
"curing shall follow the approved method statement and testing requirements.", "specification"),
("Technical specification for mechanical services: pipework materials, pressure testing "
"and commissioning to the stated standards.", "specification"),
("Structural steelwork: fabrication tolerances, bolt grades, weld inspection and "
"protective coatings are specified in this section.", "specification"),
("Drawing register. DWG-A-101 Ground floor plan Rev C 12 May. DWG-A-102 First floor plan "
"Rev B 12 May. DWG-S-201 Foundation layout Rev A.", "drawing_list"),
("Document list: drawing number, title, revision, date issued. A-301 Elevations Rev D. "
"A-302 Sections Rev D. M-401 Ventilation layout Rev B.", "drawing_list"),
("Transmittal of drawings issued for tender: E-501 Lighting plan Rev A, E-502 Power plan "
"Rev A, P-601 Drainage layout Rev C.", "drawing_list"),
("Bill of quantities. Item 2.1 Excavate trench, m3, qty 120, rate 18.50, amount 2,220.00. "
"Item 2.2 Backfill, m3, qty 95, rate 9.00, amount 855.00. Section total 3,075.00.", "bill_of_quantities"),
("Section 4 Masonry. 4.1 Facing brick wall, m2, 340, 62.00, 21,080.00. 4.2 Blockwork "
"partition, m2, 210, 38.00, 7,980.00. Carried to summary.", "bill_of_quantities"),
("Pricing schedule: item, description, unit, quantity, unit rate, total. Preliminaries "
"lump sum 45,000.00. Collection page total 112,430.00.", "bill_of_quantities"),
("Conditions of contract. This Agreement is made between the Employer and the Contractor. "
"The Contractor shall execute the Works. Payment terms: 30 days from valid invoice.", "contract"),
("Clause 14 Termination. Either party may terminate on written notice for material breach. "
"Liability is limited as set out in clause 18. Disputes go to adjudication.", "contract"),
("Form of agreement and appendix: contract sum, retention, liquidated damages for delay, "
"insurance obligations and dispute resolution.", "contract"),
("Construction programme. Activity: Piling, duration 15 days, start 03 Mar, finish 21 Mar. "
"Milestone: frame complete. Critical path shown in red.", "schedule"),
("Master schedule Gantt: site setup, groundworks, superstructure, fit-out, handover. "
"Start and finish dates, float, and key milestones.", "schedule"),
("Four-week look-ahead: roofing starts Monday, façade scaffold removed Thursday, "
"commissioning window opens in week 4.", "schedule"),
("Dear Sir, further to our meeting on site yesterday, please find attached the revised "
"access arrangements. Kind regards.", "other"),
("Minutes of progress meeting 7. Present: client, architect, contractor. Action: contractor "
"to confirm crane delivery.", "other"),
("Health and safety induction leaflet for visitors to the site, including emergency "
"assembly points and contact numbers.", "other"),
# Hard cases
("Employer's requirements: the Contractor shall supply materials to the specification and "
"complete the works by the dates in the programme.", "contract"),
("Schedule of rates: unit, rate and a note that quantities are provisional.", "bill_of_quantities"),
("Appendix C: list of approved materials and testing standards referred to in the contract.", "specification"),
]
@dataclass(frozen=True)
class Prediction:
label: str # predicted label, or "unsure"
top: float # cosine similarity to the best label
margin: float # best minus second best
def l2norm(x: np.ndarray) -> np.ndarray:
return x / np.linalg.norm(x, axis=-1, keepdims=True)
def classify(texts, model, min_top=0.30, min_margin=0.05) -> list[Prediction]:
names = list(LABELS)
label_vecs = l2norm(model.encode([LABELS[n] for n in names]))
sims = l2norm(model.encode(list(texts))) @ label_vecs.T
out = []
for row in sims:
order = np.argsort(row)[::-1]
top, margin = float(row[order[0]]), float(row[order[0]] - row[order[1]])
label = names[order[0]] if top >= min_top and margin >= min_margin else "unsure"
out.append(Prediction(label, top, margin))
return out
def report(y_true, y_pred, labels) -> None:
cols = labels + ["unsure"]
idx = {l: i for i, l in enumerate(cols)}
cm = np.zeros((len(labels), len(cols)), dtype=int)
for t, p in zip(y_true, y_pred):
cm[idx[t], idx[p]] += 1
print("Confusion matrix (rows = true, columns = predicted)")
print(" " * 20 + " ".join(f"{c[:6]:>6}" for c in cols))
for i, l in enumerate(labels):
print(f"{l:<20}" + " ".join(f"{v:>6}" for v in cm[i]))
print(f"\n{'class':<20}{'prec':>6}{'recall':>8}{'n':>4}")
for i, l in enumerate(labels):
tp, predicted, actual = cm[i, i], cm[:, i].sum(), cm[i].sum()
prec = f"{tp / predicted:.2f}" if predicted else " n/a"
print(f"{l:<20}{prec:>6}{tp / actual:>8.2f}{actual:>4}")
answered = [(t, p) for t, p in zip(y_true, y_pred) if p != "unsure"]
acc = sum(t == p for t, p in answered) / len(answered)
print(f"\ncoverage {len(answered)}/{len(y_true)}, accuracy on answered {acc:.2f}")
if __name__ == "__main__":
model = StaticModel.from_pretrained("minishlab/potion-base-8M")
texts, truth = zip(*DATA)
for min_top, min_margin in [(0.0, 0.0), (0.30, 0.05)]:
print(f"\n=== min_top={min_top}, min_margin={min_margin} ===")
preds = classify(texts, model, min_top, min_margin)
report(list(truth), [p.label for p in preds], list(LABELS))
Output of the second configuration:
=== min_top=0.3, min_margin=0.05 ===
Confusion matrix (rows = true, columns = predicted)
specif drawin bill_o contra schedu other unsure
specification 5 0 0 0 0 0 0
drawing_list 0 3 0 0 0 0 0
bill_of_quantities 0 0 3 0 0 0 1
contract 1 0 0 3 0 0 0
schedule 0 0 0 0 2 0 1
other 0 0 0 0 0 1 2
class prec recall n
specification 0.83 1.00 5
drawing_list 1.00 1.00 3
bill_of_quantities 1.00 0.75 4
contract 1.00 0.75 4
schedule 1.00 0.67 3
other 1.00 0.33 3
coverage 18/22, accuracy on answered 0.94
Without abstention, the same code answered all 22 snippets at accuracy 0.86 (19 of 22); the errors were a contract read as a specification and two "other" documents forced into "bill_of_quantities" and "contract". With the two thresholds it answered 18 of 22 at 0.94 (17 of 18) and sent four to the unsure pile. The thresholds were picked by hand on this same set, which flatters the result. The next section does it properly, on a larger set with a dev/test split.
The weak class is "other": recall 0.33, because a catch-all has no characteristic content to match. "Unsure" is a safer home for it than a wrong class, but abstention costs coverage.
Measured: scoring choice and thresholds
Two questions the toy set cannot answer: do a few example documents beat label descriptions, and what does a threshold chosen on one split do on another? A seeded generator produced 120 synthetic snippets, 20 per class, from slot-filled templates; 30 per cent carry one extra sentence from a confusable class. A stratified split gave 60 dev and 60 test snippets. A prototype is the mean embedding of three dev snippets per class, removed from dev when thresholds are chosen (otherwise they score themselves), leaving 42. Thresholds are the grid pair with the highest dev coverage whose dev precision reaches a target.
The code is sweep.py (generator folded, then the rest) and report.py, beside demo.py from above.
sweep.py, part 1: the synthetic generator and split
"""Synthetic 120-snippet set, dev/test split, threshold sweep, description vs prototype scoring.
All text is generated from templates (seeded). Numbers are a toy, not a benchmark.
"""
from __future__ import annotations
import random
import numpy as np
from model2vec import StaticModel
from demo import LABELS
NAMES = list(LABELS)
ELEM = ["concrete", "brickwork", "steelwork", "drainage", "roofing", "glazing", "joinery", "piling"]
STD = ["BS 8500", "BS 5950", "EN 1992", "BS 6399", "EN 10025", "BS 8000"]
PARTY = ["the Employer", "the Contractor", "the Client", "the Sub-Contractor"]
MON = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct"]
SHEET = ["A", "S", "M", "E", "P"]
def r(rng, xs): return rng.choice(xs)
def d(rng): return f"{rng.randint(1, 28):02d} {r(rng, MON)}"
def spec(g):
return r(g, [
lambda: f"Section {g.randint(3, 9):02d} {g.randint(10, 60)} 00 {r(g, ELEM).capitalize()}. Materials shall comply with {r(g, STD)} and be tested before use.",
lambda: f"Clause {g.randint(1, 9)}.{g.randint(1, 9)} Workmanship. All {r(g, ELEM)} shall be executed to {r(g, STD)}; tolerances and inspection are as stated below.",
lambda: f"Specification for {r(g, ELEM)}: product requirements, execution, testing and acceptance criteria to {r(g, STD)}.",
lambda: f"Part {g.randint(1, 3)} Execution. Surfaces shall be prepared and {r(g, ELEM)} installed in accordance with the manufacturer's instructions and {r(g, STD)}.",
])()
def drawing(g):
s = lambda: f"{r(g, SHEET)}-{g.randint(1, 6)}{g.randint(0, 9)}{g.randint(0, 9)} {r(g, ['Ground floor plan', 'Sections', 'Elevations', 'Foundation layout', 'Drainage layout', 'Roof plan'])} Rev {r(g, 'ABCDE')}"
return r(g, [
lambda: f"Drawing register. {s()} {d(g)}. {s()} {d(g)}. {s()}.",
lambda: f"Document list: drawing number, title, revision, date issued. {s()}. {s()}. {s()}.",
lambda: f"Transmittal of drawings issued for {r(g, ['tender', 'construction', 'comment'])}: {s()}, {s()}, {s()}.",
lambda: f"Drawing issue sheet {g.randint(1, 20)}: {s()}; {s()}; status S{g.randint(1, 4)}.",
])()
def boq(g):
it = lambda: f"{g.randint(1, 9)}.{g.randint(1, 9)} {r(g, ['Excavate trench', 'Backfill', 'Facing brick wall', 'Blockwork partition', 'Concrete slab', 'Screed'])}, {r(g, ['m2', 'm3', 'm'])}, {g.randint(20, 400)}, {g.randint(5, 90)}.{g.randint(0, 99):02d}, {g.randint(1, 30)},{g.randint(100, 999)}.00."
return r(g, [
lambda: f"Bill of quantities. Item {it()} Item {it()} Section total {g.randint(2, 90)},{g.randint(100, 999)}.00.",
lambda: f"Section {g.randint(1, 9)} {r(g, ELEM).capitalize()}. {it()} {it()} Carried to summary.",
lambda: f"Pricing schedule: item, description, unit, quantity, unit rate, total. Preliminaries lump sum {g.randint(10, 90)},000.00. Collection page total {g.randint(50, 300)},{g.randint(100, 999)}.00.",
lambda: f"Summary of bills: Bill {g.randint(1, 8)} {r(g, ELEM)} {g.randint(10, 200)},{g.randint(100, 999)}.00. Contingency {g.randint(2, 9)},000.00. Tender total.",
])()
def contract(g):
return r(g, [
lambda: f"Conditions of contract. This Agreement is made between {r(g, PARTY)} and {r(g, PARTY)}. Payment terms: {r(g, [14, 28, 30, 45])} days from valid invoice.",
lambda: f"Clause {g.randint(10, 30)} Termination. Either party may terminate on written notice for material breach. Liability is limited as set out in clause {g.randint(10, 30)}.",
lambda: f"Form of agreement: contract sum, retention of {g.randint(3, 5)} per cent, liquidated damages for delay, insurance obligations and dispute resolution by {r(g, ['adjudication', 'arbitration'])}.",
lambda: f"Particulars of the contract: the Contractor shall indemnify the Employer against claims arising from the works; defects period {g.randint(6, 24)} months.",
])()
def schedule(g):
return r(g, [
lambda: f"Construction programme. Activity: {r(g, ELEM).capitalize()}, duration {g.randint(5, 60)} days, start {d(g)}, finish {d(g)}. Milestone: {r(g, ['frame complete', 'weathertight', 'handover'])}.",
lambda: f"Master schedule Gantt: site setup, groundworks, superstructure, fit-out, handover. Start and finish dates, float and critical path.",
lambda: f"Look-ahead: {r(g, ELEM)} starts {r(g, ['Monday', 'Tuesday', 'Wednesday'])}, scaffold removed {r(g, ['Thursday', 'Friday'])}, commissioning window opens in week {g.randint(2, 8)}.",
lambda: f"Revised programme rev {g.randint(1, 9)}: {r(g, ELEM)} {g.randint(5, 40)} days, float {g.randint(0, 10)} days, completion {d(g)}.",
])()
def other(g):
return r(g, [
lambda: f"Dear Sir, further to our meeting on {r(g, ['site', 'Teams'])} {r(g, ['yesterday', 'on Tuesday'])}, please find attached the revised access arrangements. Kind regards.",
lambda: f"Minutes of progress meeting {g.randint(1, 30)}. Present: client, architect, contractor. Action: contractor to confirm {r(g, ['crane delivery', 'access dates', 'sample approval'])}.",
lambda: f"Health and safety induction leaflet for visitors, including emergency assembly points and contact numbers.",
lambda: f"Invitation to the {r(g, ['topping-out', 'site open day', 'handover'])} event on {d(g)}. Parking is available on the north side of the site.",
lambda: f"Request for information {g.randint(1, 99)}: please confirm the {r(g, ELEM)} detail shown on the attached sketch.",
])()
GEN = {"specification": spec, "drawing_list": drawing, "bill_of_quantities": boq,
"contract": contract, "schedule": schedule, "other": other}
CONFUSE = {"specification": "contract", "contract": "specification", "bill_of_quantities": "schedule",
"schedule": "bill_of_quantities", "drawing_list": "specification", "other": "contract"}
def make(n_per_class=20, seed=7, mix=0.3):
g = random.Random(seed)
rows = []
for lab in NAMES:
for _ in range(n_per_class):
t = GEN[lab](g)
if g.random() < mix: # contaminate with a sentence from a confusable class
t = t + " " + GEN[CONFUSE[lab]](g).split(". ")[0] + "."
rows.append((t.replace("..", "."), lab))
return rows
def split(rows, seed=11):
g = random.Random(seed)
dev, test = [], []
for lab in NAMES:
xs = [x for x in rows if x[1] == lab]; g.shuffle(xs)
h = len(xs) // 2
dev += xs[:h]; test += xs[h:]
return dev, test
def l2(x): return x / np.linalg.norm(x, axis=-1, keepdims=True)
def sims_desc(model, texts):
return l2(model.encode(list(texts))) @ l2(model.encode([LABELS[n] for n in NAMES])).T
def sims_proto(model, texts, shots):
P = []
for n in NAMES:
P.append(l2(model.encode([t for t, y in shots if y == n]).mean(0)))
return l2(model.encode(list(texts))) @ np.stack(P).T
def top_margin(S):
o = np.sort(S, axis=1)[:, ::-1]
return S.argmax(1), o[:, 0], o[:, 0] - o[:, 1]
def curve(S, y, grid_top, grid_mar):
pred, top, mar = top_margin(S)
ok = pred == y
out = []
for a in grid_top:
for b in grid_mar:
m = (top >= a) & (mar >= b)
out.append((a, b, m.mean(), ok[m].mean() if m.any() else float("nan"), int(m.sum())))
return out
def pick(cur, target):
c = [x for x in cur if x[4] >= 5 and x[3] >= target]
return max(c, key=lambda x: (x[2], x[3])) if c else None
def apply(S, y, a, b):
pred, top, mar = top_margin(S)
m = (top >= a) & (mar >= b)
return pred, m
def run():
model = StaticModel.from_pretrained("minishlab/potion-base-8M")
rows = make(); dev, test = split(rows)
yd_all = np.array([NAMES.index(l) for _, l in dev]); yt = np.array([NAMES.index(l) for _, l in test])
td_all = [t for t, _ in dev]; tt = [t for t, _ in test]
grid_top = np.round(np.arange(0.0, 0.81, 0.02), 2); grid_mar = np.round(np.arange(0.0, 0.31, 0.01), 2)
print("rows", len(rows), "dev", len(dev), "test", len(test))
print("test class counts", np.bincount(yt))
def shots(seed, k):
g = random.Random(seed); s = []
for n in NAMES:
s += g.sample([x for x in dev if x[1] == n], k)
return s
S_desc_t = sims_desc(model, tt); S_desc_d = sims_desc(model, td_all)
print("\nFull-coverage accuracy on test (no abstention)")
print(f"description: {(S_desc_t.argmax(1) == yt).mean():.3f}")
for k in (1, 3, 5):
a = [(sims_proto(model, tt, shots(s, k)).argmax(1) == yt).mean() for s in range(20)]
print(f"prototype k={k} (20 draws of shots from dev): mean {np.mean(a):.3f} sd {np.std(a):.3f} min {min(a):.3f} max {max(a):.3f}")
out = {}
for target in (0.90, 0.95):
print(f"\n== operating point: max dev coverage with dev precision >= {target}; reported on test")
for name in ("description", "prototype k=3", "description + prototype k=3"):
covs, precs, ns, picked = [], [], [], 0
draws = [0] if name == "description" else range(20)
for s in draws:
sh = shots(s, 3)
keep = [i for i, x in enumerate(dev) if x not in sh] # shots are not held out otherwise
td = [td_all[i] for i in keep]; yd = yd_all[keep]
if name == "description":
Sd, St = S_desc_d[keep], S_desc_t
elif name == "prototype k=3":
Sd, St = sims_proto(model, td, sh), sims_proto(model, tt, sh)
else:
Sd = (sims_desc(model, td) + sims_proto(model, td, sh)) / 2
St = (S_desc_t + sims_proto(model, tt, sh)) / 2
p = pick(curve(Sd, yd, grid_top, grid_mar), target)
if p is None: continue
picked += 1
pred, m = apply(St, yt, p[0], p[1])
covs.append(m.mean()); precs.append((pred[m] == yt[m]).mean() if m.any() else np.nan); ns.append(len(yd))
print(f"{name:28s} dev n={ns[0]:2d} test coverage {np.mean(covs):.2f} (sd {np.std(covs):.2f}) test precision {np.nanmean(precs):.2f} (sd {np.nanstd(precs):.2f}) [{picked} draws]")
if __name__ == "__main__":
run()
report.py: per-class numbers and curve data
"""Per-class test numbers at the dev-chosen operating point, and the coverage/precision curves."""
import json, random
import numpy as np
from model2vec import StaticModel
from sweep import *
model = StaticModel.from_pretrained("minishlab/potion-base-8M")
rows = make(); dev, test = split(rows)
yd_all = np.array([NAMES.index(l) for _, l in dev]); yt = np.array([NAMES.index(l) for _, l in test])
td_all = [t for t, _ in dev]; tt = [t for t, _ in test]
grid_top = np.round(np.arange(0.0, 0.81, 0.02), 2); grid_mar = np.round(np.arange(0.0, 0.31, 0.01), 2)
def shots(seed, k):
g = random.Random(seed); s = []
for n in NAMES: s += g.sample([x for x in dev if x[1] == n], k)
return s
sh0 = shots(0, 3)
keep = [i for i, x in enumerate(dev) if x not in sh0]
td = [td_all[i] for i in keep]; yd = yd_all[keep]
sets = {
"description": (sims_desc(model, td), sims_desc(model, tt)),
"prototype k=3": (sims_proto(model, td, sh0), sims_proto(model, tt, sh0)),
}
print("Per-class on test, shots draw 0, target dev precision 0.95")
res = {}
for name, (Sd, St) in sets.items():
a, b, covd, precd, nd = pick(curve(Sd, yd, grid_top, grid_mar), 0.95)
pred, m = apply(St, yt, a, b)
print(f"\n{name}: top>={a:.2f} margin>={b:.2f}; test coverage {m.sum()}/{len(yt)}, precision {(pred[m]==yt[m]).sum()}/{m.sum()}")
for i, n in enumerate(NAMES):
ans = m & (pred == i); tp = (ans & (yt == i)).sum()
print(f" {n:20s} answered {ans.sum():2d} correct {tp:2d} precision {tp/ans.sum() if ans.sum() else float('nan'):.2f} recall {tp/(yt==i).sum():.2f} abstained {((yt==i)&~m).sum()}")
# curves: margin-only sweep (top=0), mean over 20 shot draws for prototype methods
marg = np.round(np.arange(0, 0.201, 0.005), 3)
curves = {}
def sweep_curve(St):
pred, top, mar = top_margin(St); ok = pred == yt
return [((mar >= t).mean(), ok[mar >= t].mean() if (mar >= t).any() else np.nan) for t in marg]
curves["description"] = sweep_curve(sims_desc(model, tt))
cs = [sweep_curve(sims_proto(model, tt, shots(s, 3))) for s in range(20)]
curves["prototype k=3"] = [(float(np.mean([c[i][0] for c in cs])), float(np.nanmean([c[i][1] for c in cs]))) for i in range(len(marg))]
json.dump({k: [[round(float(x), 4), round(float(y), 4)] for x, y in v] for k, v in curves.items()}, open("curves.json", "w"))
Run python sweep.py, then python report.py. Output of sweep.py:
rows 120 dev 60 test 60
test class counts [10 10 10 10 10 10]
Full-coverage accuracy on test (no abstention)
description: 0.800
prototype k=1 (20 draws of shots from dev): mean 0.773 sd 0.071 min 0.633 max 0.867
prototype k=3 (20 draws of shots from dev): mean 0.909 sd 0.042 min 0.833 max 0.967
prototype k=5 (20 draws of shots from dev): mean 0.946 sd 0.035 min 0.883 max 0.983
== operating point: max dev coverage with dev precision >= 0.9; reported on test
description dev n=42 test coverage 0.85 (sd 0.00) test precision 0.86 (sd 0.00) [1 draws]
prototype k=3 dev n=42 test coverage 0.95 (sd 0.05) test precision 0.94 (sd 0.03) [20 draws]
description + prototype k=3 dev n=42 test coverage 0.96 (sd 0.05) test precision 0.91 (sd 0.03) [20 draws]
== operating point: max dev coverage with dev precision >= 0.95; reported on test
description dev n=42 test coverage 0.70 (sd 0.00) test precision 0.93 (sd 0.00) [1 draws]
prototype k=3 dev n=42 test coverage 0.82 (sd 0.15) test precision 0.97 (sd 0.03) [20 draws]
description + prototype k=3 dev n=42 test coverage 0.85 (sd 0.10) test precision 0.96 (sd 0.04) [20 draws]
Table 1. Test accuracy with no abstention; prototype rows are means over 20 draws of the shots from dev. Wilson intervals treat each mean as one 60-document result; sd and range reflect the shot draw only.
| Scoring (no abstention) | Test accuracy | Spread |
|---|---|---|
| Label descriptions | 0.80 (48 of 60) | 95% Wilson interval 0.68 to 0.88 |
| Prototype, 1 shot per class | 0.77 | sd 0.07, range 0.63 to 0.87; Wilson 0.65 to 0.86 |
| Prototype, 3 shots per class | 0.91 | sd 0.04, range 0.83 to 0.97; Wilson 0.81 to 0.96 |
| Prototype, 5 shots per class | 0.95 | sd 0.04, range 0.88 to 0.98; Wilson 0.86 to 0.98 |
One shot is no better than the description. Three and five shots score higher, but the intervals overlap, so 0.91 against 0.95 or against 0.80 is within noise on 60 documents.
Table 2. The dev-chosen operating point scored on test (brackets: sd across 20 draws).
| Scoring | Target 0.90: test coverage | Target 0.90: test precision | Target 0.95: test coverage | Target 0.95: test precision |
|---|---|---|---|---|
| Description | 0.85 | 0.86 | 0.70 | 0.93 |
| Prototype, k = 3 | 0.95 (0.05) | 0.94 (0.03) | 0.82 (0.15) | 0.97 (0.03) |
| Description + prototype | 0.96 (0.05) | 0.91 (0.03) | 0.85 (0.10) | 0.96 (0.04) |
The description row falls below both dev targets: 0.90 and 0.95 gave 0.86 (44 of 51, Wilson interval 0.74 to 0.93) and 0.93 (39 of 42, 0.81 to 0.98) on test. Both intervals contain the targets, so this is consistent with shrinkage, not proof. The prototype rows met their targets, but coverage at target 0.95 has a standard deviation of 0.15 across draws, because thresholds depend on which three documents were the shots. Pick shots on purpose; use as large a dev set as labelling allows.
Table 3. Per-class test numbers at the target-0.95 point, for the description and the first shot draw (report.py prints them). An abstained document counts against recall, not precision.
| Class (n = 10) | Description: precision | Description: recall | Prototype: precision | Prototype: recall |
|---|---|---|---|---|
| specification | 1.00 (8/8) | 0.80 | 1.00 (9/9) | 0.90 |
| drawing_list | 0.88 (7/8) | 0.70 | 1.00 (9/9) | 0.90 |
| bill_of_quantities | 0.89 (8/9) | 0.80 | 0.83 (10/12) | 1.00 |
| contract | 0.86 (6/7) | 0.60 | 1.00 (10/10) | 1.00 |
| schedule | 1.00 (9/9) | 0.90 | 1.00 (5/5) | 0.50 |
| other | 1.00 (1/1) | 0.10 | 1.00 (9/9) | 0.90 |
The catch-all differs most. A description of "none of the above" has nothing to match (one of ten "other" snippets answered); the prototype absorbed the examples' vocabulary (recall 0.90). That flatters it: the generator has five "other" templates and real catch-alls are far more varied. The prototype pays elsewhere: schedule recall is 0.50. Compare methods at equal coverage on Figure 1, not by totals at different thresholds.
Not shown: the data are template-built and easy, classes are balanced, and the encoder is static (its card does not state languages). The ordering of methods is a hypothesis to retest; checking thresholds on held-out data is the part that transfers.
Decision guide
| Situation | Start with | Evidence |
|---|---|---|
| No examples, clear descriptions | Description scoring with a margin threshold; send abstentions to review | Measured above: weakest on the catch-all |
| 3 to 5 trusted examples per class | Prototypes, optionally averaged with the descriptions | Measured above: 0.91 to 0.95 against 0.80 |
| Classes differ in meaning, not vocabulary | NLI or an LLM on the unsure cases only | Not run; from documentation |
Use the structure, not the whole document
A bill of quantities of three hundred pages is still one on page one. Whole-text classification costs more, hits input limits and dilutes the signal. Cheaper inputs usually carry the label:
- the title page or the first page;
- the top-level headings (a table of contents lists the main sections in one place);
- the column headers of the first table;
- the file name and folder path, which are free.
Truncate to a fixed budget, such as the first 1,000 to 1,500 characters. A common failure is an empty first page (a scanned cover with no text layer): fall back to the next pages or route to review, and log which text each prediction used.
A cascade: cheap first, LLM for the unsure
The cascade spends the expensive call where it can change the answer: in the toy run, four of 22 documents would reach the LLM. The code builds the prompt from the same label descriptions, parses the reply and rejects any label outside the set. The client is a fake with canned replies so the demo runs offline; they exercise the validation and say nothing about real model accuracy.
"""Cascade: cheap embedding pass first, an LLM only for 'unsure' cases.
FakeLLM is a stub so the demo runs offline. Swap in a real client behind the same
`complete(prompt) -> str` method; nothing here calls an API.
"""
import json
from model2vec import StaticModel
from demo import DATA, LABELS, classify
PROMPT = (
"Classify the document into exactly one label.\n"
"Labels:\n{labels}\n\nDocument start:\n{text}\n\n"
'Reply with JSON only: {{"label": "<one of: {names}>"}}'
)
class FakeLLM:
"""Stand-in client with canned replies keyed on the document text.
The replies only exercise the parsing and validation below; they say nothing
about how accurate a real model would be.
"""
CANNED = {
"Section 4 Masonry": '{"label": "bill_of_quantities"}',
"Four-week look-ahead": "I think this is a schedule.", # malformed on purpose
"Minutes of progress": '{"label": "meeting_minutes"}', # outside the label set
}
def complete(self, prompt: str) -> str:
document = prompt.split("Document start:\n", 1)[1]
for prefix, reply in self.CANNED.items():
if document.startswith(prefix):
return reply
return '{"label": "other"}'
def llm_label(llm, text: str) -> str:
prompt = PROMPT.format(
labels="\n".join(f"- {k}: {v}" for k, v in LABELS.items()),
text=text[:1500],
names=", ".join(LABELS),
)
try:
label = json.loads(llm.complete(prompt))["label"]
except (json.JSONDecodeError, KeyError, TypeError):
return "unsure" # unparseable reply: route to a human
return label if label in LABELS else "unsure" # reject labels outside the set
if __name__ == "__main__":
model, llm = StaticModel.from_pretrained("minishlab/potion-base-8M"), FakeLLM()
texts, truth = zip(*DATA)
first = classify(texts, model)
final = [llm_label(llm, t) if p.label == "unsure" else p.label
for t, p in zip(texts, first)]
for t, p, f, y in zip(texts, first, final, truth):
if p.label == "unsure":
print(f"{y:<19} -> LLM: {f:<19} {t[:40]!r}")
print(f"LLM calls: {sum(p.label == 'unsure' for p in first)} of {len(texts)}")
Output (the file is saved next to the first as cascade.py, importing the first as demo):
bill_of_quantities -> LLM: bill_of_quantities 'Section 4 Masonry. 4.1 Facing brick wall'
schedule -> LLM: unsure 'Four-week look-ahead: roofing starts Mon'
other -> LLM: unsure 'Minutes of progress meeting 7. Present: '
other -> LLM: other 'Health and safety induction leaflet for '
LLM calls: 4 of 22
Two of the four stay "unsure" because the fake client returned a malformed reply and an out-of-set label. That is the pattern to keep: a reply that cannot be parsed or validated is never guessed at. Even with constrained decoding, keep the check: refusals, truncated replies and capitalisation differences can still break the schema, and the label set can change faster than the schema. The same rule, validate the reply and never repair it silently, is developed in Trustworthy LLM Table Extraction: Layered Validation.
Calibration and abstaining
A score is calibrated if it matches how often the answer is right: among documents scored 0.9, about 90 per cent should be correct. Guo et al. (2017) showed that modern neural networks are often miscalibrated, and that temperature scaling, a one-parameter rescaling of the logits, usually repairs it on labelled validation data. Cosine similarities are not probabilities, so treat raw scores as a ranking, not as confidence.
Two quantities are worth thresholding.
- The top score. A low top similarity means the document resembles none of the descriptions. This is how "other" can be caught, although in Table 3 the descriptions alone caught only one of ten.
- The margin. The gap between the best and second-best labels. A small gap means two labels compete, as with a contract that contains specification clauses.
Both are specific to the encoder, the label descriptions and the truncation length, so retune them whenever any of those change. Set both from a hand-labelled development split by choosing the pair that reaches a target precision, and then read off the coverage you pay for it. Test precision can come in below the dev target, as for the description scorer in Table 2. Report coverage beside precision: "94 per cent accurate" means little without "on 82 per cent of documents". The unsure pile is a review queue, and what reviewers decide there becomes labelled data.
Build a hand-checked evaluation set
Without labels you cannot tell a good classifier from a lucky one, so build a small test set by hand and protect it.
- Sample by stratum. Draw documents per predicted label and per source (project, author, scan quality), not at random. A random sample of a skewed bundle contains almost no examples of the rare classes you most need to measure.
- Label twice. Two people label independently, then reconcile. Disagreement shows where the label definitions are ambiguous, which is often a design flaw and not an annotation error.
- Hold the set out. Do not tune descriptions, templates or thresholds on it. Split it: a development part for tuning, a test part you look at once. Prototype examples come from the development part and are excluded when thresholds are chosen. Repeating the evaluation and bootstrapping intervals are covered in Making LLM Evaluation Reproducible with MLflow.
- Report per class. Overall accuracy hides a collapsed rare class. Use precision (of what was predicted, how much was right) and recall (of what exists, how much was found) per class, plus the confusion matrix. The scikit-learn
classification_reportgives precision, recall, F1 and support per class; setzero_divisionexplicitly, because the default ("warn") scores a class with no predictions or no members as 0 and only warns. - Count the abstentions. Report coverage beside every precision figure.
With a few dozen documents per class, per-class figures are noisy (39 of 42 correct has a 95 per cent interval of 0.81 to 0.98), so quote counts and intervals as well as percentages.
When to train a classifier
A zero-label system is a starting point. Consider a trained classifier when volume makes per-document LLM calls costly, when latency matters, or when the evaluation shows a stubborn confusion that prompts and descriptions do not fix. The route that avoids hand-labelling thousands of documents is weak supervision: produce noisy labels programmatically, then train on them. Data programming (Ratner et al., 2016) and Snorkel (Ratner et al., 2017) describe a way to combine many noisy "labelling functions" and denoise them into training labels. The embedding pass, the LLM and simple rules (a title that contains "Bill of Quantities") can each act as one such function.
The plan: label the bundle with the cascade, combine its votes with rules, keep the reviewed unsure cases as the cleanest labels, train a small classifier, and compare it with the cascade on the same held-out test set. Adopt it only if it matches the cascade on per-class recall at lower cost. Weak labels inherit their sources' biases, and the hand-checked test set exposes that.
Limits
- The numbers are synthetic. The 22 toy snippets had thresholds tuned on the same set; the 120 generated ones are template-built, balanced and easy, with a five-template catch-all. They illustrate the mechanics, not the accuracy you should expect.
- The NLI pipeline and the LLM were not run. Their behaviour is described from documentation. Their cost and accuracy on your documents must be measured. Embedding cost and latency were not measured.
- Text only. Layout, tables and scans are ignored; a scan needs OCR first, and its errors flow into classification.
- One label per document. A file merging a contract and its specification must be split before classifying.
- No operations. Drift monitoring and label-set versioning are not covered.
A checklist
- Write exclusive labels, a catch-all and descriptions.
- Classify from the title page, headings and first table.
- Start with embedding similarity; add a margin and a top-score threshold. Use three to five trusted examples per class as prototypes if you have them.
- Send low-margin cases to an LLM with output restricted to the label set, and validate the reply anyway.
- Route everything still unsure to a person.
- Hand-label a stratified, double-checked dev and test split; choose thresholds on dev; report per-class precision, recall, coverage and the confusion matrix on test.
- Only then consider training on weak labels, and compare against the cascade on the same test set.
Sources
- Hugging Face Transformers docs: ZeroShotClassificationPipeline
- Yin, Hay and Roth (2019): Benchmarking Zero-shot Text Classification
- Reimers and Gurevych (2019): Sentence-BERT
- Guo et al. (2017): On Calibration of Modern Neural Networks
- Ratner et al. (2016): Data Programming
- Ratner et al. (2017): Snorkel
- Model2Vec repository
- Model card: minishlab/potion-base-8M
- Claude API docs: structured outputs
- Geifman and El-Yaniv (2017): Selective Classification for Deep Neural Networks (further reading: "Our method allows a user to set a desired risk level.")
- scikit-learn 1.9 docs: classification_report