Sub topic 4
Extracting Entities with a Pretrained spaCy Model
This chapter assumes basic Python, familiarity with tokens, and a general idea of how a neural-network classifier labels text. You will use a pretrained spaCy pipeline to detect named entities without training a model.
What a pretrained NER model does
Named entity recognition, or NER, finds spans of text that refer to things such as people, organizations, places, dates, or money. A pretrained model has already learned these patterns from labelled examples.
spaCy represents processed text with three useful objects:
Languageis the loaded processing pipeline.Docis the complete processed document.Spanis a continuous section of aDoc, such as one detected entity.
The pipeline usually tokenizes text first and then passes the tokens to components. The ner component predicts entity spans and labels. Each detected entity has its original text, a label, and character offsets.
Common labels in the English model include:
| Label | Meaning | Example |
|---|---|---|
| `PERSON` | A person | `Ada Lovelace` |
| `ORG` | An organization | `Microsoft` |
| `GPE` | A country, city, or state | `London` |
| `MONEY` | A monetary value | `$1 billion` |
| `DATE` | A date or time expression | `next Tuesday` |
The exact label set and accuracy depend on the model you load.
Install and load the model
Install spaCy and download its small English pipeline from a terminal:
pip install spacy
python -m spacy download en_core_web_smThe following program loads the model, processes a sentence, and prints every detected entity:
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_,
ent.label,
)A typical result includes entities similar to these:
Apple 0 5 ORG 383
U.K. 39 43 GPE 384
$1 billion 63 73 MONEY 394The offsets use Python's normal zero-based convention. start_char points to the first character, and end_char points just after the final character. Therefore, doc.text[ent.start_char:ent.end_char] reproduces the entity text.
ent.label_ is the readable label name. ent.label is spaCy's numeric identifier for that label. Use label_ when displaying or storing results because it is easier to understand.
Inspect tokens and spans
NER operates alongside tokenization. You can inspect the tokens that make up a document:
for token in doc:
print(token.text, token.idx, token.pos_)
for ent in doc.ents:
print(f"{ent.text!r}: {ent.start}..{ent.end}")token.idx is the token's character start offset. ent.start and ent.end are token indexes, with ent.end being exclusive. These token offsets differ from the character offsets used by start_char and end_char.
Preserve useful output
For downstream code, convert entities into ordinary dictionaries:
entities = [
{
"text": ent.text,
"label": ent.label_,
"start": ent.start_char,
"end": ent.end_char,
}
for ent in doc.ents
]
print(entities)This format is convenient for JSON responses, database records, and later evaluation. Keep the offsets when possible. They let you connect a prediction back to the original document without changing its text.
Exercise
How would you extract only organizations from a spaCy Doc?
Show answer
Filter the entities with a list comprehension such as [ent for ent in doc.ents if ent.label_ == "ORG"].