Sub topic 13
Capturing Short Phrases with N-Grams
Assume you understand tokenization and the basic use of CountVectorizer and TfidfVectorizer. This chapter shows how to preserve short word sequences instead of treating every word as independent.
Why single words can miss meaning
A unigram is a one-word token. A unigram model represents “not useful” with separate features for not and useful. It does not record that these words appeared together or in that order.
An n-gram is a sequence of n consecutive tokens:
| N-gram type | Example from “the model is useful” |
|---|---|
| Unigram | `the`, `model`, `is`, `useful` |
| Bigram | `the model`, `model is`, `is useful` |
| Trigram | `the model is`, `model is useful` |
Bigrams can capture phrases such as customer service, credit card, or not useful. Trigrams capture slightly longer patterns, but they create more features.
Choosing an n-gram range
In scikit-learn, ngram_range=(min_n, max_n) controls which sequences are created.
(1, 1)uses unigrams only.(1, 2)uses unigrams and bigrams.(2, 2)uses bigrams only.(1, 3)uses unigrams, bigrams, and trigrams.
Including unigrams gives the model broad word-level evidence. Adding bigrams helps it learn local phrases. Trigrams may help when exact wording matters, but they often occur too rarely to generalize.
from sklearn.feature_extraction.text import TfidfVectorizer
docs = [
"the service was not useful",
"the service was very useful",
]
vectorizer = TfidfVectorizer(ngram_range=(1, 2), stop_words="english")
X = vectorizer.fit_transform(docs)
print(vectorizer.get_feature_names_out())
print(X.shape)The vectorizer creates a feature for each retained unigram and bigram. Because English stop words are removed, common words such as the and was may not appear. The exact features depend on the analyzer and preprocessing settings.
Costs and configuration choices
N-grams increase the vocabulary size. A document of length L has up to L - n + 1 contiguous n-grams of size n. Across a corpus, this can produce a large sparse matrix.
Common trade-offs include:
- Use unigrams when the dataset is small or memory is limited.
- Add bigrams when phrases or word order carry useful signals.
- Add trigrams only when you have enough training examples.
- Use
min_dfto discard n-grams that appear in very few documents. - Use
max_featuresto cap the vocabulary when memory is constrained.
The tokenizer still determines what counts as a token. Changing lowercase handling, punctuation rules, or stop-word removal changes the n-grams too.
Exercise
Which setting creates both single words and adjacent two-word phrases: ngram_range=(2, 2) or ngram_range=(1, 2)?
Show answer
ngram_range=(1, 2) creates both unigrams and bigrams. The setting (2, 2) creates bigrams only.