Sub topic 5
N-grams, min_df, and Controlling Vocabulary Size
This chapter assumes basic Python, supervised learning, and the idea that a training set must be kept separate from evaluation data. It also assumes you have seen TF-IDF and sparse matrices. We will focus on how a vectorizer decides which text patterns become features.
Why single words are sometimes not enough
A unigram is a single word. With ngram_range=(1, 1), TfidfVectorizer creates one feature for each selected word.
This representation is simple, but word order disappears. The phrases “not useful” and “useful, not” contain the same two unigrams. A classifier cannot distinguish their different meanings from unigrams alone.
A bigram is a sequence of two adjacent tokens. A trigram has three tokens. For example:
| Text | Unigrams | Bigrams |
|---|---|---|
| `the engine failed` | `the`, `engine`, `failed` | `the engine`, `engine failed` |
When ngram_range=(1, 2), the vectorizer includes both unigrams and bigrams. When it is (2, 2), it includes only bigrams.
N-grams can capture useful expressions such as credit card, space station, or not recommended. They also increase the number of features quickly. Most possible word sequences are rare, so many n-gram columns contain mostly zeros.
from sklearn.feature_extraction.text import TfidfVectorizer
documents = [
"the engine failed",
"the engine started",
"a new engine started",
]
vectorizer = TfidfVectorizer(ngram_range=(1, 2), min_df=1)
matrix = vectorizer.fit_transform(documents)
print(vectorizer.get_feature_names_out())
print(matrix.shape)The output contains individual words and phrases such as engine, started, and engine started. The exact TF-IDF values depend on the document frequencies of these features.
Controlling rare features with `min_df`
min_df means minimum document frequency. Document frequency is the number of documents that contain a term at least once. It is different from the total number of times the term appears.
For example, if a term appears five times in one document and nowhere else, its document frequency is one. With min_df=2, that term is removed.
You can provide min_df as:
- An integer, such as
2, requiring a term to appear in at least two documents. - A fraction, such as
0.01, requiring a term to appear in at least 1% of documents.
Increasing min_df removes spelling mistakes, one-off names, and rare n-grams. This reduces memory use and can improve generalization. However, an informative term that appears in only one training document will also be removed.
The threshold is calculated from the data passed to fit. In a properly constructed pipeline, this means the training fold only. Do not fit the vectorizer on the complete dataset before splitting, because vocabulary selection would then use information from the evaluation data.
Other vocabulary controls
max_features keeps only a limited number of features. The vectorizer ranks candidate features by term frequency and retains the highest-ranking ones. This provides a memory limit, but it can discard rare features that are useful for a small class.
max_df removes terms that occur in too many documents. A value such as 0.9 removes terms found in more than 90% of documents. These terms often carry little information. stop_words="english" is another way to remove common English words, but a built-in stop-word list can remove words that matter in a particular domain.
Use these settings together carefully:
vectorizer = TfidfVectorizer(
ngram_range=(1, 2),
min_df=2,
max_df=0.95,
max_features=50_000,
sublinear_tf=True,
)sublinear_tf=True replaces raw term frequency with 1 + log(term frequency). Repeating a word ten times then has less than ten times the influence of using it once. This can help when documents contain repeated boilerplate.
Choosing an n-gram range
Start with unigrams when the dataset is small or the vocabulary is already large. Try (1, 2) when short phrases carry meaning. Larger n-grams usually need more training data and stronger vocabulary limits.
Choose these settings through validation rather than by inspecting the test set. A bigram setting that scores well on one split may overfit accidental phrases. Include the vectorizer and classifier in the same pipeline so each validation fold learns its own vocabulary.
Exercise
A corpus has 100 documents. You set min_df=0.05. What is the smallest number of documents in which a term must appear to remain in the vocabulary?
Show answer
It must appear in at least 5 documents, because 0.05 × 100 equals 5.