TExcelTAD
Home › NLP, Transformers & LLM Fine-Tuning › Stemming and Lemmatisation with NLTK

Stemming and Lemmatisation with NLTK

A rider searches the help centre for "reserving a bike". The answer says "Bikes can be reserved for up to 10 minutes". To a model that compares strings, "reserving" and "reserved", "bike" and "bikes" are four unrelated words, and the search finds nothing in common between the query and the answer except, perhaps, "a". English inflects verbs (ride, rides, riding, rode), nouns (bike, bikes) and adjectives (big, bigger), and derives new words with suffixes (reserve, reservation, reservable). A bag-of-words model with a few thousand training documents sees most of these forms only a handful of times each, so its counts are spread thin.

Two techniques map word forms onto a shared key. Stemming chops suffixes off with rules and produces a stem that need not be a word ("studi", "univers"). Lemmatisation maps each form to its dictionary headword, the lemma ("studies" to "study", "mice" to "mouse", "rode" to "ride"), which needs a vocabulary and usually the part of speech. This lesson implements the start of the Porter stemmer and a small lemmatiser from scratch, compares NLTK's three stemmers, measures over- and under-stemming, and ends with the question that matters most today: when to use either at all.

The Porter stemmer

Martin Porter's algorithm (1980) is the classic English stemmer. It never consults a dictionary. It applies five steps of suffix rules in order, and most rules have a condition on what is left of the word. The central quantity is the measure mm of a stem. Write each letter as C (consonant) or V (vowel; "y" counts as a vowel after a consonant). Every word then has the form

[C] (VC)m [V][C]\,(VC)^m\,[V]

where the brackets mean "optional" and mm counts the vowel-consonant sequences. "tr" and "tree" have m=0m = 0, "trouble" and "oats" m=1m = 1, "private" and "oaten" m=2m = 2. A rule such as "(m > 0) EED →\to EE" means: replace the suffix "eed" by "ee" only if the stem before it has m>0m > 0. So "agreed" becomes "agree" (the stem "agr" has m=1m = 1) while "feed" stays (the stem "f" has m=0m = 0). The conditions stop the rules from eating short words.

Step 1a handles plurals (SSES →\to SS, IES →\to I, SS →\to SS, S →\to nothing). Step 1b removes "-ed" and "-ing" when the stem contains a vowel, then repairs the result: "conflat" gets its "e" back, a double consonant is undoubled ("hopp" to "hop", but "fall" keeps its "ll"), and a short stem ending consonant-vowel-consonant gets an "e" ("fil" to "file"). The example implements these two steps exactly as the paper defines them, on the paper's own example words.

python · try it yourself
import re

def is_cons(w, i):
    c = w[i]
    if c in "aeiou":
        return False
    if c == "y":
        return i == 0 or not is_cons(w, i - 1)
    return True

def measure(stem):
    """m in [C](VC)^m[V]: the number of vowel-consonant sequences."""
    pattern = "".join("c" if is_cons(stem, i) else "v" for i in range(len(stem)))
    return len(re.findall(r"v+c+", pattern))

def has_vowel(stem):
    return any(not is_cons(stem, i) for i in range(len(stem)))

def ends_cvc(w):
    return (len(w) >= 3 and is_cons(w, len(w) - 3) and not is_cons(w, len(w) - 2)
            and is_cons(w, len(w) - 1) and w[-1] not in "wxy")

def step1a(w):
    for suf, rep in (("sses", "ss"), ("ies", "i"), ("ss", "ss"), ("s", "")):
        if w.endswith(suf):
            return w[: len(w) - len(suf)] + rep
    return w

def step1b(w):
    if w.endswith("eed"):
        return w[:-1] if measure(w[:-3]) > 0 else w
    for suf in ("ed", "ing"):
        if w.endswith(suf) and has_vowel(w[: -len(suf)]):
            w = w[: -len(suf)]
            if w.endswith(("at", "bl", "iz")):
                return w + "e"
            if len(w) >= 2 and w[-1] == w[-2] and is_cons(w, len(w) - 1) and w[-1] not in "lsz":
                return w[:-1]
            if measure(w) == 1 and ends_cvc(w):
                return w + "e"
            return w
    return w

for stem in ["tr", "tree", "trouble", "oats", "private", "oaten"]:
    print(f"m({stem}) = {measure(stem)}")
words = ["caresses", "ponies", "cats", "feed", "agreed", "plastered", "motoring",
         "sing", "conflated", "hopping", "falling", "filing", "hoped"]
for w in words:
    print(f"{w:10} -> 1a {step1a(w):9} -> 1b {step1b(step1a(w))}")
m(tr) = 0
m(tree) = 0
m(trouble) = 1
m(oats) = 1
m(private) = 2
m(oaten) = 2
caresses   -> 1a caress    -> 1b caress
ponies     -> 1a poni      -> 1b poni
cats       -> 1a cat       -> 1b cat
feed       -> 1a feed      -> 1b feed
agreed     -> 1a agreed    -> 1b agree
plastered  -> 1a plastered -> 1b plaster
motoring   -> 1a motoring  -> 1b motor
sing       -> 1a sing      -> 1b sing
conflated  -> 1a conflated -> 1b conflate
hopping    -> 1a hopping   -> 1b hop
falling    -> 1a falling   -> 1b fall
filing     -> 1a filing    -> 1b file
hoped      -> 1a hoped     -> 1b hope

Every result matches the examples in Porter's paper. "sing" keeps its "ing" because the remaining "s" has no vowel, and "motoring" loses it because "motor" has one. "ponies" becomes "poni": that is not a mistake but how the algorithm works, since step 1c later turns a final "y" into "i" as well ("pony" to "poni"), so both forms meet at the same stem. Steps 2 to 5 then remove derivational suffixes ("-ational" to "-ate", "-ness", "-ment", "-ize"), each under its own condition on mm.

Porter, Snowball and Lancaster

NLTK provides three rule-based English stemmers that need no downloaded data:

  • PorterStemmer: Porter's algorithm. NLTK's default mode adds a few extensions to the original paper; PorterStemmer(mode="ORIGINAL_ALGORITHM") gives the 1980 rules.
  • SnowballStemmer("english"): Porter's later revision, often called "Porter2", written in his Snowball string-processing language. Snowball stemmers exist for about 15 languages (SnowballStemmer.languages).
  • LancasterStemmer: the Paice/Husk stemmer, which applies its rule table iteratively and is much more aggressive.

Two kinds of error measure a stemmer. Over-stemming merges words with different meanings ("university" and "universe"). Under-stemming fails to merge forms of the same word ("ran" and "run"). The example stems a few words with all three, then counts both errors over 15 families of related words: every pair of words from different families that gets the same stem is an over-stemming error, and every pair from the same family that gets different stems is an under-stemming error.

python · try it yourself
from itertools import combinations
from nltk.stem import PorterStemmer, SnowballStemmer, LancasterStemmer

stemmers = {"porter": PorterStemmer(), "snowball": SnowballStemmer("english"),
            "lancaster": LancasterStemmer()}
show = ["running", "ran", "studies", "studying", "generously", "university",
        "universe", "organization", "organ", "fairly", "happiness", "alumni"]
print(f"{'word':13}" + "".join(f"{n:11}" for n in stemmers))
for w in show:
    print(f"{w:13}" + "".join(f"{s.stem(w):11}" for s in stemmers.values()))

families = [  # words that share a meaning: a good stemmer maps each family to one stem
    ["connect", "connected", "connection", "connecting"], ["generous", "generously", "generosity"],
    ["general", "generally"], ["study", "studies", "studying", "studied"],
    ["university", "universities"], ["universe", "universal"],
    ["organ", "organs"], ["organize", "organization", "organized"],
    ["policy", "policies"], ["police", "policing"], ["absorb", "absorbing", "absorption"],
    ["write", "writes", "writing", "written", "wrote"], ["fair", "fairly", "fairness"],
    ["provide", "provided", "providing", "provision"], ["provident"],
]
words = [w for f in families for w in f]
same_family = {(a, b) for f in families for a, b in combinations(f, 2)}
for name, st in stemmers.items():
    over = under = 0
    for a, b in combinations(words, 2):
        merged = st.stem(a) == st.stem(b)
        related = (a, b) in same_family or (b, a) in same_family
        over += merged and not related
        under += related and not merged
    print(f"{name:9} stems: {len({st.stem(w) for w in words}):2d}  over-stemmed pairs: {over}  under-stemmed pairs: {under}")
print("families:", len(families), " related pairs:", len(same_family))
word         porter     snowball   lancaster
running      run        run        run
ran          ran        ran        ran
studies      studi      studi      study
studying     studi      studi      study
generously   gener      generous   gen
university   univers    univers    univers
universe     univers    univers    univers
organization organ      organ      org
organ        organ      organ      org
fairly       fairli     fair       fair
happiness    happi      happi      happy
alumni       alumni     alumni     alumn
porter    stems: 17  over-stemmed pairs: 17  under-stemmed pairs: 16
snowball  stems: 17  over-stemmed pairs: 13  under-stemmed pairs: 14
lancaster stems: 13  over-stemmed pairs: 18  under-stemmed pairs: 6
families: 15  related pairs: 46

The table shows the characters. Porter and Snowball agree on most words; Snowball is a little more careful ("generously" to "generous", "fairly" to "fair", where Porter makes "gener" and "fairli"). Lancaster cuts deepest ("generously" to "gen", "organization" to "org"), which merges more forms of the same word and more unrelated words. On these 15 families, with 46 related pairs:

Stemmer Distinct stems Over-stemmed pairs Under-stemmed pairs
Porter 17 17 16
Snowball 17 13 14
Lancaster 13 18 6

Snowball makes fewer errors of both kinds than Porter here. Lancaster has the fewest under-stemming errors (6) but the most over-stemming errors (18). None of them merges "ran" with "run": irregular forms cannot be handled by suffix rules at all. The family list is small and chosen to show the errors, so treat the numbers as an illustration; the general pattern (Lancaster aggressive, Snowball a modest improvement on Porter) is the usual finding.

Lemmatisation: rules plus exceptions

A lemmatiser maps a form to a real headword, so it needs to know which headwords exist. NLTK's WordNetLemmatizer looks words up in WordNet, applying WordNet's "morphy" suffix rules and its exception lists. It needs the wordnet data package, which the browser cannot download, so the code is shown without running. Note the part-of-speech argument: without it, every word is treated as a noun.

python
import nltk
nltk.download("wordnet")                   # needs the network once
from nltk.stem import WordNetLemmatizer
wnl = WordNetLemmatizer()
wnl.lemmatize("mice")                      # 'mouse'
wnl.lemmatize("running")                   # 'running'  (pos defaults to noun)
wnl.lemmatize("running", pos="v")          # 'run'
wnl.lemmatize("better", pos="a")           # 'good'

The same design fits in a few dozen lines: an exception dictionary for irregular forms, a lexicon of known lemmas, and an ordered list of suffix rules per part of speech. A rule's result is accepted only if it is in the lexicon (or becomes a lexicon word after undoubling a final consonant), which is exactly what keeps a lemmatiser from producing non-words like "studi".

python · try it yourself
EXCEPTIONS = {
    "noun": {"mice": "mouse", "children": "child", "feet": "foot", "people": "person",
             "men": "man", "women": "woman", "teeth": "tooth", "data": "datum"},
    "verb": {"ran": "run", "went": "go", "was": "be", "were": "be", "is": "be", "are": "be",
             "had": "have", "has": "have", "rode": "ride", "paid": "pay", "took": "take"},
    "adj":  {"better": "good", "best": "good", "worse": "bad", "worst": "bad"},
}
LEXICON = {"bike", "battery", "box", "church", "dock", "station", "ride", "stop", "hope",
           "charge", "unlock", "try", "fix", "pass", "big", "fast", "happy", "mouse", "be"}
RULES = {  # (suffix, replacement), tried in order; the result must be in the lexicon
    "noun": [("ies", "y"), ("ches", "ch"), ("shes", "sh"), ("xes", "x"), ("ses", "s"), ("s", "")],
    "verb": [("ies", "y"), ("es", "e"), ("es", ""), ("s", ""), ("ied", "y"), ("ed", "e"),
             ("ed", ""), ("ing", "e"), ("ing", "")],
    "adj":  [("iest", "y"), ("ier", "y"), ("est", ""), ("er", "")],
}

def undouble(w):
    return w[:-1] if len(w) > 2 and w[-1] == w[-2] and w[-1] not in "lsaeiou" else w

def lemmatise(word, pos="noun"):
    w = word.lower()
    if w in EXCEPTIONS[pos]:
        return EXCEPTIONS[pos][w]
    if w in LEXICON:
        return w
    for suf, rep in RULES[pos]:
        if w.endswith(suf):
            cand = w[: len(w) - len(suf)] + rep
            for c in (cand, undouble(cand)):
                if c in LEXICON:
                    return c
    return w                                # unknown word: leave it unchanged

tests = [("bikes", "noun"), ("batteries", "noun"), ("churches", "noun"), ("boxes", "noun"),
         ("mice", "noun"), ("children", "noun"), ("stations", "noun"), ("riding", "verb"),
         ("rode", "verb"), ("stopped", "verb"), ("hoping", "verb"), ("charged", "verb"),
         ("tries", "verb"), ("passes", "verb"), ("was", "verb"), ("better", "adj"),
         ("biggest", "adj"), ("happier", "adj"), ("quickly", "adj"), ("passes", "noun")]
for w, pos in tests:
    print(f"{w:10} {pos:5} -> {lemmatise(w, pos)}")
bikes      noun  -> bike
batteries  noun  -> battery
churches   noun  -> church
boxes      noun  -> box
mice       noun  -> mouse
children   noun  -> child
stations   noun  -> station
riding     verb  -> ride
rode       verb  -> ride
stopped    verb  -> stop
hoping     verb  -> hope
charged    verb  -> charge
tries      verb  -> try
passes     verb  -> pass
was        verb  -> be
better     adj   -> good
biggest    adj   -> big
happier    adj   -> happy
quickly    adj   -> quickly
passes     noun  -> pass

The exception dictionary handles the irregular forms ("mice", "children", "rode", "was", "better") that no suffix rule can reach. The rules handle the regular ones, and the lexicon check picks the right repair: "hoping" tries "hope" (strip "-ing", add "e") before "hop", "stopped" needs undoubling ("stopp" to "stop"), and "charged" tries "charge" first. The part of speech matters: "passes" as a verb and as a noun both give "pass" here, but "better" is "good" only as an adjective, and "quickly", which is not in the lexicon, is left unchanged rather than mangled. Real lemmatisers work the same way with a full lexicon, many more exceptions and a part-of-speech tagger in front, which makes them slower than stemmers and dependent on the tagger's accuracy.

When it helps: sparse models and search

Stemming and lemmatisation pay off when matching is by exact string: keyword search and bag-of-words models on small data. The example scores four help-centre sentences against three queries by counting shared words, first on raw words and then on Porter stems (a few stop words removed from the queries).

python · try it yourself
import re
from nltk.stem import PorterStemmer

ps = PorterStemmer()
docs = ["Riders can reserve bikes before unlocking them.",
        "A reservation holds a bike for ten minutes.",
        "Unlock the bike by scanning the code.",
        "Charges are shown after each ride."]
queries = ["reserving a bike", "how is a ride charged", "unlocked bikes"]

def tokens(s, stem):
    ws = re.findall(r"[a-z]+", s.lower())
    return {ps.stem(w) for w in ws} if stem else set(ws)

for stem in (False, True):
    print("stemmed" if stem else "raw")
    D = [tokens(d, stem) for d in docs]
    for q in queries:
        qt = tokens(q, stem) - {"a", "how", "is", "the"}
        overlap = [len(qt & d) for d in D]
        print(f"  {q:22} overlap per doc {overlap}")
print(ps.stem("reserve"), ps.stem("reservation"), ps.stem("reserving"), ps.stem("riders"), ps.stem("ride"))
raw
  reserving a bike       overlap per doc [0, 1, 1, 0]
  how is a ride charged  overlap per doc [0, 0, 0, 1]
  unlocked bikes         overlap per doc [1, 0, 0, 0]
stemmed
  reserving a bike       overlap per doc [2, 2, 1, 0]
  how is a ride charged  overlap per doc [0, 0, 0, 2]
  unlocked bikes         overlap per doc [2, 1, 2, 0]
reserv reserv reserv rider ride

With raw words, "reserving a bike" shares nothing with the first document, which is the answer ("Riders can reserve bikes"). After stemming, "reserving", "reserve" and "reservation" all become "reserv" and "bikes" becomes "bike", so the first two documents both match two words. "how is a ride charged" now matches "Charges are shown after each ride" on two words instead of one, and "unlocked bikes" finds both unlocking documents. The last line shows the limits: "riders" becomes "rider", not "ride", so the person and the action stay apart (here that is correct), and a stemmer cannot tell that "reserve" and "reservation" might deserve different treatment in other contexts.

For search engines, stemming is a recall tool: it finds more of the relevant documents, at the price of some wrong matches. Most search engines apply a light stemmer (or a lemmatiser) at both index and query time, and the next lessons use it in BM25 keyword retrieval. For text classification with plenty of data the effect on accuracy is usually small, sometimes negative, because the classifier can learn the variants itself and some suffixes carry signal (tense, number, "-less" against "-ful").

For transformers, do neither. Subword tokenizers already split rare words into shared pieces ("reserving" and "reserved" share their first tokens), and the model was pretrained on unstemmed text: it uses the suffixes, and stemmed input ("the bike was reserv") is out of distribution. The same goes for dense retrieval with sentence embeddings.

Pitfalls

  • Stemming the documents but not the queries (or with a different stemmer). Both sides must go through the same function, or nothing matches.
  • Showing stems to users. Stems are internal keys; display the original words and highlight them from the original text.
  • Lemmatising without a part of speech. WordNet's lemmatiser defaults to nouns, so "running" stays "running"; tag first, or pass pos explicitly.
  • Assuming suffix rules transfer to other languages. Use the language's own Snowball stemmer, and for languages with rich morphology (Finnish, Turkish, Arabic) a morphological analyser.
  • Stemming names and codes. "Gates" becomes "gate", a product code such as "TX-100s" is mangled; protect entities and placeholders before stemming.

Practice

  1. Compute the Porter measure mm of "bicycle" and of "ride". Would the rule "(m > 1) ATE →\to nothing" fire on "private"?
  2. Why does "sing" keep its "-ing" in step 1b while "motoring" loses it?
  3. In the stemmer comparison, Lancaster has the fewest under-stemmed pairs but the most over-stemmed ones. When could that trade-off be acceptable?
  4. Add "geese" →\to "goose" and "taught" →\to "teach" to the lemmatiser. Which part of the design do they go in, and why not in the rules?
  5. You fine-tune a BERT classifier on Porter-stemmed text. Give two reasons the result is likely worse than on raw text.
Answers
  1. "bicycle" is b-i-c-y-c-l-e = C V C V C C V, where "y" after the consonant "c" is a vowel: the form is C (VC)(VC) V, so m=2m = 2. "ride" is C V C V, so m=1m = 1. For "private", the stem before "ate" is "priv" = C C V C, m=1m = 1, so the condition m>1m > 1 fails and the rule does not fire.
  2. Step 1b removes "-ing" only if the remaining stem contains a vowel. "s" has none, so "sing" stays; "motor" has two, so "motoring" becomes "motor".
  3. When recall matters much more than precision: a first-stage search over a small collection where a person (or a reranker) looks at the candidates anyway, so extra wrong matches cost little and missed documents cost a lot.
  4. In the exception dictionary (nouns: "geese"; verbs: "taught"). They are irregular: no suffix rule maps "geese" to "goose" or "taught" to "teach", and a rule general enough to do it would break many other words.
  5. BERT's tokenizer and weights were trained on unstemmed text, so stems such as "reserv" and "studi" become unusual token sequences the model has rarely seen; and stemming throws away information the model can use (tense, number, derivational suffixes), with nothing gained because subword tokenization already shares pieces between related forms.

Test yourself

What is the Porter measure mm of the stem "oats"?

  1. 0
  2. 1
  3. 2
  4. 3

Which stemmer produced the fewest under-stemmed pairs on the 15 word families?

  1. Porter
  2. Snowball
  3. Lancaster
  4. All three tied

Why does the from-scratch lemmatiser need an exception dictionary?

  1. To speed up the suffix rules
  2. Irregular forms such as "mice" or "rode" cannot be reached by suffix rules
  3. To store the stems
  4. Because Python has no string methods for suffixes

For which model is stemming usually a bad idea?

  1. BM25 keyword search
  2. A bag-of-words classifier on 500 documents
  3. A fine-tuned transformer with a subword tokenizer
  4. A boolean search over an inverted index