Sub topic 2
N-grams, min_df, and controlling vocabulary size
This chapter assumes you know basic Python, can call fit and predict in scikit-learn, and understand bag-of-words features, TF-IDF weights, and training and test splits.
N-grams
An n-gram is a run of n consecutive tokens. Unigrams (n=1) are single words. Bigrams (n=2) are adjacent word pairs such as "new york" or "not good". Setting ngram_range=(1, 2) keeps both unigrams and bigrams. Bigrams capture short phrases where word order matters. The cost is a larger vocabulary, because the number of distinct bigrams grows quickly with corpus size.
Limiting the vocabulary with min_df
min_df drops terms that appear in fewer than min_df documents. min_df=2 removes words seen in only one document, which are often typos or rare names that do not generalize. A float such as min_df=0.01 means "at least 1% of documents."
| Parameter | Effect | Typical setting |
|---|---|---|
| ngram_range | Sets which n-gram sizes become features | (1, 2) for phrases |
| min_df | Drops rare terms | 2, or a small fraction |
| max_df | Drops terms found in too many documents | 0.9 or lower |
| max_features | Caps the vocabulary size | Limits memory use |
> The vocabulary is learned during fit.
Use this approach inside a pipeline so that the test set never shapes the vocabulary.
from sklearn.feature_extraction.text import TfidfVectorizer
texts = [
"the rocket launched into orbit",
"the satellite orbits the earth",
"astronauts trained for the mission",
"the car engine needs oil",
"the new car has fast wheels",
"change the oil in the engine",
]
vectorizer = TfidfVectorizer(ngram_range=(1, 2), min_df=2)
X = vectorizer.fit_transform(texts)
print(X.shape)
print(vectorizer.get_feature_names_out())Logistic regression on sparse features
Logistic regression learns one weight per feature. It adds the weighted features and passes the sum through a sigmoid function to get a probability. Most TF-IDF entries are zero, so the matrix is sparse, and the solver handles it efficiently. With thousands of features and few documents, the model can fit the training data almost perfectly. Regularization limits that overfitting.
Regularization and choosing C
LogisticRegression applies L2 regularization by default. The C parameter is the inverse of the regularization strength. Small C shrinks weights toward zero. Large C lets them grow. Choose C with cross-validation, because training accuracy rises as C grows and says little about new text.
Putting it together in a Pipeline
A Pipeline chains the vectorizer and the classifier. When you call fit, the vocabulary and IDF values come from the training data only. Cross-validation then refits both steps on each fold.
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
texts = [
"the rocket launched into orbit",
"the satellite orbits the earth",
"astronauts trained for the mission",
"the car engine needs oil",
"the new car has fast wheels",
"change the oil in the engine",
]
labels = ["space", "space", "space", "autos", "autos", "autos"]
model = make_pipeline(
TfidfVectorizer(ngram_range=(1, 2), min_df=2),
LogisticRegression(C=1.0, max_iter=1000),
)
model.fit(texts, labels)
print(model.predict(["the engine of the car"]))Exercise
Why does min_df=2 often help when a word appears in only one training document?
Show answer
One document gives too little evidence to learn a reliable weight for that word, and the word is unlikely to appear in new text. Dropping it reduces noise and vocabulary size.