Sub topic 5
Adding Rules with spaCy’s EntityRuler
Assume you know basic Python, can install spaCy packages, and understand that a pipeline applies several text-processing components in order. This chapter focuses on adding predictable entity rules to an existing spaCy pipeline. It does not cover training a new model.
The EntityRuler is a spaCy pipeline component that creates entities from patterns. A pattern can match an exact phrase or a sequence of tokens with conditions such as lowercase text, part of speech, or token shape. Rules are useful for names, product codes, internal terms, and other entities that follow a known format.
Why combine rules with statistical NER?
A pretrained NER model learns from examples. It can recognize common people, organizations, places, and dates, but it may not know your product names or internal abbreviations. A rule can identify those terms consistently.
| Approach | Strength | Typical weakness |
|---|---|---|
| Statistical NER | Handles varied wording and context | Can miss domain-specific terms |
| EntityRuler | Predictable and easy to update | Needs patterns for possible forms |
| Both together | Combines coverage with precision | Component order affects results |
Place the ruler before the statistical ner component when rules should influence later predictions. This lets the pipeline mark known entities before the model processes the document.
import spacy
nlp = spacy.load("en_core_web_sm")
ruler = nlp.add_pipe("entity_ruler", before="ner")
ruler.add_patterns([
{"label": "ORG", "pattern": "Kiro"},
{
"label": "PRODUCT",
"pattern": [
{"LOWER": "spacy"},
{"LOWER": "pipeline"},
],
},
])
doc = nlp("Kiro published a new spaCy pipeline guide.")
print([(ent.text, ent.label_) for ent in doc.ents])The first pattern matches the exact phrase Kiro. The second pattern matches two consecutive tokens, regardless of capitalization. Each dictionary in a token pattern describes one token. LOWER compares the lowercase form, while TEXT compares the token text exactly.
Writing useful token patterns
String patterns are convenient for fixed phrases:
{"label": "GPE", "pattern": "New York"}Token patterns are more flexible. For example, this pattern matches a word beginning with an uppercase letter followed by a number:
{
"label": "PRODUCT_CODE",
"pattern": [
{"SHAPE": "Xxxxx"},
{"IS_DIGIT": True},
],
}spaCy token attributes include LOWER, LEMMA, POS, IS_DIGIT, IS_ALPHA, and SHAPE. Pattern operators can also express repetition. For example, "op": "+" means that the token pattern may occur one or more times.
A rule should describe the boundary of the entity carefully. A pattern for Kiro might also match the word inside a longer product name if the surrounding context is not considered. Test rules against both intended matches and near-misses.
Inspecting and maintaining rules
The ruler stores its patterns, so you can inspect them while debugging:
for pattern in ruler.patterns:
print(pattern)For larger applications, keep patterns in JSONL or another version-controlled data file instead of embedding every rule in Python. Include test sentences for each important rule. Check capitalization, punctuation, hyphenation, and nearby words that should not become entities.
Rules do not replace evaluation. A rule can increase recall by finding more intended entities, but it can also create false positives. Review both kinds of errors after adding patterns.
Exercise
Write an EntityRuler pattern that labels the exact phrase "Project Atlas" as a PROJECT entity, ignoring capitalization.
Show answer
Use {"label": "PROJECT", "pattern": [{"LOWER": "project"}, {"LOWER": "atlas"}]}.