Stemming cuts words down to a root form by chopping off endings: “programs”, “programming” and “programmer” all become “program”. It reduces the number of different words a model has to learn, which helps search engines and simple classifiers.
What You Will Learn
- How the Porter stemmer works
- Lancaster and Regexp stemmers
- The weaknesses of stemming
- Stemming vs lemmatization
Prerequisites
Porter Stemmer
from nltk.stem import PorterStemmer
from nltk.tokenize import word_tokenize
port = PorterStemmer()
for w in ["program", "programs", "programer", "programing", "programers"]:
print(port.stem(w), end=" ")
print()
text = "He eats what he was eating yesterday at the eatery"
print([port.stem(w) for w in word_tokenize(text)])
program program program program program ['he', 'eat', 'what', 'he', 'wa', 'eat', 'yesterday', 'at', 'the', 'eateri']
Explanation: All five forms collapse to “program”. But stems need not be real words: “was” becomes “wa” and “eatery” becomes “eateri”. Porter also lowercases by default in newer NLTK versions.
text = "It is very important to be pythonly while you are pythoning with python."
print([port.stem(w) for w in word_tokenize(text)])
['it', 'is', 'veri', 'import', 'to', 'be', 'pythonli', 'while', 'you', 'are', 'python', 'with', 'python', '.']
Explanation: “important” becomes “import” – a different word. This is over-stemming, the main risk of stemming.
Other Stemmers
from nltk.stem import LancasterStemmer, RegexpStemmer
print(LancasterStemmer().stem("beautiful"))
rstem = RegexpStemmer("ing")
print(rstem.stem("skipping"), rstem.stem("King"))
beauty skipp K
Explanation: Lancaster is more aggressive than Porter. A Regexp stemmer removes whatever pattern you give it – here every “ing”, which wrongly turns “King” into “K”. Use it only for simple, controlled cases.
Stemming vs Lemmatization
| Stemming | Lemmatization | |
|---|---|---|
| Method | Rule-based chopping | Dictionary lookup with part of speech |
| Output | May not be a real word (“veri”) | Always a real word (“very”) |
| Speed | Faster | Slower |
| Example: “better” | “better” | “good” (as adjective) |
See Lemmatization.
Series
NLP series: Introduction · Tokenizer · Stop Words · Stemming · Lemmatization · WordNet · NLTK Practice · Spam Detection Project · Text to Speech · Speech Assistant · NLP Project Ideas
Interview Questions
Q: What is over-stemming?
When different words are reduced to the same stem, e.g. “important” and “import”.
Q: When is stemming good enough?
For search and bag-of-words models where speed matters more than exact words.
Practice Exercises
- Stem every word of a news paragraph and count unique words before and after.
- Compare Porter and Lancaster on 10 words.
Summary
Stemming chops words to rough roots, reducing vocabulary size quickly but sometimes producing non-words or merging unrelated words.
Next: Lemmatization
Machine Learning Tutorials, Courses and Certifications