Sub topic 3
Lowercasing and stop words
This chapter covers two normalization steps that run before the vocabulary is built: lowercasing and stop-word removal. It assumes you know what a token is, have used CountVectorizer once, and can read short NumPy and scikit-learn snippets.
Why normalize at all
A bag-of-words model treats each distinct token string as a separate column. Without normalization, "The", "the" and "THE" become three unrelated features. Each of the three gets only a fraction of the evidence, so the model sees weaker patterns. Normalization merges strings that mean the same thing, which shrinks the vocabulary and concentrates the counts.
Normalization also discards information, so each step is a trade-off. This chapter looks at two of them.
Lowercasing
Lowercasing converts every character to lower case before tokenization. In scikit-learn it is on by default (lowercase=True), and it happens in the preprocessing stage, before the text is split into tokens.
from sklearn.feature_extraction.text import CountVectorizer
docs = ["The cat sat", "the Cat sat on the mat"]
raw = CountVectorizer(lowercase=False).fit(docs)
lowered = CountVectorizer(lowercase=True).fit(docs)
print(len(raw.vocabulary_))
print(len(lowered.vocabulary_))This prints 7 and 5. With lowercasing off, "The" and "the" are separate features, and so are "Cat" and "cat". With it on, they merge.
When lowercasing hurts
Case sometimes carries meaning:
- "US" (the country) and "us" (the pronoun) collapse into one token.
- "Apple" (the company) and "apple" (the fruit) collapse into one token.
- In some tasks, such as spam detection, all-caps words like "FREE" are themselves a signal.
For most topic and sentiment tasks, the vocabulary reduction outweighs these losses. If case matters for your task, set lowercase=False and compare cross-validated scores instead of guessing.
Stop words
Stop words are very common words, such as "the", "on", "and" and "was", that carry little topical content. Removing them has three effects:
- The vocabulary is smaller.
- The matrix is a little less dense.
- Counts and cosine similarity are no longer dominated by words that appear in almost every document.
scikit-learn ships one built-in list, selected with stop_words="english". You can also pass your own list.
from sklearn.feature_extraction.text import CountVectorizer, ENGLISH_STOP_WORDS
docs = ["the movie was good", "the movie was not good"]
print("not" in ENGLISH_STOP_WORDS)
vec = CountVectorizer(stop_words="english")
X = vec.fit_transform(docs)
print(vec.get_feature_names_out())
print(X.toarray())The first line prints True. The built-in list contains "not", so both reviews reduce to the same two-word bag, "movie" and "good". The matrix has two identical rows, even though the reviews express opposite opinions.
Keeping negations
The usual fix is to subtract the words you want to keep from the built-in list and pass the result as a list.
from sklearn.feature_extraction.text import CountVectorizer, ENGLISH_STOP_WORDS
docs = ["the movie was good", "the movie was not good"]
custom = sorted(ENGLISH_STOP_WORDS - {"not", "no", "nor"})
vec = CountVectorizer(stop_words=custom)
X = vec.fit_transform(docs)
print(vec.get_feature_names_out())
print(X.toarray())The output is ['good' 'movie' 'not'] and then [[1 1 0] [1 1 1]]. The two reviews are now distinguishable.
Where the steps run
The order of operations matters when you combine these options with n-grams.
Two consequences follow from this order:
- Stop words are removed before n-grams are built. With
ngram_range=(1, 2), the text "cat on the mat" becomes the tokens "cat" and "mat", and then the bigram "cat mat". The phrase never occurred in the text, and word adjacency has been distorted. Keep this in mind if bigrams matter to your task. - The stop list is matched against lowercase tokens. The built-in list is lower case. If you set
lowercase=False, the token "The" does not match "the" and is not removed.
Choosing a policy
| Situation | Suggested setting |
|---|---|
| Topic classification, search, clustering | Lowercase on, built-in stop words are usually fine |
| Sentiment analysis | Lowercase on, remove stop words only after keeping negations such as "not" and "no" |
| Phrase features with bigrams or trigrams | Consider leaving stop words in, so phrases like "out of stock" survive |
| Case-sensitive signals (spam, named entities) | `lowercase=False`, or add separate case features |
| Domain-specific text (legal, medical) | Build a custom list from document frequency, because generic lists miss domain-common words |
Stop words and TF-IDF
TF-IDF already gives low weight to words that appear in most documents, so stop-word removal matters less there than with raw counts. It still helps: it shrinks the vocabulary and removes noise from the L2 norm of each row. A data-driven alternative is max_df, which drops any term that appears in more than a given fraction of documents. For example, max_df=0.8 removes terms found in over 80% of documents. The next chapters cover this.
Common errors
- Using the built-in list on every task. The list contains words such as "not", "no", "never" and "without" (check with
in ENGLISH_STOP_WORDS). Removing them can erase the signal you need. - Assuming the list fits your language.
stop_words="english"is the only built-in option. For other languages, supply your own list. - Removing too much. If a rare but important word is in the list, the model never sees it. Inspect
get_feature_names_out()after fitting. - Mismatched custom lists. If your stop words do not match what your tokenizer produces (for example, a stop word that your tokenizer would split into pieces), scikit-learn may warn that the list is inconsistent with the tokenizer.
Exercise
You fit CountVectorizer(lowercase=False, stop_words="english") on the text "The cat sat on the mat". Is "The" removed? Explain why or why not.
Show answer
No. The built-in stop list is lower case, and with lowercase=False the token is "The", which does not match "the". The second "the" in the sentence is removed, but "The" stays in the vocabulary, along with "cat", "sat" and "mat". To remove both, leave lowercase=True or supply a stop list that includes capitalized forms.
Exercise
A sentiment classifier must tell "good" from "not good". Which scikit-learn option causes trouble with the default stop list, and how do you fix it?
Show answer
stopwords="english" is the problem, because the built-in list includes "not". Build a custom list with sorted(ENGLISHSTOPWORDS - {"not", "no", "nor"}) and pass it as stopwords.