Sub topic 1
Loading a Pipeline and Creating a Doc
This chapter covers the starting point for everything else in the tutorial. You load a trained spaCy pipeline, pass text through it, and get back a Doc. You will learn what each of those objects is, how the pieces connect, and which mistakes cause the most confusion early on.
Prerequisites
This chapter assumes the following:
- Basic Python, including loops, list comprehensions, and installing packages with
pip. - Familiarity with grammar terms such as noun, verb, subject, and object.
- The ability to run Python in a script or notebook.
- spaCy installed (
pip install spacy) and the small English pipeline downloaded withpython -m spacy download en_core_web_sm.
You do not need prior NLP experience. Later chapters explain part-of-speech tags and dependency relations in detail.
What a pipeline is
A spaCy pipeline is a sequence of steps that turns raw text into a structured object. The first step is always the tokenizer, which splits the text into tokens. After that, a series of components runs in order. Each one reads the Doc and adds annotations to it.
A trained English pipeline such as en_core_web_sm typically contains these components:
| Component | What it adds |
|---|---|
| `tok2vec` | Shared vector representations that other components use |
| `tagger` | Fine-grained tags (`tag_`) and coarse part-of-speech tags (`pos_`) |
| `parser` | Dependency labels (`dep_`), heads, and sentence boundaries |
| `attribute_ruler` | Rule-based fixes and mappings, for example from tags to coarse POS |
| `lemmatizer` | Base forms (`lemma_`) |
| `ner` | Named entities |
The exact list depends on the model and the spaCy version, so check nlp.pipe_names rather than assuming it.
Loading a pipeline
spacy.load takes the name of an installed pipeline package and returns a Language object. By convention this object is called nlp.
import spacy
nlp = spacy.load("en_core_web_sm")
print(type(nlp))
print(nlp.pipe_names)The first line of output is the Language class, which is the object that holds the vocabulary, the tokenizer, and the components. The second line is the list of active component names.
Loading is relatively expensive because spaCy reads model weights from disk. Load the pipeline once at the start of your program and reuse it. Do not call spacy.load inside a loop or inside a function that runs per request.
If the package is not installed, spacy.load raises an OSError that mentions E050 and says it can't find the model. The fix is to run the download command shown in the prerequisites in the same Python environment you use to run your code. A frequent cause is installing into one virtual environment and running from another.
Creating a Doc
Calling nlp on a string runs the full pipeline and returns a Doc.
import spacy
nlp = spacy.load("en_core_web_sm")
doc = nlp("The quick brown fox jumps over the lazy dog.")
print(type(doc))
print(len(doc))
print(doc.text)A Doc is a container of Token objects. It also keeps a reference to the shared vocabulary. len(doc) is the number of tokens, not characters. Note that the final period counts as a token, so this sentence has 10 tokens.
Two properties of a Doc are worth remembering:
- It is non-destructive.
doc.textalways reproduces the original input exactly, including whitespace, because each token records whether a space follows it (token.whitespace_). - Annotations are stored on the
Doc, and tokens are lightweight views into it. ATokendoes not hold its own copy of the data. This keeps memory use low, but it means a token is only meaningful while itsDocexists.
Reading token attributes
Iterating over a Doc yields tokens. Each token exposes the annotations that the pipeline components produced. The following example prints the main ones for every token.
import spacy
nlp = spacy.load("en_core_web_sm")
doc = nlp("The quick brown fox jumps over the lazy dog.")
for token in doc:
print(token.text, token.pos_, token.tag_, token.dep_, token.head.text)Each line shows five values:
token.textis the token as it appeared in the input.token.pos_is the coarse part of speech from the Universal POS tag set, such asNOUNorVERB.token.tag_is the fine-grained tag, such asNNS(plural noun) orVBD(past-tense verb).token.dep_is the dependency label that links the token to its head.token.headis the token this one attaches to. For the root of a sentence, the head is the token itself.
The trailing underscore matters. token.pos is an integer ID, and token.pos_ is the readable string. The same pattern holds for tag, dep, and lemma. Beginners often print the integer version and get numbers like 92. Use the underscore versions when you want text.
Looking up unfamiliar labels
You will meet labels you do not recognize. spacy.explain returns a short description for a POS tag, fine-grained tag, or dependency label, and returns None if the label is unknown.
import spacy
print(spacy.explain("nsubj"))
print(spacy.explain("VERB"))
print(spacy.explain("NNS"))Build this habit early. Label names are compact, and the tag sets differ between languages and models, so checking the description is faster and safer than guessing.
Slices, spans, and the shape of a Doc
You can index a Doc like a list. A single index gives a Token, and a slice gives a Span.
import spacy
nlp = spacy.load("en_core_web_sm")
doc = nlp("The quick brown fox jumps over the lazy dog.")
print(doc[3])
print(doc[1:4])
print(type(doc[3]).__name__, type(doc[1:4]).__name__)
print(doc[-1])A Span is a view of a contiguous run of tokens. It has its own text, start, and end attributes, where end is exclusive, matching normal Python slicing. Spans are the type behind noun chunks, sentences, and entities, which later chapters use heavily.
Processing many texts
Calling nlp(text) in a loop works but is slow for large inputs. Use nlp.pipe, which accepts an iterable of strings and processes them in batches. It returns a generator of Doc objects in the same order as the input.
import spacy
texts = ["The cat sat on the mat.", "Dogs chase balls in the park."]
nlp = spacy.load("en_core_web_sm", disable=["ner"])
print(nlp.pipe_names)
for doc in nlp.pipe(texts, batch_size=50):
print([(t.text, t.pos_, t.dep_) for t in doc])Because the result is a generator, you can consume it once. If you need the docs more than once, wrap it in list(...), keeping in mind that this holds every Doc in memory.
The disable=["ner"] argument skips the named entity recognizer. A disabled component is loaded but not run, so its annotations are missing from the output. This saves time when you only need tags and dependencies. A later chapter returns to disabling components and the related exclude option.
Common errors
The mistakes below account for most early problems.
- Model not found. The pipeline package is not installed in the active environment. Install it with
python -m spacy download en_core_web_sm. - Reloading the model repeatedly. Calling
spacy.loadper document multiplies runtime. Load once, reusenlp. - Printing integers instead of strings. Use
pos_,tag_,dep_, andlemma_. - Expecting annotations from a disabled component. If you disable
parser, thendep_is empty anddoc.sentsraises an error, because sentence boundaries are no longer set. - Passing a non-string.
nlpexpects astr. PassingNoneor a list raises aTypeErroror similar error. Pass lists tonlp.pipe, not tonlp. - Assuming the labels are always right. The annotations are statistical predictions. They are usually correct on ordinary text, but they can be wrong, which later chapters examine.
Summary of the working model
The working model for the rest of the tutorial is short. spacy.load gives you an nlp object. Calling nlp on text gives you a Doc. A Doc holds tokens, and each token carries annotations written by pipeline components. Slices of a Doc are Span objects. For many texts, use nlp.pipe. The next chapters examine each annotation, starting with tokens, then parts of speech, and then the dependency tree.
Exercise
You run nlp = spacy.load("en_core_web_sm", disable=["parser"]) and then print token.dep_ for every token in nlp("Birds fly south."). What do you expect to see, and why? Also, which line of code would you use to confirm which components are active?
Show answer
The dep_ values will be empty strings, because the parser component is loaded but not run, so no dependency labels are written to the tokens. You can confirm the active components with print(nlp.pipe_names), which will not list parser.
Exercise
A colleague writes a function that calls spacy.load("en_core_web_sm") on every request and then runs nlp(text) on one string. Name the two changes that would improve performance for a batch of 10,000 texts.
Show answer
First, load the pipeline once outside the function and reuse the nlp object. Second, pass all texts to nlp.pipe(texts, batch_size=...) instead of calling nlp(text) one at a time, optionally disabling components that are not needed.