Sub topic 7
Stemming by suffix stripping
This chapter assumes you can write basic Python (strings, lists, functions, regular expressions). It also assumes you know what a token is and what inflection and derivation mean. Both were covered in earlier chapters. You do not need NLTK for the hand-written examples. The library comparisons at the end do need it.
What a stemmer is for
A stemmer maps related word forms to one shared key, called a stem. After stemming, "connect", "connected", "connecting" and "connection" can all become "connect". A search index that stores the stem finds a document about "connected devices" when the user types "connecting device".
The goal is conflation, meaning that related forms collapse to the same string. A stemmer does not need to produce a real word. It only needs to produce the same string for words you want treated as equal, and different strings for words you want kept apart. This explains why Porter's stemmer returns "studi" for "studies". Nobody reads "studi"; the index only compares it.
A stemmer is also fast and needs no dictionary. It looks at one word at a time, with no sentence context, and edits the end of the string using rules.
A first, naive suffix stripper
The simplest stemmer is a list of suffixes. For each word, remove the first suffix that matches, and leave very short remainders alone.
SUFFIXES = ["ational", "ization", "ness", "ing", "ed", "es", "s"]
def strip_suffix(word, min_stem=3):
for suffix in SUFFIXES:
if word.endswith(suffix) and len(word) - len(suffix) >= min_stem:
return word[:-len(suffix)]
return word
for w in ["walking", "walked", "walks", "running",
"glass", "sing", "ponies", "happiness"]:
print(w, "->", strip_suffix(w))The output is:
walking -> walk
walked -> walk
walks -> walk
running -> runn
glass -> glas
sing -> sing
ponies -> poni
happiness -> happiThe first three words work. The rest show the problems that every real stemmer has to handle:
- "running" becomes "runn" because the doubled consonant, added by English spelling when "-ing" is attached, is not undone. "run" and "running" now have different stems.
- "glass" becomes "glas" because the final "s" looks like a plural marker. The word is not plural.
- "sing" survives only because of the
min_stemguard. Without it, "sing" would be cut to "s". - "ponies" and "happiness" give "poni" and "happi". These are not words, but they are consistent, which is enough for conflation. The singular "pony" does not become "poni", though, so plural and singular stay apart.
Each failure suggests a repair: undo doubled consonants, treat "ss" as a special case, and enforce a minimum stem. Porter's algorithm is a disciplined collection of such repairs.
Conditions make rules safe
A rule that fires on every matching suffix is too blunt. The Porter stemmer attaches a condition on the remaining stem to most rules. The most important condition uses the measure, written m.
Porter describes every word as an alternating pattern of consonant groups and vowel groups. Write C for a run of consonants and V for a run of vowels. Every word then has the form [C](VC)^m[V], where the brackets mean optional. The measure m counts the repeated vowel-consonant pairs. It is a rough proxy for the number of syllables in the stem.
| Word | Pattern | m |
|---|---|---|
| tree | CV | 0 |
| by | CV | 0 |
| trouble | CVCV | 1 |
| oats | VC | 1 |
| troubles | CVCVC | 2 |
| private | CVCVCV | 2 |
In Porter's scheme, "y" counts as a vowel when it follows a consonant and as a consonant otherwise. This function computes m:
import re
def measure(stem):
form = ""
for i, ch in enumerate(stem):
is_vowel = ch in "aeiou" or (ch == "y" and i > 0 and form[-1] == "C")
form += "V" if is_vowel else "C"
collapsed = re.sub(r"(.)\1+", r"\1", form)
return collapsed.count("VC")
for w in ["tree", "by", "trouble", "oats", "troubles", "private"]:
print(w, measure(w))This prints 0, 0, 1, 1, 2 and 2, matching the table.
The measure lets a rule say "remove this suffix only if enough stem remains". For example, a rule that strips "-ement" can require m > 1. Then "replacement" becomes "replac", while "cement" is left alone. After removing "-ement", "cement" would leave "c", which has m = 0. The condition protects short roots without a hand-made exception list.
How Porter's algorithm is organised
The algorithm runs a fixed sequence of steps. Within a step, it looks for the longest matching suffix among its rules and applies only that one rule. Then it moves to the next step.
The steps work in two groups:
- Steps 1a to 1c deal with inflection: plurals, past tense, and progressive forms.
- Steps 2 to 4 deal with derivation. They first rewrite long suffixes into shorter ones, for example "-ational" to "-ate", and then delete the shorter ones.
- Step 5 cleans up leftovers.
Step 1a is small enough to implement in full. Its four rules are listed from longest suffix to shortest, so the first match is also the longest.
RULES_1A = [("sses", "ss"), ("ies", "i"), ("ss", "ss"), ("s", "")]
def step_1a(word):
for suffix, replacement in RULES_1A:
if word.endswith(suffix):
return word[:len(word) - len(suffix)] + replacement
return word
for w in ["caresses", "ponies", "ties", "caress", "cats"]:
print(w, "->", step_1a(w))The output is:
caresses -> caress
ponies -> poni
ties -> ti
caress -> caress
cats -> catThe ("ss", "ss") rule looks like it does nothing, and that is its purpose. It matches "caress" before the bare "s" rule gets a chance, so the word is left whole. It also shows how the longest-match order does the work of an exception list. If you put the "s" rule first, "caress" would become "cares".
Step 1b: rules with repairs
Step 1b removes "-ed" and "-ing", but only when the remaining stem contains a vowel. This is why "sing" is protected, since "s" has no vowel, and why "plastered" becomes "plaster". After a removal, a cleanup phase repairs the stem:
- If the stem ends in "at", "bl" or "iz", add "e". For example, "conflating" becomes "conflat" and then "conflate".
- If the stem ends in a doubled consonant other than "l", "s" or "z", drop one. For example, "running" becomes "runn" and then "run". "Falling" keeps its "ll".
- If the stem is short (m = 1) and ends consonant-vowel-consonant, where the last consonant is not "w", "x" or "y", add "e". For example, "hoping" becomes "hop" and then "hope", which stays distinct from "hopping", which becomes "hop".
This is the fix for the "runn" failure in the naive stripper. You can see how much of the algorithm consists of spelling-rule repairs, not suffix tables.
Snowball and the Porter family
The original Porter algorithm was published in 1980. Its author later released Snowball, a small language for writing stemming algorithms, and used it to write an improved English stemmer, often called Porter2. Snowball also has stemmers for many other languages.
In NLTK, PorterStemmer is the original algorithm with a few extensions, and SnowballStemmer("english") is Porter2. Run both to compare:
from nltk.stem import PorterStemmer, SnowballStemmer
porter = PorterStemmer()
snowball = SnowballStemmer("english")
for word in ["caresses", "ponies", "running", "studies",
"university", "universe", "organization", "organ"]:
print(word, porter.stem(word), snowball.stem(word))The two stemmers agree on most common words. For "caresses", "ponies", "running" and "studies" they produce "caress", "poni", "run" and "studi". Differences appear on less common forms, so compare them on your own vocabulary instead of assuming they are interchangeable. The Snowball English stemmer is generally the better default. Pick one stemmer and use it consistently, because stems from different algorithms do not match each other.
Where suffix stripping fails
Because rules see only spelling, they make two kinds of error. The next chapter covers them in detail, so a short preview is enough here.
- Overstemming merges words that should stay apart. The Porter stemmer reduces both "university" and "universe" to "univers", and both "organization" and "organ" to "organ". A search for "universe" then returns documents about universities.
- Understemming leaves related words with different stems. The stemmer cannot connect "ran" and "running", or "data" and "datum", because no suffix rule links them.
Making a rule set more aggressive reduces understemming and increases overstemming. A rule set that is more conservative does the opposite. You cannot remove both errors, and you only choose where to sit on the trade-off.
Using stemmers correctly
Several practical points avoid the most common mistakes.
- Order matters. Tokenise first, then case-fold, then stem. Porter's rules expect lower-case input. Stemming a capitalised word can skip rules that would otherwise apply.
- Use the same stemmer on both sides. In search, you must stem the documents at index time and the query at search time with the same algorithm and version. If the two sides differ, the stems will not match and recall drops with no error message.
- Do not show stems to users. Keep the original surface form for display and use the stem only as a matching key. A highlighted "studi" in a results page looks like a bug.
- Check the language. An English stemmer applied to French or German text produces nonsense. Choose the stemmer by language, and detect the language first if your data is mixed.
- Treat names and identifiers separately. Product codes, surnames and technical terms such as "Adams" or "Paris" get stemmed like ordinary words. If those matter, exclude them from stemming, for example with a keyword list.
Summary
Suffix stripping reduces words to a shared key with ordered rules and conditions on the remaining stem. Porter's measure m guards against stripping too much from short words. The longest-match order inside each step does the work of exceptions. The cost is that stems are not always words and errors in both directions are unavoidable. The next chapters look at those errors more closely and at the dictionary-based alternative, lemmatisation.
Exercise
Compute the measure m of "oaten" and "orrery". Then say what step_1a from this chapter returns for "ties" and for "bus", and why the result for "bus" is a warning sign for this rule set.
Show answer
For "oaten": o and a are vowels, t is a consonant, e is a vowel, n is a consonant, so the pattern is VCVC, which gives m = 2 (the leading vowel run is allowed, since the form is [C](VC)^m[V]). For "orrery": o is V, rr is C, e is V, r is C, y follows a consonant so it counts as a vowel, giving VCVCV, so m = 2. step1a("ties") returns "ti", because "ies" is replaced by "i". step1a("bus") returns "bu", because only the bare "s" rule matches and nothing checks that the remaining stem is long enough or that the word is really plural. The result shows that the plain rules carry no minimum-stem condition, so very short words can be damaged.
Exercise
Extend strip_suffix from this chapter so that "running" becomes "run" while "falling" keeps its double "l" and becomes "fall". Which rule from Porter's step 1b cleanup are you reimplementing?
Show answer
After removing "ing" or "ed", check whether the stem ends in two identical consonants and, if so, drop one unless the consonant is "l", "s" or "z". For example: if len(stem) > 1 and stem[-1] == stem[-2] and stem[-1] not in "aeiou" and stem[-1] not in "lsz": stem = stem[:-1] "runn" becomes "run", and "fall" stays "fall". This is the doubled-consonant rule of step 1b's cleanup phase.