AI
Named Entity Recognition (NER): How It Works
Named entity recognition (NER) finds names of people, companies, places, dates and amounts in text. How it works, NER model examples in Python, and uses.
Named entity recognition (NER) is the natural language processing task of finding names of real-world things in text and labeling what kind of thing each one is: a person, an organization, a location, a date, an amount of money, a product and so on. Given "Maya Chen joined Acme in Berlin in March", an NER model marks "Maya Chen" as a person, "Acme" as an organization, "Berlin" as a location and "March" as a date. It turns unstructured text into structured data you can search, count and act on, which is why it sits inside contract review tools, privacy filters, search engines and news analysis.
This guide explains what named entity recognition is, how NER models work, common entity types and tagging schemes, an NER model example in Python, how LLMs change the picture, how to measure accuracy, and the main use cases and limits.
What Is Named Entity Recognition?
What is named entity recognition at its core? It's two jobs done together:
- Finding the boundaries of each entity: which words belong to the name ("New York Stock Exchange" is one entity, not three).
- Classifying the type of each entity: person, organization, location, and so on.
A "named entity" is usually a proper name, but most systems also extract other useful spans with a clear type, such as dates, times, percentages, money amounts and quantities. NER is closely related to, but different from, entity linking, which decides which real-world entity a name refers to (for example, whether "Paris" means the city in France or a person named Paris).
What Is NER in NLP?
What is NER in NLP terms? It's a token classification task: the model assigns a label to each token (word or subword) in the text, and adjacent tokens with matching labels form an entity. It's one of the core building blocks of natural language processing, often used as a step before other tasks such as relation extraction ("who works for which company"), question answering and knowledge graph building. Our overview of natural language processing shows where NER fits among other NLP tasks.
Common Entity Types
Different datasets and tools define different label sets. The two most common:
| Label set | Entity types | Where you'll see it |
|---|---|---|
| CoNLL-2003 | PER (person), ORG (organization), LOC (location), MISC (miscellaneous) | Classic benchmark; many fine-tuned BERT NER models |
| OntoNotes 5 (18 types) | PERSON, NORP (nationalities, religious or political groups), FAC (buildings, airports), ORG, GPE (countries, cities, states), LOC, PRODUCT, EVENT, WORK_OF_ART, LAW, LANGUAGE, DATE, TIME, PERCENT, MONEY, QUANTITY, ORDINAL, CARDINAL | spaCy's English pipelines and many production systems |
| Domain-specific | Drug, dosage, disease, gene; or clause, party, governing law; or account number, email, phone | Medical, legal and privacy tools |
Note the difference between LOC and GPE in OntoNotes: GPE covers places with governments (countries, cities, states), while LOC covers other locations such as mountains and rivers.
How NER Works: Tagging Schemes
Most NER models label each token with a tag that says whether it starts an entity, continues one, or is outside any entity. The most common scheme is BIO (also called IOB):
| Token | Maya | Chen | joined | Acme | Corp | in | Berlin |
|---|---|---|---|---|---|---|---|
| Tag | B-PER | I-PER | O | B-ORG | I-ORG | O | B-LOC |
- B- marks the beginning of an entity.
- I- marks a token inside an entity.
- O marks tokens outside any entity.
This lets the model represent multi-word entities and two entities of the same type next to each other. Some systems use richer schemes (BIOES adds "end" and "single" tags), but the idea is the same.
Approaches to Named Entity Recognition
| Approach | How it works | Strengths | Weaknesses |
|---|---|---|---|
| Rules and dictionaries | Regular expressions, lists of known names (gazetteers), patterns | Precise for fixed formats like emails, IDs and dates; no training data | Breaks on new names and varied wording |
| Classic machine learning | Statistical models such as conditional random fields over hand-made features | Efficient, explainable | Needs feature engineering and labeled data |
| Deep learning | Recurrent networks and, today, fine-tuned transformer encoders such as BERT | High accuracy; learns from context | Needs labeled data for the label set you want |
| Large language models | Prompting an LLM to return entities, often as JSON | Works with any label set from instructions; no training | Slower and costlier; can miss or invent spans; needs validation |
In practice, many systems combine approaches: rules for strictly formatted items (an IBAN or an email address), a fine-tuned model for names, and sometimes an LLM for unusual entity types.
NER Model Example in Python
Here's an NER model example using Hugging Face Transformers. The model, dslim/bert-base-NER, is a BERT model fine-tuned on the English CoNLL-2003 dataset, and its model card says it recognizes four entity types: location (LOC), organization (ORG), person (PER) and miscellaneous (MISC).
from transformers import pipeline
ner = pipeline(
"token-classification",
model="dslim/bert-base-NER",
aggregation_strategy="simple",
)
text = "Maya Chen joined Acme Corp in Berlin after five years at Siemens."
for entity in ner(text):
print(entity["word"], entity["entity_group"], round(entity["score"], 2))The aggregation_strategy="simple" setting merges subword tokens and B/I tags into whole entities, so you get "Maya Chen" as one person rather than separate pieces. Each result includes the entity text, its group (PER, ORG, LOC or MISC), a confidence score, and its start and end positions in the text, which you can use to highlight or redact it.
For named entity recognition Python projects, the main libraries are:
- Hugging Face Transformers: thousands of pre-trained NER models, and tools to fine-tune your own on custom labels.
- spaCy: fast production pipelines with an OntoNotes-style entity recognizer, plus rule-based matching you can combine with the model.
- NLTK: a classic toolkit, useful for learning but less accurate than modern models.
- Flair, Stanza and GLiNER: other well-known options; GLiNER-style models can recognize entity types you name at prediction time.
Training a Custom NER Model
Pre-trained models only know their training labels. If you need entities such as "contract party", "drug dosage" or "product SKU", you'll usually fine-tune:
- Define the label set with clear written rules for edge cases ("is 'the Board' an organization?").
- Annotate examples: a few hundred to a few thousand sentences, marking spans and labels. Annotation tools speed this up, and an LLM can pre-label drafts for people to correct.
- Fine-tune a transformer encoder for token classification.
- Evaluate on held-out data (see below), look at errors by entity type, and add examples where the model is weak.
- Combine with rules for formats that are easier to match exactly.
Named Entity Recognition With LLMs
Large language models can do NER from a prompt: "Extract all people, companies and amounts from this text and return them as JSON." This is useful when your entity types change often, you have no labeled data, or the entities need judgment (for example, "obligations of the supplier"). Asking for structured output with a schema makes the results easier to validate; our guide to LLM JSON output covers how.
The trade-offs: LLMs are slower and more expensive per document than a small fine-tuned model, they may return entities that aren't in the text, and their exact span positions can be unreliable. A common pattern is to prototype with an LLM, use it to pre-label training data, then train a small NER model for high-volume production.
How to Evaluate an NER Model
NER is usually evaluated at the entity level, not the token level: an entity counts as correct only if both its boundaries and its type match the reference exactly.
| Metric | Meaning |
|---|---|
| Precision | Of the entities the model found, how many were correct |
| Recall | Of the entities in the text, how many the model found |
| F1 score | The harmonic mean of precision and recall |
Report these per entity type. A model can score well overall but badly on a rare type that matters to you. Libraries such as seqeval compute these scores from BIO-tagged predictions. Also test on text from your own domain and time period: research on NER has found that performance drops noticeably on entities not seen in training and on text from a different genre or era.
Named Entity Recognition Use Cases
- Privacy and compliance: detect names, addresses, phone numbers and account details so they can be redacted before documents are shared or sent to an AI model. Our guide to AI privacy covers why that matters.
- Contract and document review: pull out parties, dates, amounts and governing law.
- Customer support: extract product names, order numbers and locations from tickets to route and analyze them.
- Healthcare: identify drugs, doses, conditions and procedures in clinical notes.
- Finance and news: track mentions of companies, people and events across articles and filings.
- Search and recommendations: index content by the entities it mentions, so users can filter by company, place or person.
- Knowledge graphs: NER plus relation extraction turns documents into connected facts.
Limits and Common Mistakes
- Ambiguity: "Apple" the company vs the fruit, "Jordan" the country vs a person.
- New names: startups, products and people that didn't exist in the training data.
- Domain shift: a news-trained model does poorly on medical notes or legal contracts.
- Nested entities: "Bank of America Stadium" contains an organization inside a facility name; simple BIO tagging can't represent both.
- Inconsistent labeling guidelines, which make training data contradict itself.
- Trusting confidence scores blindly; calibrate thresholds on your own data.
FAQ
What is named entity recognition in simple terms?
Named entity recognition is an NLP technique that finds names and other key items in text, such as people, companies, places, dates and amounts, and labels what type each one is. It turns free text into structured information.
What is an example of named entity recognition?
In the sentence "Tim Cook announced new products in Cupertino on Tuesday", an NER system labels "Tim Cook" as a person, "Cupertino" as a location and "Tuesday" as a date. Many systems would also tag the company if it were named, such as "Apple" as an organization.
What are the main types of named entities?
Common types are person, organization and location, plus dates, times, money, percentages and quantities. The CoNLL-2003 dataset uses four types (person, organization, location, miscellaneous); the OntoNotes scheme used by spaCy has 18.
How do I do named entity recognition in Python?
The quickest way is a pre-trained model: use spaCy's English pipeline or the Hugging Face Transformers token-classification pipeline with an NER model. To recognize your own entity types, annotate examples and fine-tune a transformer model.
Can large language models do named entity recognition?
Yes. You can prompt an LLM to extract entities and return them as structured data, which works without training data and with any entity types. For high volumes or strict accuracy, a fine-tuned NER model is usually faster, cheaper and more consistent.