Sub topic 2
Adding rules with the EntityRuler
This chapter assumes you know basic Python, can install packages with pip, and understand that a tokenizer splits text into tokens. It also covers how transformer encoders assign a label to each token, which is the core idea behind transformer NER models.
Adding rules with the EntityRuler
The EntityRuler is a spaCy pipeline component that labels entities from exact strings or token patterns. Place it before the statistical ner component so its matches take priority over model predictions.
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])How transformer encoders label tokens
A transformer encoder reads the whole token sequence and outputs one vector per token. A token-classification head turns each vector into a label such as B-ORG or O. The labels use BIO tags: B marks the beginning of an entity, I marks a token inside it, and O marks a token outside any entity.
Subword tokenization and its effect on NER
Transformers usually split words into subword pieces. A rare word may become several tokens, and the model predicts a label for each piece. You must map those predictions back to words, and during training you must assign each word's label to one subword only.
from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
print(tokenizer.tokenize("spaCy pipelines"))Running a transformer NER model with Hugging Face
The token-classification pipeline runs the model and merges subword predictions into whole entities when you set aggregation_strategy="simple".
from transformers import pipeline
ner = pipeline(
"token-classification",
model="dslim/bert-base-NER",
aggregation_strategy="simple",
)
for ent in ner("Hugging Face is based in New York City."):
print(ent["entity_group"], ent["word"], round(float(ent["score"]), 3))Transformer-based spaCy pipelines
spaCy also offers transformer pipelines, such as en_core_web_trf, which you install with python -m spacy download en_core_web_trf. They expose the same doc.ents interface as the small models, so your extraction code does not change. They are slower but usually more accurate.
caption: How a transformer NER model turns text into entities. alt: A flowchart showing input text split into subword tokens, passed through a transformer encoder, labeled with BIO tags, and merged into entities.
Exercise
Exercise
Why must the entity_ruler come before the ner component when you add it to the pipeline?
Show answer
The pipeline runs components in order. Placing the ruler before ner means its matches are set first, so they take priority over the statistical model's predictions.