Sub topic 12
CountVectorizer and TfidfVectorizer in scikit-learn
This chapter assumes you know how a bag-of-words count matrix and the TF-IDF formula work, as covered in the earlier chapters. It also assumes you can use NumPy arrays and call fit and predict on a scikit-learn estimator. Here the focus is on how scikit-learn's two vectorizers implement those ideas, what each setting changes, and which mistakes come up most often.
What the two classes do
CountVectorizer turns a list of strings into a sparse matrix of raw term counts. TfidfVectorizer does the same, then applies IDF weighting and L2 row normalization. The second class is equivalent to CountVectorizer followed by TfidfTransformer.
The first six stages belong to CountVectorizer. The last two are added by TfidfVectorizer.
The fit and transform contract
Both classes follow the usual scikit-learn pattern.
fit(docs)learns the vocabulary. ForTfidfVectorizerit also learns one IDF value per term.transform(docs)converts documents using whatfitlearned. It never changes the vocabulary.fit_transform(docs)does both in one pass.
The following example fits a CountVectorizer, inspects the result, and then transforms a new document that contains a word the vectorizer has never seen.
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())
print(X.format, X.shape, X.nnz)
print(vec.vocabulary_)
new = vec.transform(["the bird sat on the mat"])
print(new.toarray())The vocabulary is sorted alphabetically: cat, chased, dog, log, mat, on, sat, the. The first row of the matrix is [1 0 0 0 1 1 1 2]. The matrix has format csr, shape (3, 8), and 14 stored nonzero values (nnz). Calling toarray() is fine for a demo, but on a real corpus it can exhaust memory because it fills in every zero.
vocabulary_ is a dictionary that maps each term to its column index. The new document prints as [0 0 0 0 1 1 1 2]. The word "bird" is not in the vocabulary, so it is dropped without any error or warning.
Verifying the TF-IDF formula
By default, scikit-learn uses smoothed IDF: idf = ln((1 + n) / (1 + df)) + 1. The added 1 outside the logarithm means a term that appears in every document still gets weight 1, not 0. The raw count (the term frequency) is multiplied by this IDF, and each row is then divided by its L2 norm.
The next example reproduces that computation by hand and compares it with TfidfVectorizer.
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
docs = [
"the cat sat on the mat",
"the dog sat on the log",
"the cat chased the dog",
]
counts = CountVectorizer().fit_transform(docs).toarray()
n_docs = counts.shape[0]
df = (counts > 0).sum(axis=0)
idf = np.log((1 + n_docs) / (1 + df)) + 1
tfidf = counts * idf
tfidf = tfidf / np.linalg.norm(tfidf, axis=1, keepdims=True)
reference = TfidfVectorizer().fit_transform(docs).toarray()
print(np.allclose(tfidf, reference))This prints True. In this corpus "the" appears in all 3 documents, so its IDF is ln(4/4) + 1 = 1. "chased" appears in 1 document, so its IDF is ln(4/2) + 1, about 1.693. Even so, "the" still has the largest weight in the first row after normalization, about 0.58. Its count of 2 multiplies an IDF of 1 and outweighs the single-count words with higher IDF. This shows that TF-IDF only down-weights common words. It does not remove them. Stop word lists or max_df are used for that.
The TfidfVectorizer also stores the learned weights in idf_, one value per column in the same order as get_feature_names_out().
Equivalence with the two-step version
You can build the same features in two explicit steps. This is useful when you want to cache the counts or apply different weighting to them.
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer, TfidfVectorizer
from sklearn.pipeline import make_pipeline
docs = [
"the cat sat on the mat",
"the dog sat on the log",
"the cat chased the dog",
]
two_step = make_pipeline(CountVectorizer(), TfidfTransformer())
a = two_step.fit_transform(docs).toarray()
b = TfidfVectorizer().fit_transform(docs).toarray()
print(np.allclose(a, b))This also prints True.
Parameters that change the output
| Parameter | Default | Effect |
|---|---|---|
| `lowercase` | `True` | Lowercases text before tokenizing. |
| `token_pattern` | `r"(?u)\b\w\w+\b"` | Regex for tokens. The default drops one-character tokens such as "a" and "I". |
| `stop_words` | `None` | `"english"` or a custom list of words to drop. |
| `ngram_range` | `(1, 1)` | `(1, 2)` adds two-word phrases to the vocabulary. |
| `min_df` | `1` | Drops terms found in fewer documents. An integer is a count and a float is a fraction. |
| `max_df` | `1.0` | Drops terms found in more documents than the limit. |
| `max_features` | `None` | Keeps only the most frequent terms across the corpus. |
| `binary` | `False` | Sets every nonzero count to 1. |
| `sublinear_tf` | `False` | `TfidfVectorizer` only. Replaces the count `tf` with `1 + ln(tf)`. |
| `norm` | `"l2"` | `TfidfVectorizer` only. Row normalization. `None` turns it off. |
| `smooth_idf` | `True` | `TfidfVectorizer` only. Adds 1 to the document counts inside the IDF logarithm. |
The next example combines bigrams and stop word removal, then compares the first document with all three.
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
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")
X = vec.fit_transform(docs)
print(vec.get_feature_names_out())
print(cosine_similarity(X[0], X).round(2))Stop words are removed before n-grams are built. A phrase like "cat sat" therefore appears as a bigram, but "sat on" does not, because "on" was already removed. The similarity of the first document with itself is 1.0, as expected for L2-normalized rows.
Common errors
- Refitting on test data. Calling
fit_transformon the test set builds a new vocabulary, so the columns no longer match the model's training columns. Fit on training text only, then calltransformon test text. Putting the vectorizer in a pipeline enforces this. - Passing a single string.
fit_transform("some text")iterates over characters or raises an error. Pass a list of strings. - Custom
tokenizerwithtoken_pattern. When you supplytokenizer,token_patternis ignored, and scikit-learn warns you. Lowercasing and stop word handling are also separate steps, so check that they still match your tokenizer. - Stop word list mismatch. A custom
stop_wordslist is not tokenized the same way as your text. If your tokenizer changes words, such as by stemming, the stop words may never match. Newer versions warn about this. - Converting to dense arrays. Vocabulary size times document count grows quickly. Keep the matrix sparse, and use
min_dformax_featuresto cap the width. - Comparing IDF across corpora. IDF values depend on the fitted corpus. Two vectorizers fitted on different data produce weights that are not comparable.
Exercise
You fit TfidfVectorizer() on 1,000 training reviews, then call vec.transform(["zzyzx qwerty"]) where neither word appeared in training. What does the output row contain, and does scikit-learn raise an error?
Show answer
No error is raised. Both words are outside the learned vocabulary, so they are ignored and the row has no nonzero entries. L2 normalization leaves an all-zero row as zeros, so any cosine similarity with it is 0.
Exercise
A term appears in all 3 documents of a corpus. With default settings, what IDF does TfidfVectorizer give it, and why is that not 0?
Show answer
Its IDF is ln((1 + 3) / (1 + 3)) + 1 = 1. Smoothed IDF adds 1 outside the logarithm, so a term found in every document is weighted by 1 instead of being zeroed out.