Sub topic 8
Running a Transformer NER Model with Hugging Face
Prerequisites and the model pipeline
This chapter assumes basic Python, familiarity with tokens, and a general understanding of neural-network classifiers. You should also know how to install Python packages with pip.
A transformer is a neural network that represents each token using information from the surrounding text. For named entity recognition (NER), a token-classification model adds a label to each token. Common labels include:
PER: personORG: organizationLOC: locationMISC: another named entityO: outside any entity
Hugging Face provides the pipeline function, which hides model loading, tokenization, inference, and result formatting.
pip install transformers torchThe model used here, dslim/bert-base-NER, is a BERT model fine-tuned for English NER. BERT is a transformer encoder. The first run downloads the model and tokenizer, so it needs network access and several hundred megabytes of storage.
Running inference
Create a token-classification pipeline and pass it a string:
from transformers import pipeline
ner = pipeline(
"token-classification",
model="dslim/bert-base-NER",
aggregation_strategy="simple",
)
text = "Hugging Face is based in New York City."
entities = ner(text)
for ent in entities:
print(
ent["entity_group"],
ent["word"],
round(float(ent["score"]), 3),
ent["start"],
ent["end"],
)A result is a dictionary containing information such as:
entity_group: the predicted type, such asORGorLOCword: the text assigned to the entityscore: the model's confidence-like scorestartandend: character offsets in the original string
The output should identify Hugging Face as an organization and New York City as a location. Exact scores can differ between library versions or model revisions. Treat a score as a ranking signal, not as a calibrated probability.
Why aggregation matters
Transformer tokenizers often split a word into subword pieces. For example, an uncommon word might become several pieces. The model predicts a label for each piece, but an application usually needs one result for the complete entity.
aggregation_strategy="simple" combines adjacent token predictions into entity groups. It also returns character offsets, which let you recover the corresponding substring:
for ent in ner(text):
original = text[ent["start"]:ent["end"]]
print(f"{original!r}: {ent['entity_group']}")Aggregation cannot repair an incorrect prediction. If one part of a name receives the wrong label, the grouped result may still be incomplete or incorrectly typed. Inspect examples from your own domain before trusting the output.
Choosing this approach
Use the Hugging Face pipeline when you need a quick baseline, want access to many pretrained transformer models, or plan to fine-tune a model later. A transformer model usually handles context better than simple string rules, but it requires more memory and is slower than a small rule-based matcher. For production use, record the model name, version, and threshold decisions so results remain reproducible.
Exercise
What does aggregation_strategy="simple" do, and why is it useful for NER?
Show answer
It combines predictions for adjacent tokens or subword pieces into complete entity groups, making the output easier to use as entity spans.