Sub topic 1
Named Entity Recognition: What It Predicts
Prerequisites
This chapter assumes you know basic Python, can install packages with pip, and understand that text is split into tokens. You need Python 3.8 or later, and you must install spaCy and its English model:
pip install spacy
python -m spacy download en_core_web_smWhat named entity recognition predicts
Named entity recognition (NER) finds the spans of text that refer to real-world things, such as people, organizations, places, dates, and amounts of money. It also assigns each span a label, called an entity type. A model does not return a list of strings. It returns the position of each span in the text plus its type.
Entity spans and BIO tags
Most NER systems label each token with a BIO tag. B marks the beginning of an entity, I marks a token inside an entity, and O marks a token outside any entity. For "New York City" tagged as a location, the tags are B-GPE, I-GPE, I-GPE. A span is the group of tokens that share one entity. Because the tags encode boundaries, a model can recover the full span even when an entity has several words.
The spaCy pipeline, Doc and Span
spaCy runs text through a pipeline of components. Calling nlp(text) returns a Doc object that holds the tokens and the predictions. A Span is a slice of a Doc, and doc.ents is a tuple of Span objects. Each entity span exposes .text, .label_, .start_char, and .end_char, so you can link each prediction back to the original string.
Extracting entities with a pretrained spaCy model
The following script loads the small English pipeline 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 model usually finds "Apple" as an organization, "U.K." as a geopolitical entity, and "$1 billion" as money. Exact labels can vary with the model version, so check the output on your own machine.
Exercise
Exercise
In the BIO scheme, what tags does the two-word entity "Ada Lovelace" receive if it is a person?
Show answer
B-PERSON for "Ada" and I-PERSON for "Lovelace", with O for every token outside the name. (spaCy's default label set uses PERSON, so the tags are B-PERSON and I-PERSON.)