Sub topic 3
Building a gold dataset
A gold dataset is a set of texts with reference answers that people have checked. Every number in the rest of this tutorial depends on it. Span-level F1 measures agreement with the gold labels, so errors or ambiguity in those labels flow into every score. A token-classification model also trains on this data. This chapter covers how to build the data, how to check that it is trustworthy, and how to avoid the mistakes that make scores misleading.
It assumes you have a written schema from the previous chapter (entity types, fields, rules for null values and boundaries). You should also know basic Python, JSON, and precision, recall and F1.
What "gold" has to mean
Gold labels are not ground truth in a philosophical sense. They are the best answer your team can agree on under the written rules. That has two consequences:
- If two careful people disagree often, the task is under-specified. Fix the guidelines before labeling more data.
- A system cannot be reliably scored above the agreement level between humans. If annotators agree on 85% of spans, a reported 95% F1 is mostly noise or leakage.
The same gold data serves three purposes, and you should keep them apart:
| Split | Purpose | Who may look at it |
|---|---|---|
| Train | Fine-tuning a model, or picking few-shot examples | Everyone |
| Dev | Iterating on prompts, thresholds and hyperparameters | The builders, repeatedly |
| Test | One final comparison of approaches | Looked at rarely, scored once per decision |
Prompted systems need splits too. Prompt tuning on the test set overfits it just as training does, only more slowly.
The workflow
The sequence below is the usual one. Notice the loop: disagreements feed back into the guidelines, not only into the labels.
Step 1: Sample documents that look like production
The most common reason a good score fails to hold up is that the evaluation text differs from the text the system will see. Draw documents from the real source, not from examples you wrote yourself.
- Sample by document, not by sentence. You need to know which sentences came from which document for the splitting step later.
- Cover the variety. If invoices come from 40 vendors in three languages, sample across vendors and languages instead of taking the newest 500 files.
- Include empty cases. Documents where a field is absent, or no entity appears, teach you whether a system invents values. A dataset in which every document contains every field cannot measure that.
- Stratify for rare labels. If a label appears in 2% of documents, a random sample of 200 documents yields about four examples. Oversample for it, and report the sampling choice, since it changes the label frequencies.
Oversampling affects how you interpret scores. Per-label F1 is still valid. Overall micro-F1 reflects your sample's label mix, not production's.
Step 2: Choose a storage format that preserves offsets
Store the original text unchanged, and store each span as character offsets into that text, plus the label. Also store the surface string as a redundant check. Do not store only the entity text. If "Paris" appears twice, text alone cannot say which occurrence was labeled, and span-level scoring needs positions.
Use half-open offsets: start is the index of the first character and end is one past the last, so text[start:end] is the span. This is the convention in the BIO conversion code used in the evaluation chapter.
import json
record = {
"doc_id": "news-0001",
"text": "Angela Merkel visited Paris.",
"spans": [
{"start": 0, "end": 13, "label": "PER", "surface": "Angela Merkel"},
{"start": 22, "end": 27, "label": "LOC", "surface": "Paris"},
],
}
ALLOWED_LABELS = {"PER", "LOC", "ORG"}
def validate_record(rec):
problems = []
text = rec["text"]
seen = set()
for s in rec["spans"]:
if s["label"] not in ALLOWED_LABELS:
problems.append(f"unknown label {s['label']!r}")
if not (0 <= s["start"] < s["end"] <= len(text)):
problems.append(f"bad offsets {s['start']}-{s['end']}")
continue
if text[s["start"]:s["end"]] != s["surface"]:
problems.append(f"surface mismatch at {s['start']}-{s['end']}")
if (s["start"], s["end"], s["label"]) in seen:
problems.append(f"duplicate span at {s['start']}-{s['end']}")
seen.add((s["start"], s["end"], s["label"]))
return problems
print(validate_record(record))
broken = dict(record, spans=[{"start": 0, "end": 12, "label": "PER", "surface": "Angela Merkel"}])
print(validate_record(broken))
print(json.dumps(record))The first call prints an empty list. The second reports a surface mismatch, because offsets 0 to 12 select "Angela Merke". Run a validator like this on every file before it enters the dataset. Offset bugs are silent otherwise: they lower every score without raising an error.
Keep one JSON record per line (JSONL) so records can be diffed and reviewed in version control.
Common offset traps:
- Text normalization after labeling. If you strip whitespace, fix encoding or change line endings after annotation, every offset shifts. Normalize first, then annotate, and never edit the stored text afterward.
- Unicode. Python indexes by code point. Some annotation tools and other languages count UTF-16 units or bytes. Emoji and some accented characters then shift offsets. Test with a record that contains one.
- Overlapping or nested spans. BIO tagging cannot represent them. Decide in the schema whether they are allowed. If a token classifier is a candidate approach, forbid them or flatten them.
Step 3: Write guidelines and run a pilot
The schema from the previous chapter defines labels. Guidelines add the decisions annotators actually meet. Examples of what they need to settle:
- Does "Dr. Angela Merkel" include the title?
- Is "the European Union" labeled ORG with or without "the"?
- When the invoice shows a subtotal, a tax amount and a total, which is
total? - What counts as "not stated" for a null field: absent, illegible, or ambiguous?
Give each rule at least one positive and one negative example from real documents.
Then run a pilot. Two people label the same 30 to 50 documents independently, without discussing them. Compare results, read every disagreement, and decide whether it was a careless slip, a rule gap, or a real ambiguity. Rule gaps go into the guidelines. Repeat until the disagreements are mostly slips.
Step 4: Measure agreement
Inter-annotator agreement is how often two people produce the same labels. For extraction, the simplest useful measure reuses the metric you will score systems with: treat annotator A as gold and B as the prediction, and compute exact-match span F1. The result is nearly symmetric, so it does not matter much which you choose.
def span_f1(a, b):
a, b = set(a), set(b)
tp = len(a & b)
p = tp / len(b) if b else 0.0
r = tp / len(a) if a else 0.0
return 2 * p * r / (p + r) if p + r else 0.0
annotator_a = [(0, 13, "PER"), (22, 27, "LOC")]
annotator_b = [(0, 6, "PER"), (22, 27, "LOC")]
print(span_f1(annotator_a, annotator_b))This prints 0.5: one of two spans matches exactly, because B labeled only "Angela". A boundary disagreement counts as both a missed span and a spurious one under exact matching.
To tell boundary disputes from type disputes, also compute agreement with a looser rule, such as "overlapping span with the same label". A large gap between strict and loose agreement means annotators find the right things but disagree on boundaries, which is a guideline problem. Cohen's kappa is a common alternative that corrects for chance agreement. It suits token-level or document-level decisions, but chance agreement is hard to define for spans, so span F1 is the usual choice for NER.
For key-value fields, compare per field after the normalization rules from the schema, such as whether "120.50" equals "120.5".
There is no universal passing threshold. Look at agreement per label. A label with markedly lower agreement than the rest is usually the one whose definition needs work.
Step 5: Annotate, adjudicate and keep an overlap
For the full set, one annotator per document is usually enough. Keep a double-annotated overlap of perhaps 10 to 20% so you can keep tracking agreement, since annotators drift as they tire or interpret rules differently over time.
Adjudication resolves disagreements. A third person, ideally the one who owns the guidelines, picks the correct label for each disputed span, and records which rule decided it. Those decisions become new guideline examples.
Two cautions apply when you use a model to pre-annotate:
- Anchoring. Annotators who correct model output tend to accept it. If the model is later scored on that data, it gets credit for its own habits. Pre-annotating with a model that you will also evaluate inflates its score.
- Blind comparison. If you want a fair comparison, the test set should be labeled by humans from scratch, or at minimum reviewed with a deliberate check for under-correction.
Step 6: Split without leakage
Split by document, never by sentence or span. Sentences from the same document share vendors, names, templates and phrasing. If some land in training and others in test, a fine-tuned model memorizes them, and the test score tells you about memorization. The same applies to few-shot examples: do not draw prompt examples from the test set.
Go further than document ID where the data calls for it. Group by the unit that causes shared patterns: the same vendor, the same author, the same thread, or near-duplicate documents. A hash of the group key gives a stable, reproducible assignment:
import hashlib
def split_for(group_key, test_percent=20):
digest = hashlib.sha256(group_key.encode("utf-8")).hexdigest()
return "test" if int(digest, 16) % 100 < test_percent else "dev"
for key in ["vendor-acme", "vendor-globex", "vendor-initech"]:
print(key, split_for(key))Because the assignment depends only on the key, adding new documents later never moves existing ones across splits. Hashing gives approximate proportions, so check the resulting label counts in each split afterward, especially for rare labels.
How much data is enough
There is no fixed number, but you can reason about it. Scores from a small test set are uncertain. For a proportion near 0.8 measured over 100 entities, the standard error is the square root of 0.8 × 0.2 / 100, which is 0.04. A 95% interval is roughly plus or minus 8 points. A two-point difference between a prompted system and a fine-tuned one on 100 entities is not a finding.
| Need | Rough guidance |
|---|---|
| Compare two systems on a label | Enough test entities per label that the interval is narrower than the difference you care about. Often a few hundred per frequent label. |
| Prompt iteration | A dev set of a few dozen to a couple of hundred documents is typical. |
| Fine-tune a token classifier | Training needs far more than evaluation. Hundreds to thousands of documents is common, depending on how many labels and how varied the text. |
Count entities per label, not documents. A set of 500 documents with 12 examples of a rare label cannot evaluate that label.
Freeze and version
Once the test set is used for a decision, treat it as frozen. Record in a short README: the sampling method, guideline version, annotators' roles, agreement figures, and the split rule. If you later fix label errors, publish a new version and rescore old systems on it. Comparing scores from different dataset versions is a common source of false improvements.
Common errors
- Reporting a single F1 without saying how many entities it covers.
- Labeling from text that was later reformatted, shifting all offsets.
- Letting one person write the guidelines, label everything and adjudicate, so agreement cannot be measured.
- Splitting by sentence, which leaks near-duplicates across splits.
- Leaving out documents with no entities or with missing fields.
- Changing the guidelines mid-annotation without relabeling earlier documents.
Exercise
A team splits 1,000 labeled sentences randomly into 800 train and 200 test. The fine-tuned token classifier scores 96% F1, but it performs much worse on newly collected documents. Name the likely cause and give two changes to the dataset construction.
Show answer
Sentences from the same source documents (same vendors, templates and names) appear in both train and test, so the model has seen near-duplicates and the test score reflects memorization. Change 1: split by document, or by a group such as vendor, before extracting sentences. Change 2: sample the test documents from the same recent production source the system will serve, and check that no group key appears in both splits.
Exercise
Annotators A and B label the same 4 spans in a document. They agree exactly on 3 spans, and B marks the fourth with different boundaries. Using exact-match span F1 with A as gold, what is the agreement? What additional measurement would show whether the disagreement is about boundaries or about what to extract?
Show answer
A has 4 spans and B has 4 spans, 3 match exactly, so precision is 3/4 and recall is 3/4, and F1 is 0.75. A looser measure, such as counting overlapping spans with the same label as matches, would give 1.0 here. A large gap between strict and loose agreement points to boundary rules in the guidelines, not to disagreement about which things to extract.