Sub topic 13
Capturing short phrases with n-grams
A plain bag of words treats every word on its own, so "not good" and "good" share the feature good. An n-gram is a run of n consecutive tokens. If you add n-grams to the vocabulary, the model gets features for short phrases and recovers a little of the word order that counting throws away. This chapter assumes you know how CountVectorizer and TfidfVectorizer build a vocabulary and a document-term matrix.
What an n-gram is
Take the tokens cat sat mat.
- Unigrams (n=1):
cat,sat,mat - Bigrams (n=2):
cat sat,sat mat - Trigrams (n=3):
cat sat mat
A document with T tokens produces T - n + 1 n-grams of size n. With ngram_range=(1, 2) it produces T + (T - 1) = 2T - 1 features per occurrence list, before duplicates are merged.
Each n-gram becomes a column in the document-term matrix, exactly like a single word. Counting, IDF, and normalization work on n-gram columns with no change.
Setting ngram_range
Both vectorizers take ngram_range=(min_n, max_n). The default is (1, 1), which means unigrams only.
| Setting | Features produced |
|---|---|
| `(1, 1)` | single words only (default) |
| `(2, 2)` | bigrams only |
| `(1, 2)` | words and two-word phrases |
| `(1, 3)` | words, bigrams, and trigrams |
Most text classifiers use (1, 2). Trigrams rarely add enough to justify the extra columns unless you have a lot of data.
Seeing the effect on word order
The next example compares a sentence with and without negation.
from sklearn.feature_extraction.text import CountVectorizer
docs = [
"the movie was good",
"the movie was not good",
]
for rng in [(1, 1), (1, 2)]:
vec = CountVectorizer(ngram_range=rng)
X = vec.fit_transform(docs)
print(rng, X.shape[1])
print(vec.get_feature_names_out())With (1, 1) there are 5 features. With (1, 2) there are 10, and the list includes not good and was not. The unigram model only sees an extra not column. The bigram model has a dedicated not good column, so a classifier can give it its own weight, separate from good.
Stop words and n-grams interact
Stop-word removal happens before n-grams are built. This can create bigrams that never appeared in the original text.
from sklearn.feature_extraction.text import TfidfVectorizer
docs = [
"the cat sat on the mat",
"the dog sat on the log",
"the cat chased the dog",
]
vec = TfidfVectorizer(ngram_range=(1, 2), stop_words="english")
vec.fit(docs)
print(vec.get_feature_names_out())The first document becomes cat sat mat after the and on are removed. The vectorizer then produces the bigram sat mat, even though the original text says "sat on the mat". The output has 12 features:
- Unigrams:
cat,chased,dog,log,mat,sat - Bigrams:
cat chased,cat sat,chased dog,dog sat,sat log,sat mat
Two consequences follow:
- The stop-word list can silently change which phrases exist. If phrases matter for your task, try the vectorizer without
stop_wordsand letmax_dfor IDF down-weight the common words. - Bigrams such as
of theorin aare real phrases, but they appear in nearly every document and carry little information. Without stop-word removal, IDF gives them low weights. They still occupy columns.
Vocabulary growth
Unigrams repeat heavily across a corpus, so the vocabulary grows slowly as you add documents. Bigrams and trigrams repeat much less. Most appear once or twice. The vocabulary can grow by an order of magnitude when you move from (1, 1) to (1, 2), and trigrams add another large step.
This has three costs:
- Memory. The matrix stays sparse, but it has more stored non-zero entries and more columns. Each model also has more coefficients.
- Sparsity per feature. Most n-gram columns are non-zero in only a handful of documents. A classifier can memorize those rare phrases and overfit.
- Noisy IDF. A phrase that appears in exactly one document gets the highest possible IDF, so it receives a large weight despite weak evidence.
Pruning n-gram vocabularies
Pair ngram_range with the pruning options from the previous chapter. They matter more here than with unigrams.
min_df=2(or a higher count) removes phrases that appear in fewer than two documents. This is the most effective single setting for n-grams.max_df=0.9removes phrases that appear in more than 90% of documents.max_features=50000keeps only the most frequent n-grams, ranked by total count across the corpus.
from sklearn.feature_extraction.text import TfidfVectorizer
docs = [
"the cat sat on the mat",
"the dog sat on the log",
"the cat chased the dog",
]
vec = TfidfVectorizer(ngram_range=(1, 2), min_df=2)
vec.fit(docs)
print(vec.get_feature_names_out())On this tiny corpus, only terms that occur in at least two of the three documents survive: cat, dog, on, sat, the, the cat, the dog, sat on, and on the. Phrases such as cat chased are dropped because they occur once.
Pruning is applied after n-grams are generated. Memory is still needed during fit to count all candidate n-grams, so on a large corpus the peak memory use happens before pruning.
Choosing n-gram settings
Use these decision criteria:
- Start with
(1, 1)and measure a baseline with cross-validation. - Try
(1, 2)withmin_df=2or higher. Keep it if the validation score improves. - Try
(1, 3)only if bigrams helped and you have enough data. Gains are usually small. - If the vocabulary does not fit in memory, use
max_features, or switch to the hashing trick covered later.
N-grams help most on short texts where local context carries the meaning, such as sentiment, intent detection, or titles. They help less on long documents, where topic is already well captured by single words.
What n-grams do not fix
N-grams are still bag-of-words features. They capture only phrases of fixed, short length, and every phrase is an unrelated column. The model does not know that not good and not great are similar, or that very good is related to good. Long-range dependencies, such as a negation five words before the adjective, are not captured. For those cases you need word embeddings or contextual models, which the final chapter on limitations mentions.
Exercise
A document has the tokens "we really love this movie" (5 tokens, all distinct, no stop-word removal). How many n-gram occurrences does CountVectorizer(ngramrange=(1, 3)) generate for it, and why might adding mindf=2 on a large corpus still be a good idea?
Show answer
There are 5 unigrams, 4 bigrams, and 3 trigrams, so 12 n-grams. The formula is T - n + 1 for each n. Adding min_df=2 removes phrases that appear in only one document. Those phrases make up most of the extra columns, give very high IDF values from little evidence, and let a classifier memorize individual training documents.
Exercise
You build TfidfVectorizer(ngramrange=(1, 2), stopwords="english") and fit it on the sentence "fear of the dark". The feature list contains the bigram "fear dark". Why does this bigram exist, and how would you avoid it?
Show answer
Stop words "of" and "the" are removed before bigrams are formed, so "fear" and "dark" become adjacent tokens. To avoid it, drop the stopwords argument and rely on maxdf or IDF to down-weight common words. Alternatively, use a custom analyzer or preprocessing step that builds n-grams before removing stop words.