Sub topic 3
The spaCy pipeline, Doc and Span
This chapter covers the objects you will use in every later spaCy example: the pipeline (Language), the Doc, the Token and the Span. It assumes you can write basic Python and have a rough idea of what tokens are. Entity labels and BIO tags were covered in the previous chapters. Here we only look at how spaCy stores them.
The pipeline: text in, annotated Doc out
In spaCy, nlp is a Language object. It holds a tokenizer and an ordered list of components such as a tagger, parser or entity recognizer. When you call nlp(text), two things happen:
- The tokenizer splits the text into tokens and builds a
Doc. - Each component runs on that same
Docin order. Each one reads what earlier components wrote and adds its own annotations.
The tokenizer is not a pipeline component. It always runs first and cannot be reordered. Components are the part you can list, reorder, add, disable or replace.
import spacy
nlp = spacy.load("en_core_web_sm")
print(nlp.pipe_names)
print(nlp.pipeline[-1])For the small English model, pipe_names is typically ['tok2vec', 'tagger', 'parser', 'attribute_ruler', 'lemmatizer', 'ner']. The exact list depends on the model version. nlp.pipeline is a list of (name, component) pairs, so the last entry is the ner component.
The Doc: tokens plus annotations
A Doc is a sequence of Token objects. Several things about it matter in practice:
- It never loses the original text. Every token stores its character offset, so you can always map back to the source string.
- It is a view over shared data. A token's text is not copied around. The
Docpoints into a sharedVocabthat stores strings once and refers to them by hash. - It is mutable in its annotations, not in its tokens. You can change
doc.ents, but you cannot edit the token text in place.
A blank pipeline contains only the tokenizer. It is a good way to inspect tokenization without downloading a model:
import spacy
nlp = spacy.blank("en")
doc = nlp("Ada Lovelace worked in London.")
for token in doc:
print(token.i, repr(token.text), token.idx, token.is_alpha, token.is_punct)This prints:
0 'Ada' 0 True False
1 'Lovelace' 4 True False
2 'worked' 13 True False
3 'in' 20 True False
4 'London' 23 True False
5 '.' 29 False TrueTwo different position systems appear here:
| Attribute | Meaning | Example for `London` |
|---|---|---|
| `token.i` | Index of the token in the `Doc` | 4 |
| `token.idx` | Character offset of the token's first character in the text | 23 |
| `token.text` | The token's string | `London` |
| `token.whitespace_` | Trailing space, or an empty string | `""` (the full stop follows it directly) |
Mixing up token.i and token.idx is a common source of off-by-many bugs. Token indices count tokens. Character offsets count characters.
Span: a slice of a Doc
A Span is a contiguous range of tokens in a Doc. Entities are spans with a label. You create a span by slicing the Doc, and the slice end is exclusive, like a Python list slice:
import spacy
nlp = spacy.blank("en")
doc = nlp("Ada Lovelace worked in London.")
span = doc[0:2]
print(span.text, span.start, span.end, span.start_char, span.end_char)The output is Ada Lovelace 0 2 0 12. A Span stores both token boundaries (start, end) and character boundaries (start_char, end_char), and it knows its parent through span.doc. It can also carry a label_, and an optional kb_id_ for entity linking, which this tutorial does not use.
Creating spans from character offsets
Annotation tools and datasets usually give character offsets, not token indices. Doc.char_span converts them:
import spacy
nlp = spacy.blank("en")
text = "Ada Lovelace worked in London."
doc = nlp(text)
print(text[23:29])
print(doc.char_span(23, 29, label="GPE"))
print(doc.char_span(1, 12))
print(doc.char_span(1, 12, alignment_mode="expand"))The output is:
London
London
None
Ada Lovelacechar_span returns None when the offsets do not line up with token boundaries. Offset 1 falls inside the token Ada. The alignment_mode argument controls what happens:
"strict"(the default) returnsNonefor misaligned offsets."contract"shrinks the span to the tokens fully inside the offsets."expand"grows the span to cover every token the offsets touch.
Entities live on the Doc
A pretrained or trained ner component writes its predictions to doc.ents, a tuple of labelled Span objects. You can also write to it yourself, which is how rule-based components and conversion scripts work:
import spacy
from spacy.tokens import Span
nlp = spacy.blank("en")
doc = nlp("Ada Lovelace worked in London.")
doc.ents = [
Span(doc, 0, 2, label="PERSON"),
Span(doc, 4, 5, label="GPE"),
]
print([(e.text, e.label_) for e in doc.ents])
for token in doc:
print(token.text, repr(token.ent_iob_), repr(token.ent_type_))The first line prints [('Ada Lovelace', 'PERSON'), ('London', 'GPE')]. The token loop shows how spaCy stores entities internally:
Ada 'B' 'PERSON'
Lovelace 'I' 'PERSON'
worked 'O' ''
in 'O' ''
London 'B' 'GPE'
. 'O' ''This is the BIO scheme from the earlier chapter, stored on each token. ent_iob_ is B, I or O, and ent_type_ is the label. A third value, an empty ent_iob_, means "no entity annotation was set". That is different from O, which means "this token is explicitly not part of an entity".
The no-overlap rule
doc.ents cannot contain overlapping spans. Each token belongs to at most one entity. If you assign overlapping spans, spaCy raises a ValueError. When you need overlapping or nested annotations, such as an organisation name inside a product name, store them in doc.spans, which is a dictionary of span groups:
import spacy
from spacy.tokens import Span
nlp = spacy.blank("en")
doc = nlp("Ada Lovelace worked in London.")
doc.spans["candidates"] = [doc[0:2], doc[0:1], doc[4:5]]
print([s.text for s in doc.spans["candidates"]])Entities in doc.ents come from the ner component. Span groups in doc.spans are for any annotation that may overlap, and the standard ner component does not write to them.
Processing many texts
Calling nlp(text) in a loop works but is slow. nlp.pipe processes texts in batches and streams results lazily. It also lets you carry metadata along with each text using as_tuples=True:
import spacy
nlp = spacy.load("en_core_web_sm", disable=["parser", "lemmatizer"])
records = [
("Apple opened an office in Austin.", {"id": 1}),
("Maria joined the United Nations in 2019.", {"id": 2}),
]
for doc, meta in nlp.pipe(records, as_tuples=True, batch_size=32):
print(meta["id"], [(e.text, e.label_) for e in doc.ents])Disabling parser and lemmatizer at load time saves memory and time when you only need entities, because the entity recognizer does not read the parser's output. The cost is that doc.sents and token lemmas are no longer available. Accessing doc.sents without a sentence boundary source raises an error. For temporary changes, use a context manager:
import spacy
nlp = spacy.load("en_core_web_sm")
with nlp.select_pipes(enable="ner"):
doc = nlp("Satya Nadella leads Microsoft.")
print([(e.text, e.label_) for e in doc.ents])For large corpora, nlp.pipe(..., n_process=4) uses multiple processes. It adds start-up cost per process and is only worth it for big inputs. Output order is preserved.
Common errors
- Using
token.iwhere a character offset is needed, or the reverse. Check which ofi,idx,startandstart_charan API expects. - Forgetting that slices are end-exclusive.
doc[0:2]has two tokens.doc[4:5]is the single token at index 4. - Assuming a blank pipeline predicts anything.
spacy.blank("en")has noner, sodoc.entsis empty. - Reading
doc.sentsortoken.lemma_after disabling the components that produce them. - Calling
nlp(text)on every row of a large dataset instead ofnlp.pipe. - Treating
span.label_as an integer.span.labelis the integer hash andspan.label_is the string.
Exercise
A dataset gives the entity "Lovelace" in "Ada Lovelace worked in London." as the character range (5, 12), starting one character too late. Using spacy.blank("en"), what does doc.char_span(5, 12) return with the default alignment mode, and what does it return with alignment_mode="expand"? Why does this matter when you prepare training data?
Show answer
With the default "strict" mode, char_span(5, 12) returns None, because offset 5 is inside the token Lovelace (which starts at 4). With "expand", it returns the span Lovelace, because the span grows to cover every token the offsets touch. This matters because a None that is silently dropped removes an annotation from your training data, and one that is passed to doc.ents causes an error. Check for None values and count how many are dropped, so you can find and fix the offsets instead of losing labelled examples.