Named Entity Recognition
NER finds spans of text that refer to real-world entities — people, places, organizations, dates — and labels them, turning unstructured text into structured facts that downstream systems can query.
Why Does This Exist?
Most useful information in text is attached to real-world entities: who did what, when, where, and to whom? Named Entity Recognition (NER) locates and classifies named spans, turning unstructured text into structured (span, entity-type) pairs — the raw material for knowledge graph construction, question answering, and event extraction.
Without NER, a sentence like "Barack Obama visited Berlin on Tuesday" is just a string of characters. With NER, it becomes three structured facts: {person: Barack Obama}, {location: Berlin}, {date: Tuesday}. This transformation is the bridge between human-readable language and machine-actionable data.
Historically, before deep learning, extracting these entities required brittle, hand-crafted rules or extensive gazetteers (massive lists of names and places). These systems broke constantly. If a rule looked for capitalization, it failed on informal text. If it relied on a gazetteer, it failed on any new company or obscure town not in its database. Modern NER systems solve this by learning the context around an entity, allowing them to confidently identify "Snapchat" as an organization or "Zendaya" as a person even if the model has never seen those specific words before.
Think of It Like This
Highlighting a news article
Imagine reading a Reuters article and highlighting every person's name in yellow, every company in blue, every location in green, every date in orange. NER does that automatically across millions of documents, consistently and at machine speed. The result: structured facts like (Tim Cook, PER), (Apple, ORG), (Cupertino, LOC), (Monday, DATE).
Just as a human reader knows that "Apple" refers to a company rather than a fruit because of surrounding words like "revenue" or "CEO", an NER model uses surrounding context to apply the correct highlight color.
How It Actually Works
The BIO tagging scheme
NER is classically framed as per-token classification using BIO tags. This formulation allows a model to naturally handle multi-word entities without needing a complex bounding-box mechanism. The tags are:
- B-TYPE: Beginning of an entity span (e.g., B-PER)
- I-TYPE: Inside (continuation of) an entity span (e.g., I-PER)
- O: Outside any entity span
For the sentence "Tim Cook visited New York City":
- Tim → B-PER
- Cook → I-PER
- visited → O
- New → B-LOC
- York → I-LOC
- City → I-LOC
This scheme handles multi-token entities cleanly while remaining a standard sequence classification problem. By predicting these tags per token, the model implicitly defines both the boundary of the entity and its classification type.
Standard entity types
Instead of a markdown table, standard entity types are typically grouped into these common categories:
- PER (Person): "Marie Curie" or "Barack Obama"
- ORG (Organization): "Google DeepMind" or "United Nations"
- LOC (Location): "Mount Everest" or "Pacific Ocean"
- GPE (Geo-political entity): "France", "Paris", or "California"
- DATE (Temporal expression): "last Tuesday", "Q3 2024", or "1999"
- MONEY (Monetary value): "$4.2 billion" or "100 euros"
- PRODUCT (Product name): "iPhone 15 Pro" or "Boeing 747"
Model architecture
Modern NER typically uses a three-stage pipeline to convert text into tags:
- Pre-trained encoder (like BERT, RoBERTa, or DeBERTa): This produces contextual token embeddings that capture meaning from both sides of each token. Unlike static embeddings, a contextual embedding knows the difference between "Apple" the fruit and "Apple" the company.
- Linear projection: A simple feed-forward layer maps the high-dimensional embedding dimension down to the number of BIO tags, producing a set of tag scores (logits) for each position in the sentence.
- CRF layer (Conditional Random Field): This layer enforces valid tag sequences. A neural network outputting independent tags might accidentally predict
I-ORGimmediately following aB-PER. A CRF learns transition probabilities and strictly enforces rules like "B-X must start a span" and "I-Y must follow B-Y or I-Y". It is trained jointly with the encoder via Viterbi decoding during inference.
State-of-the-art models built on these architectures routinely achieve an F1 score above 90 on the CoNLL-2003 benchmark for news text.
Code
This snippet demonstrates how to use the popular spacy library to perform named entity recognition. Notice how the extracted entities form exact contiguous spans of text alongside their predicted labels.
import spacy
# Load the small English modelnlp = spacy.load("en_core_web_sm")
text = """Satya Nadella, CEO of Microsoft, announced a $10 billion investmentin OpenAI at a conference in San Francisco on Tuesday."""
doc = nlp(text)
# -> Satya Nadella PERSON # -> Microsoft ORG # -> $10 billion MONEY # -> OpenAI ORG # -> San Francisco GPE # -> Tuesday DATE for ent in doc.ents: print(f"{ent.text:<35} {ent.label_:<10}")For higher accuracy, transformer-based pipelines are typically used. Here is an example using Hugging Face Transformers.
from transformers import pipeline
# The aggregation_strategy="simple" flag reconstructs whole words from subword tokensner = pipeline("ner", model="dslim/bert-base-NER", aggregation_strategy="simple")
results = ner("Elon Musk founded SpaceX in Hawthorne, California in 2002.")# -> Elon Musk PER score=0.998# -> SpaceX ORG score=0.997# -> Hawthorne LOC score=0.992# -> California LOC score=0.998for entity in results: print(f"{entity['word']:<20} {entity['entity_group']:<8} score={entity['score']:.3f}")Watch Out For
Entity boundary errors
NER systems frequently miss span boundaries — such as tagging "New York City" as just "New York", or incorrectly including a title in a person span ("Dr. Jane Smith" extracted as "Dr. Jane Smith" instead of just "Jane Smith"). These errors aggressively propagate to downstream systems, breaking knowledge graphs and search features. Evaluate precision and recall per entity type, and strongly consider introducing a span-boundary review step for high-stakes applications like medical or legal extraction.
Domain shift in specialized text
A general-purpose model trained on Wall Street Journal news text will aggressively miss gene names (BRCA1), experimental drug names (Imatinib), and legal citations (42 U.S.C. § 1983). Do not deploy a news-trained NER model on scientific literature. Use domain-specific pre-trained models (such as BioBERT for biomedical text or LegalBERT for legal text) or comprehensively fine-tune on annotated in-domain data. You will often need to define and expand the entity type set to match your specific domain requirements.
The Quick Version
- Named Entity Recognition locates spans of text naming real-world entities and classifies them by type (PER, ORG, LOC, DATE).
- The BIO tagging scheme frames span labeling as a token-level classification problem: B-TYPE for the beginning, I-TYPE for the continuation, and O for outside.
- Modern architectures stack a CRF layer on top of a pre-trained contextual encoder (like BERT) to enforce valid tag sequence transitions.
- Strong models achieve F1 > 90% on standard news benchmarks, but performance degrades heavily under domain shift.
- The structured output of (span, type) pairs provides the crucial raw input that feeds knowledge graphs, QA systems, and event extraction pipelines.