Sub topic 14
When the Parser Is Wrong
This chapter assumes you can load a spaCy pipeline, read pos_, tag_, dep_ and head, and walk a tree with children and subtree. You should also have written at least one extraction rule, such as the subject-verb-object loop from the earlier chapters.
A spaCy parser is a statistical model. It predicts a tree from patterns it learned on annotated text, and it never checks that the tree is grammatical. Every attribute you have used so far can be wrong, and your extraction code inherits those errors silently. This chapter covers where errors come from, how to spot them, and how to write code that does not trust the parse blindly.
Why errors happen
Several causes account for most mistakes.
- Genuine ambiguity. Some sentences have more than one valid parse. The model picks the reading that was most common in its training data.
- Domain shift. The small English models are trained mostly on news, web text and similar sources. Legal clauses, tweets, chat logs, product titles and clinical notes look different, and accuracy drops.
- Missing structure. Headlines, bullet points, titles and fragments have no finite verb. The parser still produces one tree per sentence, so it forces a root onto text that has none.
- Tokenization and sentence splitting. The parser runs after the tokenizer. A bad split, such as a period inside an abbreviation, gives the parser the wrong input.
- Model size.
en_core_web_smtrades accuracy for speed and size. Larger pipelines are usually more accurate, but they are not error-free.
Looking at a hard case
Prepositional phrase attachment is the classic problem. In "I saw the man with the telescope", does "with the telescope" describe how you saw, or which man? The answer depends on the head the parser gives to "with". This script prints the attachment for three sentences.
import spacy
nlp = spacy.load("en_core_web_sm")
sentences = [
"I saw the man with the telescope.",
"Time flies like an arrow.",
"The old man the boats.",
]
for text in sentences:
doc = nlp(text)
print(text)
for token in doc:
print(
f" {token.i:>2} {token.text:<10} {token.pos_:<6} "
f"{token.dep_:<8} -> {token.head.text}"
)Read the output yourself. If "with" attaches to "saw", the parser chose the instrument reading. If it attaches to "man", it chose the modifier reading. Both are grammatical. The third sentence is a garden-path sentence: it only parses if "man" is a verb. Check whether the model labels "man" as a noun or a verb. Your results can differ from other people's because they depend on the model version.
Three sentences prove nothing about accuracy. What they show is that when two parses are plausible, the output is a guess, and nothing in the Doc tells you how confident that guess was.
Automatic sanity checks
You cannot verify every parse by hand, but you can cheaply detect parses that are likely to be wrong. These checks catch structural problems, not subtle attachment errors.
import spacy
nlp = spacy.load("en_core_web_sm")
def audit(doc):
"""Return a list of (sentence, reason) pairs for suspicious parses."""
problems = []
for sent in doc.sents:
root = sent.root
if root.pos_ not in ("VERB", "AUX"):
problems.append((sent.text, f"root {root.text!r} is {root.pos_}"))
elif not any(c.dep_ in ("nsubj", "nsubjpass") for c in root.children):
problems.append((sent.text, f"root {root.text!r} has no subject"))
unlabeled = [t.text for t in sent if t.dep_ == "dep"]
if unlabeled:
problems.append((sent.text, f"unclassified dependents: {unlabeled}"))
return problems
texts = [
"The engineer fixed the bug.",
"Quarterly revenue results",
"Close the door.",
]
for text in texts:
doc = nlp(text)
print(text, "->", audit(doc) or "ok")The checks encode three heuristics:
- A sentence root that is not a verb or auxiliary suggests a fragment or a mis-tag.
- A verb root without a subject suggests a missed subject or an imperative.
- The label
depmeans the parser found a relation but could not classify it.
Each heuristic produces false alarms. "Close the door." is a valid imperative, so the missing-subject flag is correct to raise but wrong to treat as an error. Treat the output as a review queue, not a verdict.
Disagreement between models
A useful trick is to parse the same text with two pipelines and look at where they disagree. Disagreement does not tell you which model is right, but it points to the sentences most worth reading. This example assumes you have also installed en_core_web_md with python -m spacy download en_core_web_md.
import spacy
small = spacy.load("en_core_web_sm")
medium = spacy.load("en_core_web_md")
def head_disagreements(text):
a, b = small(text), medium(text)
if len(a) != len(b):
return None # different tokenization, cannot compare by position
return [
(x.text, x.head.text, y.head.text)
for x, y in zip(a, b)
if x.head.i != y.head.i
]
for text in ["I saw the man with the telescope.", "The engineer fixed the bug."]:
print(text, "->", head_disagreements(text))The function returns None when the token counts differ, because token positions no longer line up. An empty list means the two models agree on every head. Agreement is weak evidence of correctness, since both models were trained on similar data and can make the same mistake.
Tag errors that break lemmas and rules
Lemmas depend on the part-of-speech tag, so a wrong tag produces a wrong lemma. A word like "saw" can be a noun (a tool) or the past tense of "see". Mis-tagging it changes lemma_, which changes every count or dictionary lookup keyed on the lemma. The same holds for rules: a pattern that looks for token.pos_ == "VERB" silently ignores a verb the tagger called a noun.
When a rule returns less than you expect, print the tokens of a missed example before changing the rule. In most cases the cause is an upstream tag or dependency label, not the rule.
Rules that are too narrow
The subject-verb-object extractor from the earlier chapter looks for nsubj and dobj or obj. Many valid sentences do not use those labels. Passive sentences are the standard example, and the English models label the subject of a passive verb differently.
import spacy
nlp = spacy.load("en_core_web_sm")
doc = nlp("The report was written by the team.")
for token in doc:
print(f"{token.text:<8} {token.dep_:<10} -> {token.head.text}")In the English models, the subject of a passive verb usually appears as nsubjpass rather than nsubj, and the "by" phrase is usually attached with the label agent. A rule that only accepts nsubj finds nothing here. Other known gaps include:
- Conjoined verbs, where the second verb has no subject of its own and shares the first one.
- Questions and relative clauses, where the object appears before the verb.
- Verbs with a clausal complement ("decided to leave"), where the object is a clause and not a noun.
A rule that fails on these cases does not raise an error. It returns fewer results than it should, and nobody notices the loss.
Measuring instead of guessing
For any project where extraction quality matters, build a small gold set. Take 50 to 100 representative sentences from your own data, correct the parse by hand, and compare your pipeline's output against the corrected labels. The comparison tells you the share of tokens with the right head, and the right head plus the right label. Run it again whenever you change the model, spaCy version or rules.
| Approach | Cost | What it tells you |
|---|---|---|
| Reading a few parses | Minutes | Whether anything is obviously broken |
| Automatic sanity checks | Hours to write | Which sentences are structurally suspicious |
| Two-model comparison | Low | Where the models disagree |
| Hand-labelled gold set | Days | Real accuracy on your domain |
Practical rules of thumb
- Keep the original sentence next to every extracted triple, so a reviewer can check it quickly.
- Prefer rules that use several signals (POS, dependency label and lemma) over rules that rely on one.
- Log the sentences that match no rule. They show you which constructions you are missing.
- Treat extraction output as a candidate list for a human or a downstream filter, not as ground truth.
- If errors cluster in your domain, consider a larger pretrained pipeline first. Training or fine-tuning your own components is the next step, and it needs annotated data.
Exercise
A colleague's subject-verb-object extractor returns no triples for "The contract was signed by both parties." The sentence is grammatical and the verb is correctly tagged. Give the most likely reason and a first debugging step.
Show answer
The extractor probably accepts only the nsubj label, but the subject of a passive verb is usually labelled nsubjpass in the English models. First print every token's dep_ and head for the sentence to see the labels the model actually produced. Then extend the rule to accept nsubjpass, and treat the "by" phrase (usually labelled agent) as the actor.
Exercise
Your sanity check flags "Close the door." because the root verb has no subject. Should you fix the parser output? Explain.
Show answer
No. The parse is probably correct. Imperatives have an implied subject, so a missing nsubj is valid. The heuristic gives a false alarm, which is why such checks should produce a review queue and not automatically reject sentences. You can refine the check, for example by skipping sentences whose root is in the base form and has no subject.