Sub topic 12
CountVectorizer and TfidfVectorizer in scikit-learn
Assume you know basic Python, NumPy vectors, classifier fit and predict, and logarithms. This chapter focuses on how scikit-learn turns text into numeric features.
CountVectorizer: from text to counts
CountVectorizer learns a vocabulary from a collection of documents. A vocabulary is the set of terms that the vectorizer recognizes. It then counts each term in each document.
from sklearn.feature_extraction.text import CountVectorizer
docs = [
"the cat sat on the mat",
"the dog sat on the log",
"the cat chased the dog",
]
vec = CountVectorizer()
X = vec.fit_transform(docs)
print(vec.get_feature_names_out())
print(X.toarray())fit_transform performs two operations:
fitlearns the vocabulary fromdocs.transformconverts each document into a row of counts.
The output columns follow the vocabulary order, not the order in which words first appear.
| Term | First document count | Second document count |
|---|---|---|
| cat | 1 | 0 |
| dog | 0 | 1 |
| the | 2 | 1 |
By default, the vectorizer lowercases text and uses a token pattern that selects words containing at least two characters. Punctuation is discarded.
TfidfVectorizer: weighting distinctive terms
TfidfVectorizer produces a similar document-term matrix, but it gives less weight to terms that appear in many documents.
Term frequency, or TF, measures how often a term occurs in one document. Inverse document frequency, or IDF, measures how uncommon the term is across the corpus. With scikit-learn's default smoothing:
idf(term) = log((1 + number_of_documents) /
(1 + number_of_documents_containing_term)) + 1The TF-IDF value is the term frequency multiplied by IDF. Scikit-learn then applies L2 normalization by default, scaling each row to length 1.
from sklearn.feature_extraction.text import TfidfVectorizer
vec = TfidfVectorizer()
X = vec.fit_transform(docs)
print(vec.get_feature_names_out())
print(X.toarray().round(3))A common term such as the receives a smaller weight than a term appearing in only one document. The values are floating-point numbers rather than raw counts.
Choosing vectorizer settings
The vectorizer's settings change the features it creates.
| Setting | Effect | Typical use |
|---|---|---|
| `ngram_range=(1, 2)` | Includes single words and two-word phrases | Capture phrases such as `not good` |
| `stop_words="english"` | Removes common English words | Reduce uninformative terms |
| `min_df=2` | Keeps terms in at least two documents | Remove rare noise |
| `max_df=0.9` | Removes terms in over 90% of documents | Remove corpus-wide terms |
| `sublinear_tf=True` | Replaces TF with `1 + log(TF)` | Reduce the effect of repeated words |
Exercise
Exercise
Why should you call fit only on training documents when building a classifier?
Show answer
Fitting on test documents leaks vocabulary and IDF information from the test set into training.