Sub topic 1
What named entity recognition predicts
Named entity recognition (NER) takes raw text and returns a list of spans, each with a label. A span is a contiguous stretch of text, such as Apple or $1 billion. The label says what kind of thing the span refers to, such as an organization or an amount of money. This chapter defines that output precisely. It also covers where the label sets come from and which errors to expect.
Prerequisites
This chapter assumes you have:
- Basic Python, including functions, loops and installing packages with pip.
- Familiarity with tokens and simple text processing, such as splitting text into words.
- A general idea of what a neural network classifier does: it maps an input to one of a fixed set of classes.
To run the code you need spaCy and its small English model:
pip install spacy
python -m spacy download en_core_web_smThe task: text in, labeled spans out
NER is a structured prediction task. The input is a string. The output is a set of entities, and each entity has three parts:
- A start position in the text.
- An end position in the text.
- A label drawn from a fixed label set.
Positions are usually character offsets, where the end is exclusive. Some libraries report token indices instead. Check which one you have before you compare results from two tools.
Most NER systems are trained as token classifiers. Internally they assign a tag to each token. Your application usually wants the spans, so the tags are converted back into spans. The next chapter covers that conversion, called BIO tagging. For now, treat the span list as the real output.
Entity types depend on the label scheme
NER does not have one universal set of types. The label set comes from the dataset the model was trained on. Two common schemes look quite different:
| Scheme | Typical labels | Notes |
|---|---|---|
| CoNLL-2003 | PER, ORG, LOC, MISC | Four types, news text. Many Hugging Face NER models use it. |
| OntoNotes 5 | PERSON, ORG, GPE, LOC, DATE, MONEY, PRODUCT, NORP, CARDINAL and others | 18 types. spaCy's English pipelines use it. |
| Custom | Anything you define, such as DRUG, GENE or INVOICE_NO | Needs your own annotated data or rules. |
Two details cause trouble in practice:
- GPE versus LOC. In OntoNotes, GPE (geopolitical entity) covers countries, cities and states. LOC is for other places, such as mountains or rivers. CoNLL has only LOC, so the same city gets a different label under each scheme.
- Non-name entities. OntoNotes includes dates, money, percentages and numbers. These are not names, but the same span-labeling machinery handles them.
You can list the labels a spaCy model knows and print a short description of each:
import spacy
nlp = spacy.load("en_core_web_sm")
for label in nlp.get_pipe("ner").labels:
print(label, "-", spacy.explain(label))Always check the label set before you evaluate or compare models. A model trained on CoNLL cannot output MONEY, so it cannot be scored fairly on a task that needs it.
A first example
This script runs a pretrained pipeline and prints each entity with its character offsets:
import spacy
nlp = spacy.load("en_core_web_sm")
doc = nlp("Apple is looking at buying a U.K. startup for $1 billion.")
for ent in doc.ents:
print(ent.text, ent.start_char, ent.end_char, ent.label_)The output is typically:
Apple 0 5 ORG
U.K. 29 33 GPE
$1 billion 46 56 MONEYExact results can vary with the model version. Three things to notice:
Appleis an organization here, not a fruit. The model uses the surrounding words to decide.$1 billionis one span even though it contains several tokens.- Words such as
startupget no label. Most tokens belong to no entity, which matters for evaluation later.
Slicing the original text with the offsets returns the entity string. text[29:33] gives U.K.. The span is anchored to the original text, not to a cleaned-up copy.
From spans to per-token tags
The model works token by token, so spaCy exposes the per-token view too. Each token carries an entity-boundary flag and an entity type:
import spacy
nlp = spacy.load("en_core_web_sm")
doc = nlp("Apple is looking at buying a U.K. startup for $1 billion.")
for token in doc:
print(f"{token.text:<10} {token.ent_iob_:<2} {token.ent_type_}")The flag ent_iob_ is B for the first token of an entity, I for a later token inside one, and O for a token outside every entity. $1 billion is tokenized as $, 1 and billion. The first gets B and the other two get I, all with type MONEY. This is the same information as the span list in a different form. The next chapter explains why systems use this form.
Why NER is hard
NER looks like a lookup problem, but a dictionary of names fails quickly. The label depends on the context.
- Ambiguous strings.
Washingtoncan be a person, a city, a state or a government.Jordancan be a country or a person. The model must read the sentence. - Unseen names. New companies, products and people appear constantly. A model has to generalize from cues such as capitalization, position, and words like
Inc.orDr. - Boundary decisions. Is the entity
Bank of AmericaorAmerica? Is itPresident BidenorBiden? Annotation guidelines settle these questions, and models inherit those choices. - Surface cues are unreliable. Capitalization helps in news text. It fails in tweets, in all-caps headlines and in lowercase search queries.
- Domain shift. A model trained on news may miss drug names in clinical notes or part numbers in support tickets.
What NER does not do
NER is often confused with neighboring tasks. It stops at finding and typing mentions.
- Entity linking maps a mention to a specific record, such as a Wikipedia page. NER only says "this is a PERSON".
- Coreference resolution decides that
Ada Lovelace,sheandthe mathematicianrefer to the same person. NER does not group mentions. - Relation extraction finds links between entities, such as "works for". It usually runs after NER.
- Normalization turns
$1 billioninto1000000000 USD, ornext Fridayinto a date. NER marks the span and leaves the value to you.
Keeping these separate helps you debug. If your pipeline merges two people with the same name, that is a linking or coreference problem, not an NER bug.
Kinds of errors
Once you evaluate a model, you will see the same four failure types:
| Error | Example | What went wrong |
|---|---|---|
| Missed entity | `Kiro` gets no label | The model predicted nothing for a true entity (false negative). |
| Spurious entity | `Monday` tagged as ORG | The model predicted an entity that is not there (false positive). |
| Wrong type | `Paris` tagged PERSON | The span is right and the label is wrong. |
| Wrong boundary | `Bank of` tagged ORG | The type may be right, but the start or end is off. |
A boundary error and a type error each make the prediction wrong when you score entities as whole spans. The evaluation chapter shows how to count them. Looking at which error type dominates tells you what to fix. Missed entities often point to a vocabulary or domain gap. Boundary errors often point to inconsistent annotation guidelines.
Where the rest of the tutorial goes
You now have the vocabulary for the remaining chapters. A model predicts a label for every token, and those labels are decoded into labeled spans. The same task can be solved with rules, with spaCy's statistical models, or with a fine-tuned transformer. The chapters differ in how they produce the tags and in how much annotated data they need. They all produce the same span-level output you saw in doc.ents, which is why you can compare them with one set of metrics.
Exercise
Run the first example on the sentence "Jordan visited Jordan last June." and inspect the output. Then answer: why can the two occurrences of "Jordan" get different labels, and what does this show about NER compared with a name dictionary?
Show answer
A typical result tags the first "Jordan" as PERSON and the second as GPE, and "last June" as DATE. Exact labels vary by model version, so check your own output. The labels differ because the model uses the surrounding words (the subject position before "visited" versus the object position after it) to choose a type. A dictionary maps each string to one label, so it would give both occurrences the same label. NER predicts a label for each mention in its context, not for each string.
Exercise
A model trained on CoNLL-2003 labels a sentence as "Berlin" LOC. A model trained on OntoNotes labels it "Berlin" GPE. Is one of them wrong? How should this affect the way you compare the two models?
Show answer
Neither is necessarily wrong. The two datasets use different label sets and different definitions: CoNLL has no GPE type, and OntoNotes splits places into GPE and LOC. To compare the models fairly, map both label sets onto a shared one (for example, collapse GPE and LOC to LOC) or score each model on test data annotated with its own scheme.
Exercise
A model predicts the span "Bank of" with label ORG, and the gold annotation is "Bank of America" with label ORG. Name the error type, and say whether the prediction counts as correct when entities are scored as whole spans.
Show answer
This is a boundary error. The label matches but the end offset does not. Under whole-span scoring it is not correct, so it counts as both a false positive (the predicted span) and a false negative (the missed gold span).