Sub topic 5
N-grams, min_df, and controlling vocabulary size
This chapter assumes you can fit a TfidfVectorizer and read a sparse document-term matrix, as covered in the previous chapters on bag-of-words and TF-IDF. It also assumes you know why a vectorizer must be fit on training data only. Here you will see how the vocabulary is built, how n-grams enlarge it, and which parameters keep it to a useful size.
Why the vocabulary needs control
Every distinct term the vectorizer keeps becomes one column of the document-term matrix and one coefficient in the logistic regression. On a real corpus, the number of distinct words is large. Most of them appear in only one or two documents.
Those rare terms cause three problems:
- Memory and speed. More columns mean larger coefficient arrays and slower training.
- Overfitting. A term seen in one training document can act as an identifier for that document. A linear model can use it to memorize the document's label, and the weight does not carry over to new text.
- Noise. Typos, ids, and names fill the vocabulary and carry almost no signal.
Controlling the vocabulary means keeping terms that occur often enough to generalize and dropping the rest.
N-grams: recovering some word order
A bag-of-words model discards order. "Not good" and "good, not bad" look alike if you only count the single words "good" and "not". An n-gram is a sequence of n consecutive tokens. A unigram is one token, a bigram is two, and a trigram is three.
You request n-grams with ngram_range=(min_n, max_n). The range (1, 2) means "all unigrams and all bigrams".
from sklearn.feature_extraction.text import CountVectorizer
docs = ["the movie was not good", "the movie was good"]
for ngram in [(1, 1), (1, 2)]:
vec = CountVectorizer(ngram_range=ngram)
vec.fit(docs)
print(ngram, list(vec.get_feature_names_out()))With (1, 2) the vocabulary contains not good and was good as separate features. The model can now give "not good" its own weight, which a unigram model cannot do. The cost is a larger vocabulary.
How fast the vocabulary grows
A document with T tokens produces about T unigrams and T-1 bigrams. The number of tokens per document roughly doubles, but the number of distinct terms across the corpus grows faster. Most bigrams occur once, because most word pairs are rare. Adding trigrams makes this worse.
Practical guidance:
(1, 2)is a common choice and often gives a modest gain over unigrams.(1, 3)rarely pays off in a bag-of-words linear model unless you have a lot of data and a strongmin_df.- Always prune rare n-grams when you use n-grams. Without pruning, most of the new columns are one-off phrases.
The parameters that control vocabulary
| Parameter | What it does | Typical use |
|---|---|---|
| `min_df` | Drops terms appearing in fewer documents than the threshold. An int is a document count. A float is a fraction of documents. | `2` to `5` for small corpora, `0.001` for large ones |
| `max_df` | Drops terms appearing in more documents than the threshold. | `0.5` to `0.95` to remove near-universal words |
| `max_features` | Keeps only the top terms, ranked by total count across the corpus. | A hard cap such as `20000` when memory is a constraint |
| `stop_words` | Removes listed words before n-grams are built. | `"english"` with care, see below |
| `lowercase` | Lowercases text before tokenizing. Default is `True`. | Leave on unless case carries meaning |
| `token_pattern` | Regular expression that defines a token. The default keeps tokens of two or more word characters. | Change it to keep single characters or symbols |
Both min_df and max_df count documents, not occurrences. A word that appears 500 times in one document has a document frequency of 1.
The order of filtering
The vectorizer applies the steps in a fixed order. This order explains several surprises.
Two consequences follow:
- Stop words are removed before n-grams are generated. After removal, words that were separated by a stop word become neighbors. A phrase like "end of the road" with
"of"and"the"removed yields the bigramend road. max_featuresis applied aftermin_dfandmax_df. It ranks the surviving terms by total count in the corpus, not by document frequency or by usefulness to the classifier.
Seeing the effect on a real corpus
The next script fits several vectorizer settings on the same training text. It prints the number of columns and the number of stored nonzero values for each.
from sklearn.datasets import fetch_20newsgroups
from sklearn.feature_extraction.text import TfidfVectorizer
categories = ["sci.space", "rec.autos", "talk.politics.misc"]
remove = ("headers", "footers", "quotes")
train = fetch_20newsgroups(subset="train", categories=categories, remove=remove)
settings = [
{"ngram_range": (1, 1)},
{"ngram_range": (1, 2)},
{"ngram_range": (1, 2), "min_df": 2},
{"ngram_range": (1, 2), "min_df": 5},
{"ngram_range": (1, 2), "min_df": 5, "max_df": 0.5},
{"ngram_range": (1, 2), "max_features": 20000},
]
for params in settings:
vec = TfidfVectorizer(**params)
X = vec.fit_transform(train.data)
print(params, "columns:", X.shape[1], "nonzeros:", X.nnz)When you run it, expect these patterns:
- Moving from
(1, 1)to(1, 2)multiplies the column count several times over. - Adding
min_df=2removes most of those new columns, because most bigrams occur in exactly one document. - Raising
min_dfto 5 shrinks the vocabulary again, but the number of nonzeros falls much less. The rare terms contribute many columns but few stored values, so the memory saving of the matrix itself is smaller than the column count suggests. The saving is larger in the model, where each column costs one coefficient per class.
Choosing values by validation, not by guess
There is no universally correct min_df. A higher value gives a smaller, more stable model. It also discards terms that are rare but highly informative, such as a specific product name that appears in only a few documents of one class. Treat ngram_range and min_df as hyperparameters and compare them with cross-validation on the training set.
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
for ngram in [(1, 1), (1, 2)]:
for min_df in [1, 2, 5]:
pipe = make_pipeline(
TfidfVectorizer(sublinear_tf=True, ngram_range=ngram, min_df=min_df),
LogisticRegression(max_iter=1000),
)
scores = cross_val_score(
pipe, train.data, train.target, cv=5, scoring="f1_macro"
)
print(ngram, min_df, round(scores.mean(), 3))Because the vectorizer sits inside the pipeline, each fold learns its own vocabulary and its own document frequencies from the fold's training portion. The min_df threshold is therefore computed without seeing the validation fold. If you vectorized the whole corpus first and then split, the validation documents would help decide which terms survive, and the scores would be optimistic.
The grid search chapter later in this tutorial automates this loop.
Gotchas
Other points to check:
- A very high
min_dfon a small corpus can empty the vocabulary. If every term is pruned, scikit-learn raises aValueErrorsaying no terms remain after pruning. Lowermin_dfor raisemax_df. max_dfmust be larger thanmin_df. Scikit-learn raises an error when the thresholds contradict each other.- Thresholds given as floats scale with corpus size.
min_df=0.01means "at least 1% of documents". On 100 documents that is 1 document, and on 100,000 documents it is 1,000. An integer stays fixed. - IDF depends on the pruning. Document frequencies are computed on the training data, so the same term gets a different IDF value if you change the training set. Compare settings through the pipeline, not by reusing a stored matrix.
- Out-of-vocabulary terms are silently ignored at prediction time. A test document containing a term the vectorizer never saw contributes nothing for that term. A heavily pruned vocabulary therefore leaves more of each test document unrepresented.
Alternatives when the vocabulary is too big
If pruning does not fit your constraints, there are other options:
- Character n-grams. Setting
analyzer="char_wb", ngram_range=(3, 5)builds features from character sequences within word boundaries. This handles misspellings and word forms, and it gives a vocabulary that grows more slowly than word bigrams and trigrams. It usually produces many features per document. HashingVectorizer. It maps each term to a column index with a hash function, so there is no stored vocabulary and memory is fixed. The trade-offs are that you cannot recover which term a column represents, which hurts coefficient interpretation, and that different terms can collide in one column. It also has no built-in IDF step, so you addTfidfTransformerafter it.- Custom
token_patternortokenizer. Changing what counts as a token (for example, merging numbers into one placeholder) shrinks the vocabulary at its source.
Summary of decision criteria
- Start with unigrams. Add bigrams when word order plausibly matters, such as negation or short phrases like "machine learning".
- Whenever you add n-grams, set
min_dfto at least 2. - Use
max_dfto drop terms found in most documents, but check that your stop-word choice does not already do this job. - Use
max_featuresas a resource limit rather than as a quality tool. - Validate every choice with cross-validation on a pipeline.
Exercise
You switch a TfidfVectorizer from ngram_range=(1, 1) to (1, 2) with default min_df=1. The column count grows by a factor of five and validation F1 does not improve. Give two changes you could try to keep the possible benefit of bigrams while reducing the cost, and say how you would decide whether they worked.
Show answer
Set min_df to 2 or higher so that bigrams occurring in only one document are dropped, and optionally cap the size with max_features. Another option is to remove stop words, but only after checking that the list does not contain negations that matter for the task. To decide, put the vectorizer in a pipeline and compare cross-validated macro F1 for each setting on the training data, along with the column count. Keep the smallest vocabulary whose score matches or beats the best one. Use the test set only once at the end.
Exercise
A term appears 40 times in a single document and in no other document. Is it kept by min_df=2? Is it kept by max_features=1000 if it is among the 1000 most frequent terms by total count?
Show answer
It is not kept by min_df=2, because min_df counts documents and this term appears in only one. It can survive max_features=1000 only if it also passes min_df and max_df, because max_features is applied after those filters. With the default min_df=1 it passes that filter, and its total count of 40 may place it in the top 1000, so it can be kept. This is why max_features does not remove one-document terms.