Sub topic 3
Aligning word labels to subword tokens
This chapter assumes you know basic Python, can install packages with pip, and have used BIO-tagged token data before. You should also understand that a transformer is a neural network that reads token sequences. The chapter covers label alignment, fine-tuning, spaCy training, entity-level evaluation, and choosing an approach.
Aligning word labels to subword tokens
Transformer tokenizers split rare or long words into subword pieces. A word like "Washington" may become two tokens, while your dataset still has one BIO label for that word. Only one token per word should carry the label. The other tokens get -100, which PyTorch's cross-entropy loss ignores.
from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
def tokenize_and_align_labels(example):
tokenized = tokenizer(example["tokens"], is_split_into_words=True, truncation=True)
labels = []
previous_word_id = None
for word_id in tokenized.word_ids():
if word_id is None:
labels.append(-100)
elif word_id != previous_word_id:
labels.append(example["ner_tags"][word_id])
else:
labels.append(-100)
previous_word_id = word_id
tokenized["labels"] = labels
return tokenizedFine-tuning a transformer for NER
Load a pretrained encoder with a token-classification head sized to your label set. Then train with the Hugging Face Trainer and DataCollatorForTokenClassification, which pads labels with -100. Run this on the aligned training and validation splits, and track entity-level F1 on the validation split rather than token accuracy. Token accuracy is inflated by the many O tokens.
Training a custom spaCy NER model
spaCy trains from a config file. Generate a config for NER, then train on binary DocBin files that you created from annotated spans.
python -m spacy init config config.cfg --lang en --pipeline ner --optimize accuracy
python -m spacy train config.cfg --output ./output --paths.train ./train.spacy --paths.dev ./dev.spacyEvaluating NER with entity-level metrics
Score entities, not tokens. An entity counts as correct only when both its span and its label match. The seqeval library computes this from BIO sequences.
from seqeval.metrics import classification_report, f1_score
y_true = [["B-PER", "I-PER", "O", "B-LOC"]]
y_pred = [["B-PER", "I-PER", "O", "O"]]
print(f1_score(y_true, y_pred))
print(classification_report(y_true, y_pred))This prediction finds the person but misses the location. Precision is 1.0, recall is 0.5, and F1 is about 0.67.
Error analysis and choosing an approach
Inspect errors before changing the model. Boundary errors, such as predicting "New" without "York", are common in subword models. Label confusion between similar types, such as ORG and LOC, is another frequent error.
| Approach | Best when | Main cost |
|---|---|---|
| EntityRuler rules | Entities follow fixed patterns | Manual maintenance |
| Pretrained spaCy model | Standard entity types suffice | Less control over labels |
| Custom spaCy training | You have annotated spans and want a small, fast pipeline | Needs annotation |
| Fine-tuned transformer | You need higher accuracy on your own labels | More compute and data |
Exercise:
Exercise
A word is split into three subword tokens and has the label I-ORG. Which tokens receive a label, and what values do the others get?
Show answer
Only the first subword receives I-ORG. The second and third subwords receive -100, so the loss ignores them.