Skip to main content

How to Find Names, Places and Organizations in Text with a Hugging Face NER Pipeline

· 9 min read
Jagdish Kumawat
Founder @ Dewiride

Named entity recognition, or NER, finds the names in a piece of text: people, places, organizations and other named things. A Hugging Face token-classification pipeline does it with a pretrained model, either one token at a time or grouped into whole names. This guide finds two people, a society and a city in one sentence with Transformers 5.26.0 on Python 3.14.

Syntax​

Syntax
from transformers import pipeline

ner = pipeline(
"token-classification",
model="<model>",
revision="<commit>",
aggregation_strategy="<strategy>",
)
results = ner("<text>")
PartWhat it means
"token-classification"The task: give each token of the text a label. "ner" is another name for it
model="<model>"A model trained to tag names, as <owner>/<name> on the Hugging Face Hub
revision="<commit>"The exact version of the model, so it can't change under you
aggregation_strategy="<strategy>"Whether to group tokens into whole names: "none" (the default) returns every token, "simple", "first", "average" and "max" group them
ner("<text>")Returns a list with one dictionary per token, or per name when grouped

A token is a piece of text the model reads: usually a word, sometimes part of a word. The pipelines documentation calls this pipeline the "Named Entity Recognition pipeline using any ModelForTokenClassification".

The Example​

The sentence is "Ada Lovelace met Charles Babbage at the Royal Society in London." The model is dslim/bert-base-NER, a BERT model trained on news articles to tag four kinds of names: people (PER), organizations (ORG), locations (LOC) and miscellaneous other names (MISC). It's MIT-licensed.

Prerequisites​

  • uv. This guide uses uv 0.13.10. The project uses Python 3.14, which uv downloads if needed.
  • About 430 MB for the model, downloaded on the first run.

Step 1: Create the Project​

Terminal
uv init --python 3.14 ner-demo
cd ner-demo
uv add transformers torch

That's a project with Transformers 5.26.0 and PyTorch 2.15.0.

Step 2: Tag Every Token​

First, without grouping, to see what the model really does:

ner_tokens.py
from transformers import pipeline

ner = pipeline(
"token-classification",
model="dslim/bert-base-NER",
revision="d1a3e8f13f8c3566299d95fcfc9a8d2382a9affc",
)

text = "Ada Lovelace met Charles Babbage at the Royal Society in London."
for token in ner(text):
print(f"{token['word']:<10}{token['entity']:<7}{token['score']:.3f}")

Each result is a dictionary. The loop prints three of its keys: the token (word), its tag (entity) and how sure the model is of the tag (score, from 0 to 1).

Terminal
uv run python ner_tokens.py
Output
Warning: You are sending unauthenticated requests to the HF Hub. Please set a HF_TOKEN to enable higher rate limits and faster downloads.
config.json: 100%|██████████████████████████████████████████████████| 829/829 [00:00<00:00, 415kB/s]
model.safetensors: downloading bytes: ██████████████████████████████████████████| 411MB, 2.57MB/s
model.safetensors: reconstructing file: 100%|██████████████████████████| 433MB / 433MB, 14.6MB/s
Loading weights: 100%|██████████████████████████████████████████| 199/199 [00:00<00:00, 6428.13it/s]
[transformers] BertForTokenClassification LOAD REPORT from: dslim/bert-base-NER
Key | Status | Details
-------------------------+------------+--------
bert.pooler.dense.weight | UNEXPECTED |
bert.pooler.dense.bias | UNEXPECTED |

Notes:
- UNEXPECTED: can be ignored when loading from different task/architecture; not ok if you expect identical arch.
tokenizer_config.json: 100%|██████████████████████████████████████| 59.0/59.0 [00:00<00:00, 431kB/s]
vocab.txt: 100%|█████████████████████████████████████████████████| 213k/213k [00:00<00:00, 2.04MB/s]
added_tokens.json: 100%|█████████████████████████████████████████| 2.00/2.00 [00:00<00:00, 16.5kB/s]
special_tokens_map.json: 100%|██████████████████████████████████████| 112/112 [00:00<00:00, 909kB/s]
Ada B-PER 1.000
Love I-PER 1.000
##lace I-PER 0.999
Charles B-PER 1.000
Ba I-PER 1.000
##bba I-PER 0.972
##ge I-PER 0.998
Royal B-ORG 0.997
Society I-ORG 0.998
London B-LOC 0.999

The terminal after uv run python ner_tokens.py: the model downloading, a BertForTokenClassification LOAD REPORT listing two UNEXPECTED pooler weights, then one line per token: Ada B-PER, Love I-PER, ##lace I-PER, Charles B-PER, Ba I-PER, ##bba I-PER, ##ge I-PER, Royal B-ORG, Society I-ORG and London B-LOC, each with a score close to 1.

Here's how to read it:

  • The tags. B- marks the first token of a name and I- the tokens that continue it, so Ada B-PER and Love I-PER belong to one person. The part after the dash is the kind of name: PER, ORG or LOC.
  • The ## tokens. The model's vocabulary has no single token for "Lovelace", so the tokenizer split it into Love and ##lace. ## means "glued to the token before".
  • The missing words. "met", "at", "the" and "in" aren't names. The model tags them O, for outside any name, and the pipeline leaves O tokens out by default.

The first run downloads the model's files. The LOAD REPORT above the results is a warning, not an error: Fixed: BertForTokenClassification LOAD REPORT from dslim/bert-base-NER explains it. The command works unchanged in PowerShell.

note

The model's card describes B-PER as "Beginning of a person's name right after another person's name", which is the older way of using these tags. The output above shows what this model does: it puts B- on the first token of every name, even one that follows no other name, such as London.

Step 3: Group the Tokens into Whole Names​

Ten tokens for four names is hard to use. aggregation_strategy="simple" joins each B- token with the I- tokens after it:

ner_entities.py
from transformers import pipeline

ner = pipeline(
"token-classification",
model="dslim/bert-base-NER",
revision="d1a3e8f13f8c3566299d95fcfc9a8d2382a9affc",
aggregation_strategy="simple",
)

text = "Ada Lovelace met Charles Babbage at the Royal Society in London."
for entity in ner(text):
print(entity)

The ner_entities.py script in a macOS-style code window: a token-classification pipeline with the dslim/bert-base-NER model, its pinned revision and aggregation_strategy simple, then a loop that prints every entity found in the sentence about Ada Lovelace, Charles Babbage, the Royal Society and London.

Terminal
uv run python ner_entities.py
Output
Loading weights: 100%|█████████████████████████████████████████| 199/199 [00:00<00:00, 13329.92it/s]
[transformers] BertForTokenClassification LOAD REPORT from: dslim/bert-base-NER
Key | Status | Details
-------------------------+------------+--------
bert.pooler.dense.weight | UNEXPECTED |
bert.pooler.dense.bias | UNEXPECTED |

Notes:
- UNEXPECTED: can be ignored when loading from different task/architecture; not ok if you expect identical arch.
{'entity_group': 'PER', 'score': np.float32(0.99940664), 'word': 'Ada Lovelace', 'start': 0, 'end': 12}
{'entity_group': 'PER', 'score': np.float32(0.99224246), 'word': 'Charles Babbage', 'start': 17, 'end': 32}
{'entity_group': 'ORG', 'score': np.float32(0.99783516), 'word': 'Royal Society', 'start': 40, 'end': 53}
{'entity_group': 'LOC', 'score': np.float32(0.9993856), 'word': 'London', 'start': 57, 'end': 63}

The terminal after uv run python ner_entities.py: the LOAD REPORT, then four dictionaries: Ada Lovelace PER from 0 to 12, Charles Babbage PER from 17 to 32, Royal Society ORG from 40 to 53 and London LOC from 57 to 63, each with a score above 0.99.

Four names, each whole. Each dictionary holds:

KeyWhat it is
entity_groupThe kind of name, without B- or I-
scoreThe average of its tokens' scores
wordThe name, with the ## pieces joined back together
start, endWhere the name sits in the text, counted in characters: text[0:12] is "Ada Lovelace"

The scores print as np.float32(…) because the pipeline returns NumPy numbers. They work like ordinary numbers, and float(entity["score"]) turns one into a plain Python float.

Which Strategy to Choose​

The documentation describes the five strategies:

StrategyWhat it does
"none"No grouping: one result per token, as in Step 2
"simple"Joins each B- token with the I- tokens after it. Two B- tokens in a row become two names
"first"Like "simple", but a word can't be split: it takes the tag of its first token
"average"Like "simple", but a word can't be split: its tokens' scores are averaged, then the best tag wins
"max"Like "simple", but a word can't be split: it takes the tag of its highest-scoring token

"simple" worked here, but on some names the model tags a ## piece B- instead of I-, and "simple" then returns part of a word as a name of its own. Fixed: Hugging Face NER Pipeline Splits a Name into Pieces Like "##ka" shows it happening and how "first" fixes it. The last three strategies work only with models whose tokens follow the spaces between words, which BERT models like this one do.

Common Mistakes​

MistakeWhat happensDo this instead
Leaving out aggregation_strategyYou get one result per token, with ## piecesPass "simple", or "first" for names the model splits
Expecting every word in the outputWords outside names are tagged O and left outOnly names come back; that's by design
Using a model trained on English for other languagesIt misses or mislabels namesChoose a model for your language on the Hub
Looking for entity when groupingGrouped results have entity_group insteadRead entity_group, or entity only with "none"

FAQ​

What's the difference between "ner" and "token-classification"?​

None. pipeline("ner", …) creates the same pipeline.

Can it find other kinds of names, such as products or dates?​

Not this model: it knows only PER, ORG, LOC and MISC. Other models on the Hub are trained with other tags, and the same code works with them.

Why is the score below 1 for a name it got right?​

The score is how sure the model is, not whether it's right. Charles Babbage got 0.992 because ##bba scored lower than the other tokens.

Conclusion​

A token-classification pipeline with dslim/bert-base-NER tagged each token of the sentence with B- and I- tags, and aggregation_strategy="simple" turned those ten tokens into four names: Ada Lovelace and Charles Babbage (PER), the Royal Society (ORG) and London (LOC), each with its position in the text.

Additional Resources​