Sub topic 12
Choosing between stemming, lemmatisation and subwords
This chapter assumes you can write basic Python and read regular expressions. It also assumes you know what an NLP task such as search or classification looks like, and that you have met tokenisation, Porter and Snowball stemmers, and WordNet lemmatisation in the earlier chapters. Here you will compare the three techniques and decide which one a task needs.
The decision in one sentence
All three techniques try to answer one question: how should two different surface strings be treated as related? Stemming and lemmatisation answer by merging them into one shared form. Subword tokenisation answers by keeping them separate but breaking them into shared pieces. The right choice depends on what your downstream system does with tokens.
| Technique | What it produces | Typical cost | Main risk |
|---|---|---|---|
| Stemming | A truncated stem, possibly not a word | Very cheap, no lexicon | Overstemming and understemming |
| Lemmatisation | A dictionary base form | Needs a lexicon and usually POS tags | Wrong POS gives wrong or unchanged lemma |
| Subword tokenisation | Pieces from a learned vocabulary | Needs a trained vocabulary | Pieces may not be meaningful units |
| None (case folding only) | Original word forms | Free | Sparse counts, many rare types |
Comparing the three on the same words
The following script runs a stemmer, a lemmatiser and a toy WordPiece tokeniser on the same words. The WordPiece vocabulary is hand-written so the example is self-contained. A real vocabulary is learned from a corpus.
import nltk
from nltk.stem import PorterStemmer, WordNetLemmatizer
nltk.download("wordnet")
porter = PorterStemmer()
lemmatizer = WordNetLemmatizer()
VOCAB = {"play", "##ing", "##s", "##ed", "un", "##believ", "##able"}
def wordpiece(word, vocab):
"""Greedy longest-match-first splitting, as in WordPiece."""
pieces = []
start = 0
while start < len(word):
end = len(word)
piece = None
while start < end:
candidate = word[start:end]
if start > 0:
candidate = "##" + candidate
if candidate in vocab:
piece = candidate
break
end -= 1
if piece is None:
return ["[UNK]"]
pieces.append(piece)
start = end
return pieces
for word in ["universities", "universe", "running", "ran", "unbelievable", "zebra"]:
print(
word,
porter.stem(word),
lemmatizer.lemmatize(word),
lemmatizer.lemmatize(word, pos="v"),
wordpiece(word, VOCAB),
)Reading the output column by column shows the differences:
- Porter reduces both
universitiesanduniversetounivers. That merges two words with different meanings, which is overstemming. It leavesranasran, so it never connects it torunning, which becomesrun. That is understemming. - WordNet with the default noun tag turns
universitiesintouniversitybut leavesrunningas a noun. Withpos="v",runningbecomesrunandranalso becomesrun. - WordPiece splits
unbelievableintoun,##believand##able. It never mergesranwithrun, because it only splits and does not map to a base form.zebrahas no matching pieces in this tiny vocabulary, so it becomes[UNK]. A real vocabulary includes single characters or bytes, so real tokenisers avoid this.
When stemming is the right choice
Choose a stemmer when these conditions hold:
- The system is a bag-of-words system, such as keyword search, TF-IDF classification or topic modelling on large collections.
- Recall matters more than precision, so a query for
connectedshould find documents withconnection. - Nobody reads the tokens. A stem like
studiis fine inside an index and poor in a user interface. - You need speed and a small footprint. A stemmer is a handful of string rules with no dictionary and no tagger.
Stemming also fits languages with regular suffixing, and Snowball offers stemmers for many of them. A stemmer cannot handle irregular forms. Rules do not connect mice to mouse, went to go or better to good, because those forms are not produced by stripping a suffix.
Prefer Snowball over the original Porter when you can. It fixes some known Porter inconsistencies and has a documented rule set per language. Whichever you pick, apply the same stemmer to both documents and queries. If the index is built with one and queries are processed with another, matches silently fail.
When lemmatisation is the right choice
Choose a lemmatiser when these conditions hold:
- You need valid words in the output. Examples are keyword extraction shown to users, glossaries, and dictionary or ontology lookups.
- You need precision, and overstemming such as
universeanduniversitywould produce false matches. - The language has irregular morphology, which is true for English verbs and for many other languages where suffix stripping fails.
- You can afford a POS tagging step. A lemmatiser without POS information is guessing.
The cost is the pipeline. The usual order is tokenise, tag, then lemmatise. Tagger errors pass into the lemmatiser. If the tagger labels running as a noun in she is running late, the lemma stays running and you lose the link to run.
The WordNet lemmatiser uses the tag letters n, v, a (adjective) and r (adverb). Penn Treebank tags such as VBG or NNS must be mapped to those letters before you call lemmatize. A missing mapping falls back to noun, which is a common silent bug.
When subword tokenisation is the right choice
If you are using a pretrained neural model, such as a BERT-style encoder or a GPT-style decoder, use that model's own tokeniser. It was trained together with the model's embeddings, and a different tokeniser would send the model pieces it has never seen. Applying a stemmer or lemmatiser first usually does not help and often hurts, for three reasons:
- The model has learned from inflected forms. Information such as tense, number and negation is carried by the endings you would remove.
- Stemmed strings like
universare rare in the training data, so they split into odd pieces. - Large vocabularies and contextual embeddings already handle the sparsity that stemming was designed to reduce.
Subword methods also fit when you must avoid unknown words entirely, for example with names, typos, code, social-media text or morphologically rich languages. BPE (byte-pair encoding) and WordPiece both build a vocabulary of frequent pieces and fall back to smaller pieces, down to characters or bytes, for rare words. The trade-offs are:
- Pieces often do not align with morphemes.
unbelievablesplitting cleanly is lucky, and many words split into arbitrary fragments. - Token counts rise for languages and domains that were rare in the training corpus. That raises cost and shortens the usable context.
- The vocabulary is fixed once trained. Changing it means retraining the model, or at least adapting it.
Neither: when to keep the surface forms
Sometimes the best normalisation is the smallest one. Case folding and Unicode normalisation are cheap and rarely harmful. Stemming and lemmatisation destroy information, so leave the forms alone when they carry the signal:
- Authorship and style analysis. Tense, plurality and function-word choices are the features.
- Sentiment.
loved,lovingandlovelycan differ in tone, and capitalisation (GREAT) can signal emphasis. If you case-fold, you lose that emphasis. - Named entities and legal or medical text.
Parsonsandparsonsmay differ, and a stem can merge drug names or statute terms that must stay distinct. - Machine translation and generation. The output must be inflected correctly, so the model needs the real forms.
Evaluate instead of guessing
Opinions about normalisation are cheap and measurements are not. The following protocol settles the question for your own data.
- Fix everything except the normaliser: the same data split, features, model and hyperparameters.
- Run at least four variants: raw tokens with case folding only, a Snowball stemmer, a lemmatiser with POS tags, and (if the model allows it) a subword tokeniser.
- Compare with a metric that matches the task, such as F1 for classification, or recall at k and precision at k for retrieval.
- Use cross-validation or several random seeds, so a difference of a fraction of a point is not mistaken for a result.
- Read the errors. Print the words that collapsed together under each variant and check them by hand. A handful of bad merges in a high-frequency word can explain a metric drop.
- Record the pipeline version. Indexes and models built with one normaliser cannot be queried with another.
Expect small differences. On large datasets with a strong classifier, the gap between stemming, lemmatisation and no normalisation is often under a percentage point, and with enough training data raw forms sometimes win. In small-data retrieval in a morphologically rich language, stemming can give a clear recall gain. The cost of each choice (latency, dependencies, extra tagging) is a legitimate tiebreaker when the metrics are close.
Common mistakes
- Mixing normalisers between training and serving. Always ship the exact same function in both places.
- Stemming before lemmatising. A lemmatiser expects real words, and stems like
studiare not in its lexicon, so they pass through unchanged. - Lemmatising lower-cased text with a tagger that expects the original case. Tag first, then fold case. Capitalisation helps taggers spot proper nouns.
- Removing stop words before tagging. Words like
isandtheare context the tagger uses. - Using a stemmer for a language it was not built for. English Porter rules applied to German or Finnish text give garbage. Use the language-specific Snowball stemmer, or a lemmatiser built for that language.
- Treating a lower vocabulary size as success. Smaller vocabularies are a side effect. The metric you care about is the goal.
Exercise
A team builds a keyword search over 2 million support tickets. Users type short queries and see highlighted snippets of the original text. Index size and query latency matter. Which technique would you try first, and what must be true of how the query and the documents are processed?
Show answer
Try a stemmer first, preferably the English Snowball stemmer. Search is a bag-of-words, recall-oriented task, and stemming is cheap and needs no tagger. Highlighting uses the original text, so users never see stems, provided positions of the original tokens are stored. The query and the documents must go through the identical stemmer and tokenisation, or matches fail. Measure recall and precision at k against a lemmatised variant before committing.
Exercise
You fine-tune a pretrained BERT-style classifier. A colleague proposes stemming the input with Porter first "to reduce vocabulary". Give two reasons not to do it.
Show answer
First, the model was pretrained on normal inflected text with its own subword vocabulary, so stems such as univers are rare and split into odd pieces, which makes the input less like the training data. Second, endings carry information (tense, number, negation), and the model's contextual embeddings and subword vocabulary already handle sparsity, so the stemmer removes signal without helping. The correct step is to use the model's own tokeniser and evaluate on a validation set.
Exercise
A lemmatiser run over the text "She was running late" returns running, not run. Name the likely cause and the fix.
Show answer
The lemmatiser was called without part-of-speech information, so it treated running as a noun and left it unchanged. Tag the sentence first, map the tagger's tags to the lemmatiser's tag letters (here a verb, v), and call lemmatize("running", pos="v"), which returns run.