Sub topic 6
Dependency Relations: dep_ and head
This chapter explains what a dependency parse is and how spaCy stores it on each token. It covers the two attributes you will use most, dep_ and head, along with the common errors people make when reading them.
Prerequisites. You should be comfortable with basic Python and have a spaCy pipeline installed (python -m spacy download en_core_web_sm). You should know what a noun, verb, subject, and object are. You should also know that pos_ holds a token's coarse part of speech, which earlier chapters covered.
What a dependency parse is
A part-of-speech tag describes a word on its own. A dependency parse describes how words connect. Each word in a sentence is attached to exactly one other word, its head, with a labelled link that names the grammatical relation between them. The word being attached is the dependent (or child). One word has no real head above it. It is the root, and it is usually the main verb.
The result is a tree. Every token has one head, the links never form a cycle, and following heads upward from any token always reaches the root.
In this sentence "approved" is the root. "committee" depends on it as the subject, and "budget" depends on it as the direct object. The determiners and the adjective hang off the nouns they modify.
The two attributes
Every Token in a Doc exposes the parse through two attributes:
token.headis anotherToken, the word this token attaches to.token.dep_is a string, the label of the relation between the token and its head.
There is also token.dep, an integer ID for the same label. The underscore version is the readable one, and it follows the same convention as pos_ and tag_.
Run this to see both attributes on a sentence:
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)The output has one row per token. The row for "fox" shows nsubj and the head jumps. The row for "jumps" shows ROOT and the head jumps.
The root points to itself
In spaCy the root token's head is the token itself. This is a convention that keeps head always valid, so you never get None. It has a practical consequence. A loop like "follow head until you reach the top" must stop when token.head == token, not when head is missing.
import spacy
nlp = spacy.load("en_core_web_sm")
doc = nlp("The committee approved the new budget.")
for token in doc:
if token.head == token:
print(token.text, "is the root of its sentence")
print(token.dep_)The label on the root is ROOT in English models. Check token.dep_ == "ROOT" or token.head == token. Both work, but the second does not depend on the label set.
Reading the labels
The label tells you the role. These are the English labels you will meet most often. They come from the ClearNLP-style scheme used by the English models.
| Label | Meaning | Example (dependent in bold in prose) |
|---|---|---|
| `nsubj` | nominal subject | "The **committee** approved" |
| `dobj` | direct object | "approved the **budget**" |
| `det` | determiner | "**The** committee" |
| `amod` | adjectival modifier | "the **new** budget" |
| `prep` | prepositional modifier | "jumps **over**" |
| `pobj` | object of a preposition | "over the **dog**" |
| `aux` | auxiliary verb | "She **has** left" |
| `conj` | conjunct | "reviewed and **approved**" |
| `cc` | coordinating conjunction | "reviewed **and** approved" |
| `ROOT` | root of the sentence | "The committee **approved**..." |
Do not memorize this list. Use spacy.explain to look up any label:
import spacy
print(spacy.explain("nsubj"))
print(spacy.explain("VERB"))
print(spacy.explain("NNS"))It returns a short description, or None if the label is unknown. That None is a useful signal. It usually means a typo or a label from a different scheme.
Labels depend on the model
Label sets differ between languages and between model families. English models use dobj for direct objects. Models that follow Universal Dependencies conventions use obj. When you write code that tests dep_, check which labels your model emits. The safe approach used in later chapters is to accept both, as in token.dep_ in ("dobj", "obj").
You can see the labels a loaded pipeline can produce:
import spacy
nlp = spacy.load("en_core_web_sm")
print(nlp.get_pipe("parser").labels)This prints a tuple of every label the parser was trained to predict. Use it to find the exact strings to test against.
Heads and dependents together
The parse is easiest to understand when you read each token as "this word is the label of that word". "fox" is the nsubj of "jumps". "lazy" is the amod of "dog". Reading it this way makes errors visible. If a sentence says "dog" is the nsubj of "jumps", you can see at once that the attachment is wrong.
A helpful print format shows the relation as a sentence:
import spacy
nlp = spacy.load("en_core_web_sm")
doc = nlp("The committee approved the new budget.")
for token in doc:
if token.head != token:
print(f"{token.text!r} is {token.dep_} of {token.head.text!r}")
else:
print(f"{token.text!r} is the root")Because every token except the root has exactly one head, this loop prints one line per token. The number of relations always equals the number of tokens in the sentence.
Each sentence has its own tree
When a Doc holds several sentences, the parser builds one tree per sentence. Each sentence has one root. A token's head is always in the same sentence as the token. This matters when you search for the root. doc can have many roots, and you should look for them per sentence:
import spacy
nlp = spacy.load("en_core_web_sm")
doc = nlp("Researchers published the dataset. The editors reviewed the paper.")
for sent in doc.sents:
print(sent.root.text, sent.root.dep_)The root property of a Span returns the token whose head lies outside the span, or is itself. For a sentence, that is the sentence root. The next chapter shows how the parse also decides where sentences begin and end.
Common errors
These are the mistakes intermediate users make most often when starting with dep_ and head.
- Comparing a token to a string.
token.head == "jumps"is always false, becauseheadis aTokenand not a string. Usetoken.head.text == "jumps". - Using
depwhen you meandep_.token.dep == "nsubj"is false becausedepis an integer. Usedep_for strings. - Expecting the root to have no head. The root's head is itself. Code that stops at
Noneloops forever. - Testing one label spelling. A check for
"dobj"finds nothing in a model that emits"obj". The code runs without errors and returns empty results, which is easy to miss. - Assuming the parse is correct. The parser is a statistical model. It predicts the tree and sometimes gets it wrong, especially on long sentences, fragments, and ambiguous attachments such as "I saw the man with the telescope".
- Using the parse without the pipeline component. If you load a pipeline with the parser disabled,
dep_is an empty string andheadis the token itself, so every token looks like a root. See the check below.
import spacy
nlp = spacy.load("en_core_web_sm", disable=["parser"])
doc = nlp("The committee approved the new budget.")
print(doc.has_annotation("DEP"))
print([t.dep_ for t in doc])doc.has_annotation("DEP") returns False here, and the labels are empty strings. Call this method before you rely on a parse. It turns a silent failure into a clear one.
Ambiguity in practice
Some sentences have more than one valid parse. In "I saw the man with the telescope", the phrase "with the telescope" can attach to "saw" (you used the telescope) or to "man" (the man had it). The parser picks one. You can see which by looking at the head of the preposition:
import spacy
nlp = spacy.load("en_core_web_sm")
doc = nlp("I saw the man with the telescope.")
for token in doc:
if token.dep_ == "prep":
print(token.text, "attaches to", token.head.text)Neither answer is a bug in the code. The text itself is ambiguous, and the model returns its single most likely tree. If your task needs the other reading, you need more context or a manual rule.
Summary of the working model
- Each token has one head and one label. The root is its own head.
headis aToken.dep_is a string.- Labels depend on the language and model. Use
spacy.explainand the parser'slabelsto check them. - The tree is predicted by a model, so it can be wrong. Check
doc.has_annotation("DEP")and inspect examples before you build on it.
Exercise
You run [t.text for t in doc if t.dep_ == "dobj"] on a pipeline whose parser uses the label obj for direct objects, and you get an empty list. The sentence clearly has a direct object. What is the cause, and how would you change the code so it works with both label sets?
Show answer
The test looks for the exact string "dobj", but this model emits "obj", so no token matches and no error is raised. Check the labels with nlp.get_pipe("parser").labels, then accept both spellings: [t.text for t in doc if t.dep_ in ("dobj", "obj")].
Exercise
A token's head is the token itself. What does that tell you about the token, and what condition would you use in a loop that climbs from a token to the top of its tree?
Show answer
It is the root of its sentence. Climb with while token.head != token: token = token.head, which stops at the root. Checking for None would never end, because the root's head is never None.