Sub topic 10
Combining TF and IDF
This chapter assumes you have read the previous chapters on term frequency and inverse document frequency. You should be comfortable with a document-term matrix of counts, with ln (the natural logarithm), and with NumPy arrays. Here you combine the two ideas into one weight, compute it by hand, and check it against scikit-learn.
The core idea
A raw count says how often a term appears in one document. It does not say whether the term helps tell documents apart. TF-IDF multiplies two signals:
- Term frequency (TF) is how often the term appears in this document.
- Inverse document frequency (IDF) is how rare the term is across the corpus.
The weight is tfidf(t, d) = tf(t, d) × idf(t). A term gets a high weight only if it is frequent in the document and rare elsewhere. A term that appears in every document gets the lowest IDF, so its weight stays close to its raw count.
The scikit-learn formula
Textbooks often write idf = log(n / df). Under that formula, a term in every document gets log(1) = 0 and disappears. scikit-learn uses a different default (smooth_idf=True):
idf(t) = ln((1 + n) / (1 + df(t))) + 1
Here n is the number of documents and df(t) is the number of documents containing t. The +1 inside the fraction acts as if one extra document contained every term, which avoids division by zero. The +1 outside the logarithm means a term found in every document keeps an IDF of 1 instead of 0.
After multiplying, each row is divided by its Euclidean length (L2 norm), so every document vector has length 1.
A worked example
Use the three-document corpus from earlier chapters:
the cat sat on the matthe dog sat on the logthe cat chased the dog
The vocabulary in alphabetical order is cat, chased, dog, log, mat, on, sat, the, and n = 3. The IDF values are:
| Term | df | IDF calculation | IDF |
|---|---|---|---|
| cat | 2 | ln(4/3) + 1 | 1.288 |
| chased | 1 | ln(4/2) + 1 | 1.693 |
| dog | 2 | ln(4/3) + 1 | 1.288 |
| log | 1 | ln(4/2) + 1 | 1.693 |
| mat | 1 | ln(4/2) + 1 | 1.693 |
| on | 2 | ln(4/3) + 1 | 1.288 |
| sat | 2 | ln(4/3) + 1 | 1.288 |
| the | 3 | ln(4/4) + 1 | 1.000 |
Take document 1. Its count row is [1 0 0 0 1 1 1 2]. Multiply each count by the matching IDF:
- cat: 1 × 1.288 = 1.288
- mat: 1 × 1.693 = 1.693
- on: 1 × 1.288 = 1.288
- sat: 1 × 1.288 = 1.288
- the: 2 × 1.000 = 2.000
The squared values sum to about 11.841, so the L2 norm is about 3.441. Dividing each weight by 3.441 gives:
[0.374, 0, 0, 0, 0.492, 0.374, 0.374, 0.581]
Notice that mat, the only term unique to this document, has a higher weight than cat, on or sat. Notice also that the still has the largest weight. Its IDF is the lowest, but its count of 2 pushes the product up. This is a common surprise, and the callout below covers it.
Reproducing it in code
The first script reads the learned IDF values and the first row. The second uses norm=None to expose the weights before normalization.
import numpy as np
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()
X = vec.fit_transform(docs)
print(vec.get_feature_names_out())
print(np.round(vec.idf_, 3))
print(np.round(X[0].toarray(), 3))The IDF vector is [1.288 1.693 1.288 1.693 1.693 1.288 1.288 1.] and the first row matches the hand calculation. The attribute idf_ has one value per vocabulary term, in the same order as get_feature_names_out().
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()
vec = TfidfVectorizer(norm=None)
raw_weights = vec.fit_transform(docs).toarray()
print(np.allclose(raw_weights, counts * vec.idf_))
print(np.round(raw_weights[0], 3))The check prints True, and the first row is [1.288 0. 0. 0. 1.693 1.288 1.288 2.]. This confirms that the unnormalized TF-IDF matrix is the count matrix with each column scaled by its IDF.
Parameters that change the combination
| Parameter | Default | Effect |
|---|---|---|
| `use_idf` | `True` | If `False`, skip IDF and use only TF (then normalize). |
| `smooth_idf` | `True` | If `False`, IDF is `ln(n / df) + 1`. A term unseen in training would then divide by zero, so keep smoothing unless you have a reason. |
| `sublinear_tf` | `False` | Replaces count `c` with `1 + ln(c)`, so a term seen 10 times is not weighted 10 times. |
| `norm` | `"l2"` | Row normalization. Use `None` to see raw weights, or `"l1"` to make each row sum to 1. |
Common errors
- Comparing weights across fits. IDF depends on the corpus. The same word has a different weight after you add or remove documents, so you cannot compare matrices from different fits directly.
- Expecting the textbook formula. If you compute
log(n / df)by hand, your numbers will not match scikit-learn. Use the smoothed formula with+1, as in the table above. - Forgetting the normalization step. A hand calculation that stops after multiplying will not match
TfidfVectorizer(). Either divide each row by its norm or setnorm=Noneon the vectorizer. - Mixing up the log base. scikit-learn uses the natural logarithm. A different base only rescales IDF, but your numbers will differ from the library's.
- Refitting on new text.
fit_transformon test data recomputes IDF from the test set. Fit once on training data, then calltransform. The leakage chapter covers this.
Reading the result
After normalization, each row has length 1, so a weight is a share of that document's direction in vector space. Long and short documents become comparable, which is why cosine similarity works well on these rows. The rare terms (chased, log, mat) carry more weight than shared terms such as sat, which is the behavior TF-IDF is designed to produce.
Exercise
Using the smoothed IDF formula with n = 3, compute the unnormalized TF-IDF weight of "chased" and of "the" in document 3 ("the cat chased the dog"). Which is larger, and what does that tell you about stop words?
Show answer
"chased" appears once and in 1 document, so idf = ln(4/2) + 1 = 1.693 and the weight is 1 × 1.693 = 1.693. "the" appears twice and in all 3 documents, so idf = ln(4/4) + 1 = 1.0 and the weight is 2 × 1.0 = 2.0. "the" is larger because its count of 2 outweighs its low IDF. Smoothed IDF only reduces the weight of common words, it does not remove them. Use stopwords, maxdf, or sublinear_tf to handle them.
Exercise
You call TfidfVectorizer(norm=None, smooth_idf=False) on the three-document corpus. What is the IDF of "the", and why can this setting cause problems at prediction time?
Show answer
With smoothidf=False, idf = ln(n / df) + 1 = ln(3/3) + 1 = 1.0 for "the". The risk is a term whose df is 0. Dividing by zero is only avoided because the vocabulary is built from the training data, so every term has df of at least 1 at fit time. Still, the smoothing is what makes the formula behave as if one extra document contained every term, so keeping smoothidf=True is the safer default.