Sub topic 12
Training a Custom spaCy NER Model
Prerequisites and training workflow
This chapter assumes that you know basic Python, can install packages with pip, and understand tokens and classification. You should also know that a named entity recognition (NER) model predicts a label for a span of text, such as PERSON, ORG, or GPE.
A custom spaCy NER model learns from annotated examples. Each example contains:
- The original text.
- Character offsets for each entity.
- A label for each entity.
- A training or development split.
The development set, often called the dev set, is held out during training. It helps measure whether the model works on text it has not seen.
Preparing annotated spans
spaCy stores entities as Span objects. A span covers a range of tokens in a Doc. You can create one from character offsets with doc.char_span.
The end offset is exclusive. In the sentence below, Ada Lovelace occupies characters 0 through 11, so its span is (0, 12). London occupies (23, 29).
import spacy
from spacy.tokens import DocBin
nlp = spacy.blank("en")
examples = [
(
"Ada Lovelace worked in London.",
[(0, 12, "PERSON"), (23, 29, "GPE")],
),
(
"Grace Hopper joined the U.S. Navy.",
[(0, 12, "PERSON"), (26, 35, "ORG")],
),
]
doc_bin = DocBin()
for text, annotations in examples:
doc = nlp.make_doc(text)
entities = []
for start, end, label in annotations:
span = doc.char_span(start, end, label=label, alignment_mode="strict")
if span is None:
print(f"Skipping misaligned span: {text[start:end]!r}")
else:
entities.append(span)
doc.ents = entities
doc_bin.add(doc)
doc_bin.to_disk("train.spacy")alignment_mode="strict" requires the offsets to match complete token boundaries. This is safer than silently changing an annotation. A None result usually means that an offset is wrong or that the annotation cuts through a token.
For a real project, create separate train.spacy and dev.spacy files. Keep documents, rather than individual sentences, in only one split. Otherwise, nearly identical text can appear in both sets and produce an overly optimistic evaluation.
Generating a config and training
A spaCy config describes the pipeline, model architecture, optimizer, and training settings. Generate one instead of writing every setting manually:
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 --pipeline ner option creates a pipeline with an NER component. The --optimize accuracy option chooses a configuration intended for predictive quality. It may select transformer components, so install the required packages if the generated config requests them.
After training, spaCy writes the best checkpoint under ./output/model-best. Load it and inspect predictions:
import spacy
nlp = spacy.load("./output/model-best")
doc = nlp("Ada Lovelace worked in London.")
for entity in doc.ents:
print(entity.text, entity.label_)The model can only predict labels that were present in training data. If PRODUCT never appears in the annotations, the model has no basis for predicting it.
Common training errors
- Incorrect character offsets cause missing or misaligned spans.
- Overlapping entities cannot normally be stored together in
doc.ents. - Too few examples cause memorization instead of generalization.
- Inconsistent labels, such as
COMPANYandORGfor the same concept, confuse the model. - A dev set that is too small gives unstable metrics.
After training, inspect false positives and false negatives. Add representative examples, correct the annotations, retrain, and compare entity-level precision, recall, and F1 rather than judging a model from one successful sentence.
Exercise
Why should a training script check whether doc.char_span returns None?
Show answer
None means that the character offsets do not align with the document's token boundaries. Skipping or correcting that annotation prevents invalid entity spans from entering training.