Sub topic 12
Training a custom spaCy NER model
Pretrained spaCy models only know the labels they were trained on, such as PERSON, ORG and GPE. If you need DRUG, PART_NUMBER or CLAUSE_TYPE, or if the pretrained model performs poorly on your text, you have to train your own. This chapter covers the spaCy workflow for that: annotated spans, the binary .spacy format, the config file, the training loop, and evaluation.
This chapter assumes you can run Python scripts and shell commands, and that you know what a span and a BIO tag are from the earlier chapters. You should also be comfortable with the Doc and Span objects.
The workflow at a glance
spaCy training is driven by a config file, not by a Python training loop you write yourself. You supply data and a config, and the spacy train command does the rest.
Preparing training data
spaCy reads training data from .spacy files. Each file is a serialized DocBin, which is a compact container of Doc objects. For NER, each Doc must have its ents set.
Annotation tools often export character offsets, such as (0, 12, "PERSON"). You turn these into spans with doc.char_span(). This method returns None when the offsets do not line up with token boundaries, so you must check for that.
The script below builds spans by searching for each entity string, so the offsets are always right. It then splits the examples into a training file and a development file.
import spacy
from spacy.tokens import DocBin
nlp = spacy.blank("en")
def make_doc(text, entities):
doc = nlp.make_doc(text)
spans = []
for surface, label in entities:
start = text.index(surface)
span = doc.char_span(start, start + len(surface), label=label)
if span is None:
print(f"Skipped {surface!r} in {text!r}: not aligned to tokens")
continue
spans.append(span)
doc.ents = spans
return doc
train_data = [
("Ada Lovelace worked in London.", [("Ada Lovelace", "PERSON"), ("London", "GPE")]),
("Alan Turing studied at Cambridge.", [("Alan Turing", "PERSON"), ("Cambridge", "GPE")]),
("Grace Hopper moved to Washington.", [("Grace Hopper", "PERSON"), ("Washington", "GPE")]),
]
dev_data = [
("Charles Babbage lived in London.", [("Charles Babbage", "PERSON"), ("London", "GPE")]),
]
for name, data in [("train.spacy", train_data), ("dev.spacy", dev_data)]:
db = DocBin()
for text, entities in data:
db.add(make_doc(text, entities))
db.to_disk(name)
print("wrote", name, len(data), "docs")Three examples are only enough to check that the pipeline runs. A model with usable accuracy typically needs hundreds of annotated examples per label, and more for ambiguous labels.
Alignment problems
The most common data bug is a span that does not match token boundaries. The tokenizer splits London. into London and .. An annotation of (23, 30) that includes the full stop therefore returns None.
char_span has an alignment_mode argument that controls what happens:
| Mode | Behaviour |
|---|---|
| `"strict"` (default) | Returns `None` unless both offsets fall exactly on token boundaries. |
| `"contract"` | Shrinks the span to the tokens fully inside the offsets. |
| `"expand"` | Grows the span to include every token the offsets touch. |
Keep strict while you build the dataset, so that annotation problems show up. Switch to contract or expand only if you know the offsets are slightly noisy. Silently dropping misaligned spans removes true entities from the document. Those tokens are then treated as non-entities, which teaches the model the wrong thing.
Overlapping spans
doc.ents cannot hold overlapping spans. Assigning overlapping spans raises a ValueError. If your annotations contain nested or overlapping entities, pick one level to keep. The helper spacy.util.filter_spans(spans) keeps the longest span when two overlap. Nested entities need a different component, SpanCategorizer, which is outside this chapter.
Missing annotations are not the same as "no entity"
In a training Doc, any token that is not inside an entity is treated as a known non-entity. If you annotated only some entities in a text, the model learns that the others are not entities. Annotate every entity of your label set in each training document, or leave out documents you did not fully annotate.
Generating and reading the config
A config file holds the pipeline, the model architecture, the optimizer, the data paths and the training schedule. Generate a starting point with init config:
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.spacyThe --optimize flag picks a preset:
efficiencyuses a small CPU-friendly model with static vectors-free embeddings. It trains and runs quickly and is a good default for production on CPUs.accuracyuses a transformer. It needs thespacy-transformerspackage, and training is slow without a GPU. Add--gpu-id 0tospacy trainwhen you have one.
The --paths.train and --paths.dev options override the [paths] section of the config at the command line. Any config value can be overridden this way with dotted names, for example --training.max_epochs 20.
Some config sections you will touch most often:
| Section | What it controls |
|---|---|
| `[nlp]` | Language, the list of pipeline components, batch size at inference. |
| `[components.ner]` | The NER component and its model architecture. |
| `[training]` | `max_epochs`, `max_steps`, `patience`, `dropout`, `eval_frequency`. |
| `[training.score_weights]` | Which metrics decide the "best" model. For NER these are `ents_f`, `ents_p` and `ents_r`. |
| `[corpora]` | Where the training and dev data are read from. |
If you edit a config by hand and leave out defaults, run python -m spacy init fill-config config.cfg config.cfg to add them back.
Checking the data before training
Run spacy debug data before a long training run:
python -m spacy debug data config.cfg --paths.train ./train.spacy --paths.dev ./dev.spacyIt reports the number of examples, the entity count per label, labels that appear in the dev set but not in the training set, and tokens that begin or end with whitespace in a span. Fix any warnings first. A label that appears fewer than a few dozen times is usually too rare to learn.
Running training and reading the log
spacy train prints a table every eval_frequency steps. The columns that matter are the loss, the NER precision, recall and F-score on the dev set, and the combined score. Training stops when the score has not improved for patience evaluations, or at max_epochs or max_steps.
Two directories are written to ./output:
model-bestis the checkpoint with the highest combined score on the dev set.model-lastis the final checkpoint.
Use model-best unless you have a reason not to. Load it like any other pipeline:
import spacy
nlp = spacy.load("./output/model-best")
doc = nlp("Mary Somerville was born in Scotland.")
print([(ent.text, ent.label_) for ent in doc.ents])Evaluating on held-out data
The dev set is used during training to choose the best checkpoint, so its score is slightly optimistic. Keep a third test set that the training run never saw. Evaluate on it with:
python -m spacy evaluate ./output/model-best ./test.spacy --output metrics.jsonThe result contains ents_p, ents_r and ents_f, plus a per-label breakdown in ents_per_type. These are entity-level metrics. A prediction counts only if both the span boundaries and the label match, which is the same convention you saw with seqeval.
Starting from a pretrained pipeline
You do not always have to train from a blank pipeline. Two common patterns exist:
- Add new labels to an existing pipeline. Source the
nercomponent from a pretrained package in the config, for examplesource = "en_core_web_sm"in[components.ner]. Train on data that contains both the old and the new labels. If you train only on the new label, the model forgets the old ones. This is called catastrophic forgetting. - Combine a custom model with the pretrained one. Keep the pretrained NER and add your own component, or use an
EntityRuler, for the new labels. This avoids retraining but can produce overlapping predictions that you must resolve.
Pattern 1 gives one consistent model. Pattern 2 is cheaper when you only need a few extra labels.
Common failure modes
- Dev score stays at zero. Check that the dev file has entities and that the label names match the training file exactly.
PersonandPERSONare different labels. - Training score is high, dev score is low. The model has memorised a small training set. Add data or raise
dropout. - Many entities are skipped at conversion time. The offsets are misaligned, usually because of trailing punctuation or whitespace. Inspect a few skipped examples.
- A rare label never gets predicted. It has too few examples. Collect more, or cover it with an
EntityRuler. spacy trainfails to import a transformer. You generated anaccuracyconfig without installingspacy-transformers.
Exercises
Exercise
You annotate "Cambridge." in the text "Alan Turing studied at Cambridge." as a GPE using the character range that includes the final full stop. With the default settings, what does doc.char_span(start, end, label="GPE") return, and what are two ways to fix it?
Show answer
It returns None, because the end offset falls inside the single "." token's boundary and not on a token boundary that matches the range. Fix it either by correcting the annotation so the span ends before the full stop, or by passing alignment_mode="contract" (or "expand") so the span snaps to token boundaries. Correcting the annotation is safer, because it keeps the data exact.
Exercise
After training, model-best has a dev F-score of 0.92, but on a separate test set the F-score is 0.78. Give two likely causes and one check for each.
Show answer
First, the dev set is small or similar to the training data, and the best checkpoint was chosen on it, so the score is optimistic. Check the dev set size and how much it overlaps with the training text. Second, the test set has a different distribution, such as other sources, styles or entity types. Check ents_per_type in the spacy evaluate output to see which labels dropped, then read the errors for those labels.