Sub topic 14
Controlling Vocabulary Size
Prerequisites
This chapter assumes you understand tokenization, document-term matrices, TF-IDF, and basic Python. The examples use scikit-learn vectorizers and a small list of documents.
A vectorizer creates one feature for each vocabulary term. A large vocabulary can improve coverage, but it also creates more columns, uses more memory, and may include spelling mistakes, names, or terms that occur only once. Vocabulary pruning means removing terms that are unlikely to help the task.
The main pruning controls
min_df removes rare terms. It accepts either an integer document count or a fraction of the documents.
max_df removes overly common terms. It also accepts a count or a fraction. This is useful for words that appear in nearly every document and therefore provide little distinction.
max_features keeps only a fixed number of terms after the other filtering rules are applied. The vectorizer chooses terms by corpus frequency, so this option gives a predictable upper bound on the number of columns.
| Parameter | Example | Effect |
|---|---|---|
| `min_df` | `2` | Keep terms in at least two documents |
| `max_df` | `0.8` | Remove terms in more than 80% of documents |
| `max_features` | `10_000` | Keep at most 10,000 terms |
from sklearn.feature_extraction.text import TfidfVectorizer
docs = [
"red apples are sweet",
"green apples are crisp",
"red pears are sweet",
"green pears are crisp",
"apples and pears are fruit",
]
vectorizer = TfidfVectorizer(
min_df=2,
max_df=0.8,
max_features=4,
)
X = vectorizer.fit_transform(docs)
print(vectorizer.get_feature_names_out())
print("shape:", X.shape)Here, a term must occur in at least two documents. Terms occurring in more than 80% of documents are removed. The final matrix has no more than four columns.
Choosing the thresholds
Use a document count when the corpus size is fixed and the rule has a clear meaning. For example, min_df=3 removes terms that appear in only one or two documents.
Use a fraction when the corpus may grow. min_df=0.01 requires a term to appear in at least 1% of documents. The resulting count changes as the dataset changes.
Start with mild filtering, inspect validation results, and then increase pruning if training is slow or rare terms cause overfitting. Classification and search tasks may need different vocabularies.
A useful selection process
Common errors include setting min_df so high that useful terms disappear, using max_features without measuring validation performance, and fitting separate vocabularies for training and test data. A single fitted vectorizer must define the feature columns for every later dataset.
Exercise
A corpus has 1,000 documents. What does mindf=0.02 require, and what does maxdf=0.9 remove?
Show answer
mindf=0.02 requires a term to appear in at least 20 documents. maxdf=0.9 removes terms appearing in more than 900 documents.