Sub topic 3
Capturing short phrases with n-grams
This chapter assumes basic Python, familiarity with NumPy arrays, the fit and predict idea for classifiers, and the bag-of-words and TF-IDF material from earlier chapters.
Capturing short phrases with n-grams
A bag of words counts single words, so "not good" and "good" share the feature "good". An n-gram is a run of n consecutive tokens. Setting ngram_range=(1, 2) keeps single words and adds two-word pairs.
from sklearn.feature_extraction.text import CountVectorizer
docs = ["the movie was not good", "the movie was good"]
vec = CountVectorizer(ngram_range=(1, 2))
vec.fit(docs)
print(vec.get_feature_names_out())Controlling vocabulary size
Each new n-gram adds a column, so the vocabulary grows quickly. These parameters limit it:
| Parameter | Effect |
|---|---|
| min_df | Drops terms found in fewer documents than this count or proportion |
| max_df | Drops terms found in more documents than this proportion |
| max_features | Keeps only the most frequent terms across the corpus |
Setting sublinear_tf=True replaces raw term counts with 1 + log(tf), which reduces the effect of words that repeat many times in one document.
Comparing documents with cosine similarity
Cosine similarity measures the angle between two vectors. Scikit-learn normalizes TF-IDF rows to unit length, so the score falls between 0 and 1 for these non-negative vectors. A score of 1 means identical direction.
Fitting the vectorizer on training data only
The vectorizer learns a vocabulary and IDF values from the texts you pass to fit. If you fit on the full dataset, test documents influence the features and inflate evaluation scores. Fit on training texts, then call transform on test texts. A pipeline does this automatically.
A TF-IDF text classification pipeline
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
train_texts = ["great movie, loved it", "terrible plot and bad acting"]
train_labels = [1, 0]
model = make_pipeline(
TfidfVectorizer(ngram_range=(1, 2), sublinear_tf=True),
LogisticRegression(max_iter=1000),
)
model.fit(train_texts, train_labels)
print(model.predict(["loved the acting"]))The hashing trick for very large vocabularies
HashingVectorizer maps each term to a column index with a hash function. It stores no vocabulary and needs no fit step, but two terms can share a column (a collision), and you cannot list feature names.
from sklearn.feature_extraction.text import HashingVectorizer
hv = HashingVectorizer(n_features=2**18, ngram_range=(1, 2), alternate_sign=False, norm="l2")
X = hv.transform(["the cat sat on the mat", "the dog sat on the log"])
print(X.shape)Limitations and alternatives
Bag-of-words features ignore word order beyond the n-gram window, so "dog bites man" and "man bites dog" look nearly identical with unigrams. They also treat "car" and "automobile" as unrelated columns. Word embeddings and transformer models capture meaning and order, and they are the usual next step when these limits matter.
Exercise
Why does HashingVectorizer need no fit step, and what does that cost you?
Show answer
It computes each column index from the term itself with a hash function, so it stores no vocabulary. The cost is possible collisions between terms and no feature names to inspect.