Sub topic 5
Lemmas and why they depend on POS
This chapter assumes you can load a spaCy pipeline, iterate over a Doc, and read token.pos_ and token.tag_. These were covered in the earlier chapters on tokens and part-of-speech tags. Here you will see what a lemma is, where it comes from, and why a wrong or missing POS tag produces a wrong lemma.
What a lemma is
A lemma is the dictionary form of a word. It is the form you would look up in a dictionary entry. The tokens "runs", "ran", and "running" all share the lemma "run". The tokens "mice" and "mouse" share the lemma "mouse".
Lemmas are useful whenever you want inflected forms to count as one item. Examples are word-frequency counts, keyword search, and matching a vocabulary list.
Lemmatization differs from stemming. A stemmer cuts suffixes with fixed rules and can produce non-words, such as "studi" from "studies". A lemmatizer returns a real word and can handle irregular forms like "ran" to "run". To do that, it needs to know the word's grammatical category.
In spaCy, a token has two related attributes:
token.lemma_is the lemma as a string.token.lemmais the same lemma as an integer hash. spaCy uses it internally and you rarely need it.
The same string, different lemmas
The surface form "meeting" can be a noun ("a long meeting") or the present participle of a verb ("we are meeting"). Its lemma differs in each case.
import spacy
nlp = spacy.load("en_core_web_sm")
for text in ["The meeting ran late.", "We are meeting the client."]:
doc = nlp(text)
print([(t.text, t.pos_, t.lemma_) for t in doc if t.text == "meeting"])Typical output:
[('meeting', 'NOUN', 'meeting')]
[('meeting', 'VERB', 'meet')]The lemmatizer receives the token's text and its POS, and it looks up rules and exceptions for that pair. It never sees the sentence. The sentence matters only because it determined the POS tag earlier in the pipeline.
The table below shows more pairs where the POS changes the lemma. Exact results can vary between model versions, so check them on your own install.
| Token | POS | Typical lemma |
|---|---|---|
| saw | VERB | see |
| saw | NOUN | saw |
| meeting | VERB | meet |
| meeting | NOUN | meeting |
| better | ADJ | good |
| better | ADV | well |
| was | AUX | be |
How the lemmatizer is wired
For English, the lemmatizer is a rule-based component with a lookup table of irregular forms. You can check the pipeline order and the lemmatizer's mode:
import spacy
nlp = spacy.load("en_core_web_sm")
print(nlp.pipe_names)
print(nlp.get_pipe("lemmatizer").mode)Typical output:
['tok2vec', 'tagger', 'parser', 'attribute_ruler', 'lemmatizer', 'ner']
ruleThree components matter for lemmas:
- The
taggerpredicts the fine-grained tag intoken.tag_, for exampleVBGorNNS. - The
attribute_rulermaps each fine-grained tag to a coarse Universal POS value intoken.pos_. It also holds a few hand-written exceptions, such as the lemma for the contraction piece "n't". - The
lemmatizerreadstoken.pos_and applies the rules for that POS.
The mode value rule means the lemmatizer applies suffix rules and exception lists keyed by POS. Some other languages use lookup mode, which maps a surface form straight to a lemma and ignores POS. Lookup mode is simpler, but it cannot tell "meeting" the noun from "meeting" the verb.
The consequence is a chain of dependencies. If the tagger is wrong, pos_ is wrong, and the lemma is probably wrong too. If the attribute_ruler is missing, the lemmatizer has nothing to read.
What happens when POS is missing
You can see the dependency directly by disabling the attribute_ruler. The tagger still runs and sets tag_, but pos_ stays empty.
import spacy
text = "The children were running."
full = spacy.load("en_core_web_sm")
print([(t.text, t.pos_, t.lemma_) for t in full(text)])
broken = spacy.load("en_core_web_sm", disable=["attribute_ruler"])
print([(t.text, t.pos_, t.lemma_) for t in broken(text)])With the full pipeline you should see lemmas such as "child", "be", and "run". With the attribute_ruler disabled, pos_ is an empty string. The lemmatizer then cannot apply its rules and falls back to the lowercased token text, so "children", "were", and "running" come back unchanged. spaCy also prints a warning about missing POS information.
The same applies if you disable the tagger. You are not told which components the lemmatizer needs unless you read the warning, so check nlp.pipe_names and spot-check a few lemmas after you change a pipeline.
Lemmas in practice: counting words
A common use is counting content words by lemma. The code below drops punctuation, whitespace, and stop words, then counts the remaining lemmas in lowercase.
from collections import Counter
import spacy
nlp = spacy.load("en_core_web_sm", disable=["parser", "ner"])
texts = [
"The engineers tested the model, and the model passed.",
"She is testing a better model while they fixed bugs.",
]
counts = Counter()
for doc in nlp.pipe(texts):
for token in doc:
if token.is_alpha and not token.is_stop:
counts[token.lemma_.lower()] += 1
print(counts.most_common(5))Here "tested" and "testing" count as one item, "test", and "model" appears three times. The variable counts is a normal Counter, so you can use any of its methods.
Two details in this code are worth noting:
- The call to
.lower()is a safeguard. Most lemmas are already lowercase, but proper nouns keep their capitalization, so "Paris" and "paris" would otherwise count separately. - Stop-word filtering uses the token's surface form, not its lemma. spaCy's stop list is a set of word forms, and
token.is_stopchecks that form.
Edge cases and common errors
Tagger errors propagate. The POS tagger sometimes misreads ambiguous words in short or unusual text, such as headlines, search queries, and titles. "Saw the saw" can tag both tokens as the same POS. A wrong POS gives a wrong lemma with no error and no warning, because the lemmatizer trusts its input.
Lemmas are not always what you expect. Some words are treated by the rules as already being in base form. Comparatives and superlatives are mapped through an exception list, which is why "better" can become "good" for an adjective but "well" for an adverb. Words that are not in that list are left as they are, so a rare irregular form may come back unchanged.
Case and unknown words. The lemmatizer does not know the word. It knows rules. A made-up word such as "blorfing" with a VERB tag will get a lemma by suffix stripping, such as "blorf". That is a guess and not a lookup.
Contractions. The tokenizer splits "didn't" into "did" and "n't". The attribute ruler gives "n't" the lemma "not" and "did" the lemma "do". If you count lemmas, you will see "not" and "do" as separate items.
Overwriting lemmas by hand. You can assign token.lemma_ = "..." in a custom component. Do this only after the lemmatizer has run, or your value will be replaced.
Models differ. A larger English model gives different tags in some sentences, and therefore different lemmas, than en_core_web_sm. Pin the model version when you need repeatable results.
A checking habit
When you rely on lemmas, print a small sample with the POS next to it:
import spacy
nlp = spacy.load("en_core_web_sm")
doc = nlp("The saw was on the table, and I saw it.")
for token in doc:
print(f"{token.text:8} {token.tag_:5} {token.pos_:6} {token.lemma_}")If a lemma looks wrong, look at pos_ first. The cause is usually there, and you can use spacy.explain(token.tag_) to read the tag.
Exercise
A colleague disables the tagger component to make processing faster, then complains that token.lemma_ for "running" returns "running" instead of "run". What is the cause, and what two changes would restore good lemmas while still saving time?
Show answer
The attribute_ruler sets pos_ from the tagger's tag_. Without the tagger, pos_ is empty, and the rule-based lemmatizer falls back to the lowercased token text. To restore lemmas, keep the tagger and attribute_ruler enabled. To still save time, disable components that lemmas do not need, namely parser and ner, and process texts with nlp.pipe.
Exercise
Write code that processes "We are meeting the client after the meeting." and prints each occurrence of "meeting" with its pos_ and lemma_. What do you expect to see, and why do the lemmas differ?
Show answer
Code: doc = nlp("We are meeting the client after the meeting.") followed by print([(t.text, t.pos_, t.lemma_) for t in doc if t.text == "meeting"]). Expected: the first "meeting" is tagged VERB with lemma "meet", and the second is tagged NOUN with lemma "meeting". The lemmatizer applies different rules for each POS, so the same surface string maps to different lemmas.