Sub topic 4
Extracting entities with a pretrained spaCy model
This chapter shows how to run a pretrained spaCy English pipeline over text and read its entity predictions. You can then inspect them at the span and token level, and process many texts efficiently. It assumes you can run Python in a virtual environment and install packages with pip. It also assumes you know what a token is and have seen the span and BIO ideas from the previous chapters.
What you get when you load a model
A spaCy pretrained pipeline is a package of trained components that run in order on a text. Install the small English pipeline once:
pip install spacy
python -m spacy download en_core_web_smCalling spacy.load("en_core_web_sm") returns an nlp object. Calling nlp(text) runs the tokenizer first and then each pipeline component. The result is a Doc, a sequence of tokens with annotations attached. The ner component writes its predictions onto the Doc.
The ner component is only one stage. You can list the stages with nlp.pipe_names. The pipeline also does part-of-speech tagging and dependency parsing, which you often don't need for entity extraction. We will switch those off later.
Reading entities from a Doc
The first example loads the model, runs a sentence through it, and prints each entity with its character offsets and label.
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 should be:
Apple 0 5 ORG
U.K. 29 33 GPE
$1 billion 46 56 MONEYdoc.ents is a tuple of Span objects. A span is a slice of the Doc with a label. The character offsets index into the original string, so doc.text[29:33] gives "U.K.". Exact predictions can differ slightly between model versions, so treat the labels above as typical rather than guaranteed.
Entities never overlap in doc.ents. Each token belongs to at most one entity. If you need overlapping or nested spans, spaCy provides doc.spans for that, but the standard NER component does not write there.
Useful Span attributes
A Span carries more than text and a label. These are the ones you will use most:
| Attribute | Meaning |
|---|---|
| `ent.text` | The covered text as a string |
| `ent.label_` | The label as a string, such as `ORG` |
| `ent.label` | The label as an integer hash |
| `ent.start`, `ent.end` | Token indices into the `Doc` (end is exclusive) |
| `ent.start_char`, `ent.end_char` | Character offsets into `doc.text` |
| `ent.sent` | The sentence containing the span (needs sentence boundaries) |
Be careful with start and end. They count tokens, not characters. Mixing the two is a common source of off-by-N bugs when you convert spaCy output to another format.
The label scheme
The English pipelines are trained on the OntoNotes 5 corpus, which defines 18 entity types. Some labels are not obvious from their names. spacy.explain returns a short description:
import spacy
nlp = spacy.load("en_core_web_sm")
doc = nlp("The European Commission fined Google 4.3 billion euros on 18 July 2018.")
for ent in doc.ents:
print(f"{ent.text!r:35} {ent.label_:10} {spacy.explain(ent.label_)}")These are the labels you will meet most often:
| Label | Covers | Example |
|---|---|---|
| `PERSON` | People, including fictional ones | Ada Lovelace |
| `ORG` | Companies, agencies, institutions | Microsoft |
| `GPE` | Countries, cities, states | London |
| `LOC` | Non-political locations, such as mountains and rivers | the Alps |
| `NORP` | Nationalities, religious or political groups | Canadian |
| `DATE` | Absolute or relative dates and periods | 18 July 2018 |
| `MONEY` | Monetary values | $1 billion |
| `CARDINAL` | Numerals that fit no other type | three |
The remaining labels are FAC, PRODUCT, EVENT, WORK_OF_ART, LAW, LANGUAGE, TIME, PERCENT, QUANTITY and ORDINAL. You cannot ask a pretrained model for a label it was not trained on. If you need DRUG or INVOICE_NUMBER, you need rules or a custom model, which later chapters cover.
Seeing the BIO tags underneath
Chapter two showed BIO tags. spaCy stores the same information on each token. The ent_iob_ attribute is B, I or O, and ent_type_ holds the label (empty for O).
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_} {token.ent_type_}")For the money entity you will see $ marked B, then 1 and billion marked I, all with type MONEY. This token-level view is useful when you want to compare spaCy output with a BIO-tagged dataset, or to debug why a span boundary looks wrong. Spans are always whole-token units. spaCy cannot predict an entity that starts in the middle of a token.
Checking and visualising predictions
displacy renders entities as highlighted text. In a notebook it displays inline. In a script, ask for the HTML string:
import spacy
from spacy import displacy
nlp = spacy.load("en_core_web_sm")
doc = nlp("Marie Curie won the Nobel Prize in Paris in 1903.")
html = displacy.render(doc, style="ent", jupyter=False)
with open("entities.html", "w", encoding="utf-8") as f:
f.write(html)Open entities.html in a browser to see the labelled spans. This is a quick way to review a sample of predictions by eye before you trust a model on your data.
Processing many texts efficiently
Calling nlp(text) in a loop works but is slow for large collections. nlp.pipe processes texts in batches and streams the results. You can also skip components you do not need.
import spacy
from collections import Counter
nlp = spacy.load("en_core_web_sm", disable=["parser", "lemmatizer"])
texts = [
"Tim Cook presented the new iPhone in Cupertino.",
"Lagos is the largest city in Nigeria.",
"The WHO met in Geneva on Monday.",
]
counts = Counter()
for doc in nlp.pipe(texts, batch_size=50):
for ent in doc.ents:
counts[ent.label_] += 1
print(counts.most_common())Two details matter here:
- Disabling
parserremoves sentence boundaries, soent.sentwill raise an error. If you need sentences, keep the parser or add the lightweightsentencizercomponent. - In
en_core_web_sm, thenercomponent has its own internal encoder, so it works with the tagger and parser turned off. Components that share an upstreamtok2veccan break when you disable the shared layer. Checknlp.pipe_namesandnlp.disabledafter loading.
For very large jobs, nlp.pipe(..., n_process=4) uses multiple processes. It helps on CPU-bound workloads but adds start-up cost and does not work well for tiny inputs.
Choosing a pretrained package
The English family comes in several sizes. They share the same API, so you change only the string passed to spacy.load.
| Package | Character | Typical use |
|---|---|---|
| `en_core_web_sm` | Small and fast, no static word vectors | Prototypes, low-memory environments |
| `en_core_web_md` | Adds word vectors | Slightly better accuracy at modest cost |
| `en_core_web_lg` | Larger vectors | Better accuracy, higher memory use |
| `en_core_web_trf` | Transformer-based | Highest accuracy, slower, benefits from a GPU |
The transformer package is installed with python -m spacy download en_core_web_trf. A later chapter covers how it works. For now, note that the code you write against doc.ents does not change.
Common errors and gotchas
- Missing model.
OSError: [E050] Can't find model 'en_core_web_sm'means the package is not installed in the active environment. Run the download command in the same virtual environment you run Python from. - Version mismatch. A model trained for one spaCy minor version can warn or fail on another. Check
spacy.__version__andnlp.meta["version"]when results look odd. - Empty results.
doc.entsis an empty tuple when nothing is found. Always loop over it rather than indexingdoc.ents[0]. - Case and formatting sensitivity. The model uses capitalisation and context.
"apple released a phone"in lowercase may lose theORGprediction. Text in ALL CAPS, or noisy text from social media or OCR, can also hurt. - Domain shift. A model trained on news may mislabel medical, legal or code-heavy text. Spot-check on your own data before relying on it.
- Ambiguity.
Washingtoncan be aPERSON, aGPEor anORG. The model picks from context, and it can be wrong. - Whole-text limits. Very long documents use memory and can exceed
nlp.max_length(one million characters by default). Split long text into chunks, for example by paragraph, and run those throughnlp.pipe.
Summary of the workflow
- Install the package and load it with
spacy.load. - Call
nlp(text)for one text ornlp.pipe(texts)for many. - Read
doc.ents, usinglabel_,textand the character offsets. - Review samples with
displacy, and compare token-level BIO attributes when you need to. - Disable unused components for speed, keeping any that your later code depends on.
Exercise
You run nlp = spacy.load("en_core_web_sm") on 10,000 short product reviews and want the number of ORG and PRODUCT entities. You do not need part-of-speech tags, parses or sentences. Describe how you would load the model and count entities efficiently, and name one thing that would break if you also wanted ent.sent.
Show answer
Load with spacy.load("en_core_web_sm", disable=["parser", "lemmatizer"]), then iterate with for doc in nlp.pipe(reviews, batch_size=50):. For each ent in doc.ents, if ent.label_ is ORG or PRODUCT, increment a collections.Counter keyed by the label. Disabling the parser also removes sentence boundaries, so accessing ent.sent would raise an error. To keep it you would leave the parser enabled or add the sentencizer component.