Sub topic 11
Why Part of Speech Matters for Lemmas
What you need first
This chapter assumes you can read basic Python and know what a lemma is: the dictionary form of a word, such as "run" for "running". It also assumes you have met the WordNet lemmatiser in the previous chapter and know the basic grammar terms noun, verb, adjective, and adverb. You need NLTK installed (pip install nltk).
One surface form, several lemmas
A lemmatiser maps an inflected word to its dictionary form. The trouble is that many English words have more than one possible dictionary form. Which one is correct depends on how the word is used in the sentence.
Consider these two sentences:
- "She is running the meeting." Here "running" is a verb form, and its lemma is "run".
- "The running was exhausting." Here "running" is a noun, and its lemma is "running".
The characters are identical, so a lemmatiser that sees only the string cannot choose. It needs one more piece of information: the part of speech (POS), the grammatical category of the word in context. The POS is the extra input that turns an ambiguous lookup into a well-defined one.
The same applies to other words:
| Word | POS given | Lemma returned | Why |
|---|---|---|---|
| leaves | noun | leaf | plural of "leaf" |
| leaves | verb | leave | third-person singular of "leave" |
| meeting | noun | meeting | the noun is already a base form |
| meeting | verb | meet | present participle of "meet" |
| running | noun | running | the noun is already a base form |
| running | verb | run | present participle of "run" |
| better | adjective | good | irregular comparative |
| better | noun | better | the noun "better" is a base form |
Stemmers never face this problem because they ignore meaning and strip suffixes by rule. Lemmatisation gains accuracy by consulting a lexicon, and the price is that it must know the POS first.
How the WordNet lemmatiser uses the POS
NLTK's WordNetLemmatizer accepts a pos argument with these values:
"n"for noun. This is the default."v"for verb."a"for adjective."r"for adverb.
Internally it calls WordNet's morphy function, which works in three steps for the POS you gave:
- It checks an exception list for irregular forms of that POS, such as "mice" to "mouse" for nouns or "were" to "be" for verbs.
- It applies suffix-detachment rules for that POS. For verbs these include removing "s", "es", "ed", and "ing". For nouns they include "s", "ses", "ves", and "ies".
- It keeps only the candidates that exist as lemmas of that POS in WordNet. If several survive, the lemmatiser returns the shortest. If none survive, it returns the input word unchanged.
The POS therefore selects which exception list and which rule set are used, and which part of the dictionary is searched. The code below shows the effect:
import nltk
from nltk.stem import WordNetLemmatizer
nltk.download("wordnet")
lemmatizer = WordNetLemmatizer()
for word in ["leaves", "meeting", "running", "better"]:
for pos in ["n", "v", "a"]:
print(word, pos, lemmatizer.lemmatize(word, pos=pos))Look at the rows for "meeting". With pos="n", WordNet already lists "meeting" as a noun, so nothing changes. With pos="v", the rule that removes "ing" produces "meet", which is a verb in WordNet, so it is accepted. With pos="a" no adjective candidate exists, so the word comes back unchanged.
That last behaviour is a frequent source of silent errors. A wrong or missing POS does not raise an exception. The lemmatiser quietly returns the word untouched, and the mistake only shows up later as a poor feature or a missed search match.
Getting the POS from a tagger
In real text you do not know the POS in advance. A POS tagger is a model that assigns a tag to each token using its context. NLTK ships one that produces Penn Treebank tags such as NN (singular noun), NNS (plural noun), VBD (past-tense verb), VBG (present participle), and JJR (comparative adjective).
WordNet uses its own four categories, so you must translate between the two tag sets. The first letter of the Penn tag is enough:
import nltk
from nltk.corpus import wordnet
from nltk.stem import WordNetLemmatizer
from nltk.tokenize import TreebankWordTokenizer
for resource in ["wordnet", "averaged_perceptron_tagger_eng", "averaged_perceptron_tagger"]:
nltk.download(resource)
lemmatizer = WordNetLemmatizer()
tokenizer = TreebankWordTokenizer()
def to_wordnet_pos(penn_tag):
if penn_tag.startswith("J"):
return wordnet.ADJ
if penn_tag.startswith("V"):
return wordnet.VERB
if penn_tag.startswith("R"):
return wordnet.ADV
return wordnet.NOUN
sentence = "The mice were running and the children ate better apples."
tokens = tokenizer.tokenize(sentence)
for token, tag in nltk.pos_tag(tokens):
lemma = lemmatizer.lemmatize(token.lower(), pos=to_wordnet_pos(tag))
print(f"{token:10} {tag:5} {lemma}")The two nltk.download names for the tagger cover older and newer NLTK releases. Downloading a name that your version does not use only prints a warning.
With a typical tagger the lemmas come out as the, mouse, be, run, and, the, child, eat, good, apple, and .. The exact tags can differ between tagger versions, and the lemmas differ with them.
Three details in this code matter:
- Tag first, lowercase second. The tagger uses capitalisation as a clue, for example to spot proper nouns, so it receives the original tokens. Only the lemmatiser call lowercases the token, because WordNet lookups are lowercase.
- Tag whole sentences. The tagger needs the surrounding words. Tagging a single word in isolation gives a guess based on its most common use.
- Use a tokeniser that matches the tagger. The tagger was trained on Penn Treebank text, where "don't" is split into "do" and "n't". A regular expression such as
\w+would split it into "don" and "t", which the tagger has never seen.TreebankWordTokenizerfollows the training convention.
The whole pipeline
The diagram shows where the POS enters and what the lemmatiser does with it.
Failure modes and edge cases
Tagger errors propagate
The lemmatiser trusts the tag it receives. If the tagger labels "saw" as a noun in "He saw it", the lemmatiser keeps "saw" when the correct lemma is "see". Tagger accuracy on clean newswire text is high, but it drops on tweets, chat messages, headlines, and lists of keywords. Those are the domains where text often lacks the grammatical context that taggers rely on.
Unknown words pass through
Neologisms, brand names, typos, and technical terms are not in WordNet. Because step 3 filters candidates against the dictionary, such words are returned unchanged even with the right tag. For example, a plural form of a new product name will not be reduced to its singular. A stemmer would at least strip the "s".
The default is a noun
If you call lemmatize without pos, every word is treated as a noun. On a typical sentence this leaves most verb forms unchanged, so "running", "walked", and "was" all stay as they are. Many tutorials skip the pos argument and then conclude that lemmatisation does little. The missing argument is the cause.
Satellite adjectives and other tags
WordNet also has a "satellite adjective" category ("s"). Mapping Penn tags to wordnet.ADJ is enough for most uses. Tags that fit none of the four categories, such as determiners, prepositions, and punctuation, fall back to noun in the function above. That is harmless for words like "the" because they are not in the noun lexicon and pass through, but it is a deliberate shortcut. If you want to skip those tokens, filter them out before lemmatising.
Proper nouns
Names such as "Paris" or "Apple" tag as NNP, which maps to noun. Lowercasing before the lookup may match a common-noun entry such as "apple" and change the meaning. If you want to keep named entities intact, skip the lemmatiser for NNP and NNPS tags.
Cost
Tagging adds a model pass to every document. It is still cheap compared with neural models, but it is much slower than a stemmer, which only applies string rules. On very large collections that difference can decide which technique you choose.
Other toolkits
The ideas in this chapter apply outside NLTK. spaCy, for example, runs its tagger first and then uses the predicted tag to choose among lemma rules and lookup tables, so token.lemma_ already depends on the POS. You do not pass the tag yourself, but the same tagger-error and unknown-word problems apply.
Summary of the decision
Use POS-aware lemmatisation when valid dictionary forms matter and the text is grammatical enough for a tagger to work. Typical cases are building a vocabulary that people will read, linguistic analysis, and features where "better" and "good" should merge. If the text is noisy, the speed requirement is strict, or the vocabulary is full of words WordNet does not know, a stemmer or a subword tokeniser will often serve you better. The final chapter compares these options directly.
Exercise
In the sentence "We are meeting at noon", a pipeline calls lemmatizer.lemmatize("meeting") with no pos argument. What lemma does it return, what should it return, and what single change fixes it for this sentence and for text in general?
Show answer
It returns "meeting", because the default POS is noun and "meeting" is already a base form of the noun. The correct lemma here is "meet", since "meeting" is a verb form in this sentence. For this sentence you can pass pos="v". For text in general, run a POS tagger on the whole sentence, map each Penn tag to a WordNet category with a function such as towordnetpos, and pass that category to lemmatize for each token.
Exercise
Using the towordnetpos function from this chapter, what WordNet category does each of the tags VBZ, JJR, RB and NNP map to, and why might you want to treat NNP differently from the others before lemmatising?
Show answer
VBZ maps to wordnet.VERB, JJR maps to wordnet.ADJ, RB maps to wordnet.ADV, and NNP maps to wordnet.NOUN. NNP marks a proper noun such as "Apple" or "Paris". Lowercasing it and looking it up as a common noun can match an unrelated dictionary entry and change the meaning, so you may prefer to skip the lemmatiser for NNP and NNPS tokens and keep them as they are.
Exercise
A colleague lemmatises tweets with a tagger and finds that many verbs come back unchanged. Give two causes related to this chapter and one check you would run.
Show answer
One cause is that the tagger performs poorly on short, ungrammatical, informal text, so it assigns the wrong tag and the lemmatiser looks in the wrong part of WordNet. A second cause is that the words are slang, typos, or new terms that are not in WordNet, so no candidate survives the dictionary filter and the word is returned unchanged. A useful check is to count the tokens whose lemma equals the input, then read a random sample of them along with their tags to see whether the tags or the vocabulary are at fault.