Sub topic 14
Controlling vocabulary size
This chapter assumes you can run CountVectorizer and TfidfVectorizer and know what a document-term matrix is. It covers how to shrink the vocabulary on purpose, which settings do it, and what can go wrong.
Why the vocabulary needs limits
Every distinct token becomes a column in the document-term matrix. Vocabulary size grows with corpus size. A rough rule (Heaps' law) says it grows like N^β, where N is the number of tokens and β is usually between 0.4 and 0.6. Real corpora also contain typos, product codes, names and numbers that appear once.
Large vocabularies cause three problems:
- Memory and speed. A linear classifier stores one weight per column per class. Matrix operations touch more columns.
- Overfitting. A term seen in one training document can only memorize that document. It cannot generalize.
- Noise in similarity. Rare terms add dimensions that carry no shared signal.
N-grams make this worse. Each distinct bigram is a new column, and most bigrams occur once. Pruning is nearly mandatory once you use ngram_range=(1, 2) on a real corpus.
The three pruning parameters
| Parameter | Default | Removes | Typical use |
|---|---|---|---|
| `min_df` | 1 | Terms in fewer documents than the threshold | Typos, one-off identifiers |
| `max_df` | 1.0 | Terms in more documents than the threshold | Corpus-specific stop words |
| `max_features` | None | Everything outside the top N terms by total count | A hard cap on matrix width |
min_df and max_df accept two kinds of value:
- An int is an absolute number of documents.
- A float in [0.0, 1.0] is a proportion of documents.
So max_df=0.9 and max_df=2 mean different things on a three-document corpus. A common source of bugs is writing min_df=1.0 and getting a proportion, not a count of one.
max_features ranks terms by their total count across the whole corpus, not by document frequency. A term repeated 500 times in one document can outrank a term that appears once in each of 100 documents.
Scikit-learn applies the filters in a fixed order, shown below.
Seeing the effect on a toy corpus
The three-document corpus has these document frequencies: the 3; cat, dog, on and sat 2 each; chased, log and mat 1 each.
from sklearn.feature_extraction.text import CountVectorizer
docs = [
"the cat sat on the mat",
"the dog sat on the log",
"the cat chased the dog",
]
settings = {
"default": {},
"min_df=2": {"min_df": 2},
"max_df=0.9": {"max_df": 0.9},
"min_df=2, max_df=0.9": {"min_df": 2, "max_df": 0.9},
"max_features=3": {"max_features": 3},
}
for name, kwargs in settings.items():
vec = CountVectorizer(**kwargs).fit(docs)
print(f"{name:22} {len(vec.vocabulary_)} terms: {sorted(vec.vocabulary_)}")The vocabulary sizes are 8, 5, 7, 4 and 3, in the order of the dictionary.
min_df=2dropschased,logandmat.max_df=0.9dropsthe, because 3/3 = 1.0 exceeds 0.9.- Combining both leaves
cat,dog,onandsat. max_features=3keepsthe(total count 6) and then breaks ties among count-2 terms, so don't rely on which two it picks.
Pruning n-grams
Bigrams show why min_df matters. This compares vocabulary sizes with and without it.
from sklearn.feature_extraction.text import CountVectorizer
docs = [
"the cat sat on the mat",
"the dog sat on the log",
"the cat chased the dog",
]
for min_df in (1, 2):
vec = CountVectorizer(ngram_range=(1, 2), min_df=min_df).fit(docs)
print(min_df, len(vec.vocabulary_))
try:
CountVectorizer(min_df=4).fit(docs)
except ValueError as err:
print("ValueError:", type(err).__name__)This prints 1 18 and 2 9. Eight unigrams plus ten bigrams give 18 columns. Requiring two documents keeps five unigrams and four bigrams (the cat, sat on, on the, the dog). The last call raises ValueError, because no term can appear in four of three documents.
How pruning interacts with TF-IDF
- Pruning happens before weighting. With
TfidfVectorizer, the IDF values of kept terms do not change, because document frequency is computed from the same documents. The row L2 norms do change, since removed terms no longer contribute. Surviving weights get slightly larger. - Fit-time only. The pruned vocabulary is learned in
fit. Attransformtime, unseen terms and pruned terms are silently ignored. Document frequency thresholds computed on test data would be leakage, so keep the vectorizer inside a pipeline. - Rows can become empty. A short document made only of pruned terms becomes an all-zero row. Its cosine similarity to anything is 0, and a classifier sees a bias-only input. Count such rows with
X.getnnz(axis=1) == 0and decide how to handle them.
Choosing values
There is no universal setting. Start with these and check on validation data:
min_df. Use 2 to 5 for corpora of thousands of documents. Use a small float such as 0.001 when corpus size varies. Leave it at 1 for tiny corpora, where it would remove most of the vocabulary.max_df. Use 0.5 to 0.95 to catch domain-specific filler such as "patient" in clinical notes. A fixed stop word list will not catch these. Lower values risk removing terms that separate classes.max_features. Use it when you need a predictable memory budget, such as 50,000 columns. It is a blunt tool, so trymin_dffirst.- Tune in a pipeline. Put the vectorizer and classifier in one
Pipeline. Search overtfidfvectorizer__min_dfand friends with cross-validation, so each fold learns its own vocabulary.
Check the result with len(vec.vocabulary_) and the matrix shape before and after. If accuracy barely changes while the width drops by 10x, the pruning is paying off.
Common mistakes
- Using
min_df=1.0expecting "at least one document". It means "in 100% of documents". - Setting
max_dfsmaller thanmin_df. Scikit-learn raises aValueError. - Applying
max_featuresto rank by document spread. It ranks by total count. - Pruning very hard and then wondering why many documents have no features.
- Fitting on the full dataset before splitting, which leaks test-set document frequencies into the vocabulary.
When pruning is not enough
If even a pruned vocabulary does not fit in memory, or you cannot hold a vocabulary dictionary at all (streaming data, billions of n-grams), a hashed representation avoids storing the mapping. That is the topic of the hashing trick, later in this tutorial.
Exercise
You fit CountVectorizer(mindf=2, maxdf=2) on the three-document toy corpus ("the cat sat on the mat", "the dog sat on the log", "the cat chased the dog"). Which terms remain, and why is the not among them?
Show answer
The remaining terms are cat, dog, on and sat. Each appears in exactly 2 documents, which satisfies both mindf=2 (at least 2) and maxdf=2 (at most 2). The term the appears in all 3 documents, which exceeds maxdf=2, so it is dropped. The terms chased, log and mat appear in only 1 document and fail mindf=2.
Exercise
A term appears 40 times in a single document and nowhere else. Another term appears once in each of 30 different documents. With maxfeatures=1 on this corpus, assuming no other terms matter, which is kept, and which would mindf=2 keep?
Show answer
maxfeatures=1 keeps the first term, because it ranks by total corpus count (40 versus 30). mindf=2 keeps the second term, because it appears in 30 documents, while the first appears in only 1 document and is removed.