Sub topic 4
Measuring extraction quality with span-level F1
This chapter assumes you know basic Python, how precision, recall and F1 are defined, and what an extraction schema and a gold dataset are from the earlier chapters. Here you will turn those pieces into a scoring procedure. The procedure gives one comparable number for a prompted LLM and for a fine-tuned token classifier.
Why accuracy is the wrong measure
Most tokens in a document are not part of any entity. A model that tags every token as O (outside any entity) can reach 90% or more token accuracy and extract nothing. Extraction is a task of finding the right items, so you score the items, not the tokens.
Precision, recall and F1 fit this because the output is a set of predicted items compared against a set of gold items:
- Precision is the share of predicted items that are correct. Low precision means the system invents or mislabels things.
- Recall is the share of gold items the system found. Low recall means the system misses things.
- F1 is the harmonic mean of the two. It is low when either one is low.
What counts as one item
You must decide what the unit of scoring is before you compute anything. For named entities and similar tasks, the unit is a span: a start position, an end position and a label. A prediction is correct only if all three match a gold span. This is called exact match.
def bio_to_spans(tags):
spans = []
start = None
label = None
for i, tag in enumerate(tags + ["O"]):
if start is not None and not (tag.startswith("I-") and tag[2:] == label):
spans.append((start, i, label))
start = None
label = None
if tag != "O" and start is None:
start = i
label = tag[2:]
return spans
def precision_recall_f1(gold, pred):
gold, pred = set(gold), set(pred)
tp = len(gold & pred)
p = tp / len(pred) if pred else 0.0
r = tp / len(gold) if gold else 0.0
f1 = 2 * p * r / (p + r) if p + r else 0.0
return p, r, f1
gold = bio_to_spans(["B-PER", "I-PER", "O", "B-LOC"])
pred = bio_to_spans(["B-PER", "O", "O", "B-LOC"])
print(gold)
print(pred)
print(precision_recall_f1(gold, pred))The output is:
[(0, 2, 'PER'), (3, 4, 'LOC')]
[(0, 1, 'PER'), (3, 4, 'LOC')]
(0.5, 0.5, 0.5)The end index is exclusive, as in a Python slice. The predicted person span (0, 1, 'PER') covers only the first token, so it does not equal the gold span (0, 2, 'PER'). That single boundary error produces one false positive and one false negative.
Counting true positives, false positives and false negatives
Each comparison produces one of three outcomes:
| Outcome | Meaning | Effect |
|---|---|---|
| True positive (TP) | Predicted span equals a gold span | Raises precision and recall |
| False positive (FP) | Predicted span matches no gold span | Lowers precision |
| False negative (FN) | Gold span matches no predicted span | Lowers recall |
Precision is TP / (TP + FP). Recall is TP / (TP + FN). F1 is 2TP / (2TP + FP + FN), which is a convenient form because it uses only the three counts.
A wrong boundary is penalized twice, once as an FP and once as an FN. A correct boundary with the wrong label is also both. Exact match is strict on purpose, and it is the convention behind most published NER numbers.
Aggregating over documents and labels
A real evaluation covers many documents and several labels. Two choices matter.
Micro and macro averaging
Micro averaging pools the TP, FP and FN counts across all documents and labels, then computes the metrics once. Frequent labels dominate the result. Macro averaging computes F1 for each label and averages those values, so a rare label counts as much as a common one.
Report both. A system can have a high micro F1 because it handles PER well while failing completely on a rare ORG label. Only the per-label scores and the macro average show this.
from collections import Counter
def label_counts(gold, pred):
tp, fp, fn = Counter(), Counter(), Counter()
gold, pred = set(gold), set(pred)
for s in gold & pred:
tp[s[-1]] += 1
for s in pred - gold:
fp[s[-1]] += 1
for s in gold - pred:
fn[s[-1]] += 1
return tp, fp, fn
def f1_from_counts(tp, fp, fn):
denom = 2 * tp + fp + fn
return 2 * tp / denom if denom else 0.0
# Each span carries its document id so spans from different documents never match.
gold = [("d1", 0, 2, "PER"), ("d1", 3, 4, "LOC"), ("d2", 0, 1, "ORG")]
pred = [("d1", 0, 1, "PER"), ("d1", 3, 4, "LOC"), ("d2", 0, 1, "LOC")]
tp, fp, fn = label_counts(gold, pred)
labels = sorted(set(tp) | set(fp) | set(fn))
per_label = {l: f1_from_counts(tp[l], fp[l], fn[l]) for l in labels}
micro = f1_from_counts(sum(tp.values()), sum(fp.values()), sum(fn.values()))
macro = sum(per_label.values()) / len(per_label)
print(per_label)
print("micro", round(micro, 3), "macro", round(macro, 3))This prints {'LOC': 0.5, 'ORG': 0.0, 'PER': 0.0} and then micro 0.333 macro 0.167. The code builds each span as a tuple that begins with the document id. Without the id, a span at positions 0 to 1 in one document would match a span at the same positions in another.
Duplicates
Python sets collapse identical items. If the same span can legitimately occur twice, as with repeated fields in a table, use a multiset (Counter) and count matches as the minimum of the two counts. For ordinary span evaluation each position pair is unique, so sets are fine.
Scoring fields instead of spans
Many extraction tasks return key-value fields such as the invoice schema from the previous chapters, not tagged text. An LLM returns the string "Acme", not character offsets. For these tasks the scored item is the pair of field name and normalized value.
Normalize both sides before comparing. Lowercase, strip whitespace, and convert amounts to numbers, so that "120.50" and 120.5 match. Write the normalization rules down with the labeling guidelines, because they change the score.
Null handling needs explicit rules. Treat each field as follows:
- Gold has a value and the prediction equals it: TP.
- Gold has a value and the prediction is a different value: one FP and one FN.
- Gold has a value and the prediction is null: FN.
- Gold is null and the prediction has a value: FP.
- Gold is null and the prediction is null: nothing is counted.
Rule 5 is why precision punishes systems that guess. The schema instruction "use null when not stated" only pays off if the metric rewards it.
Comparing prompted and fine-tuned systems fairly
The two approaches produce output in different forms, so the comparison can go wrong in ways that have nothing to do with model quality.
- Different coordinates. A token classifier labels tokens, and the tokens depend on the tokenizer. An LLM returns strings. Convert both to character offsets in the original text, or both to normalized strings, before scoring. The Hugging Face pipeline shown later in this tutorial already returns
startandendcharacter offsets. - Repeated strings. If the LLM returns
"Paris"and the text contains it twice, you cannot tell which occurrence was meant. Decide whether you score at the document level (is this entity present?) or the occurrence level, and score both systems the same way. - Same gold data, same split. Few-shot examples and fine-tuning data must come from a training split. Score both systems only on held-out documents that neither saw.
- Same normalization. Apply the same cleaning of whitespace, case and punctuation to both outputs.
Relaxed matching and its limits
Exact match often looks harsh. A prediction of "Dr. Angela Merkel" against gold "Angela Merkel" scores zero. Two common relaxations exist:
- Overlap match. A prediction counts if it overlaps a gold span of the same label.
- Type-only match. Ignore the boundaries and check only that the label was found in the right place.
Use relaxed scores as a diagnostic next to the exact score, not instead of it. A large gap between exact and overlap F1 tells you the model finds the right things but disagrees on boundaries. That points to unclear labeling guidelines, such as whether titles belong to a name, rather than to a model problem. If your downstream use needs the exact string, exact match is the honest number.
Reporting uncertainty
A gold set of 100 spans gives noisy scores. A difference of two F1 points between two systems may not be real. Two practices help:
- Report the count of gold items per label next to each score. A label with eight examples has an F1 you should not trust to a decimal place.
- Bootstrap over documents. Resample the test documents with replacement many times, recompute F1 each time, and report the 2.5th and 97.5th percentiles. Resample whole documents, not individual spans, because spans within a document are not independent.
If the intervals of two systems overlap heavily, you have not shown that one is better.
Common mistakes
- Scoring tokens instead of spans. Token-level F1 gives partial credit for half-correct entities and is not comparable to published span scores.
- Forgetting the
Ohandling at the end of a sequence. Thebio_to_spansfunction appends a sentinel"O"so the last span is closed. Without it, a span that ends at the end of the text is silently dropped. - Invalid BIO sequences. A tag sequence such as
O I-PERhas noB-PER. The function above starts a span at theI-tag. Other libraries drop it. Pick a rule and apply it identically to every system. - Zero-division. If a system predicts nothing, precision is undefined. Return 0.0 and say so in the report.
- Averaging F1 across documents. Per-document F1 averaged over documents weights short documents too heavily. Pool the counts instead.
Exercise
The gold spans are [("d1", 0, 2, "PER"), ("d1", 5, 6, "LOC"), ("d1", 8, 9, "ORG")]. A system predicts [("d1", 0, 2, "PER"), ("d1", 5, 6, "ORG"), ("d1", 8, 9, "ORG"), ("d1", 10, 11, "LOC")]. Using exact match, compute TP, FP, FN, precision, recall and F1. Then give the per-label F1 for ORG.
Show answer
TP is 2: the PER span and the ORG span at 8 to 9. FP is 2: the ORG prediction at 5 to 6 has the wrong label, and the LOC prediction at 10 to 11 matches nothing. FN is 1: the gold LOC span at 5 to 6 was not predicted with that label. Precision is 2/4 = 0.5, recall is 2/3 = 0.667, and F1 is 22 / (22 + 2 + 1) = 4/7 = 0.571. For ORG, TP is 1 (8 to 9), FP is 1 (5 to 6), FN is 0, so F1 is 2 / (2 + 1 + 0) = 0.667.
Exercise
A prompted LLM returns {"vendor": "Acme", "total": null, "currency": "EUR"} for an invoice whose gold is {"vendor": "Acme Corp", "total": 120.5, "currency": "EUR"}. Count TP, FP and FN at the field level, and say what a normalization rule could change.
Show answer
Currency matches: TP = 1. Vendor differs ("Acme" versus "Acme Corp"): one FP and one FN. Total is gold-valued but predicted null: one FN. So TP = 1, FP = 1, FN = 2, giving precision 0.5, recall 1/3 and F1 0.4. A normalization rule that strips legal suffixes such as "Corp" would turn the vendor into a match, raising TP to 2 and removing the FP and one FN. Such rules must be fixed in the guidelines before scoring, and applied to every system.