Sub topic 9
Inverse document frequency
This chapter assumes you can read a document-term matrix (rows are documents, columns are vocabulary terms, cells are counts). It also assumes you know basic NumPy and what a natural logarithm is.
Why raw counts are not enough
A count matrix treats every term as equally informative. In a corpus of news articles, "the" may appear dozens of times per document, while "tsunami" appears twice in one article. The count for "the" is larger, but it tells you nothing about which document you are reading.
Inverse document frequency (IDF) is a weight that depends only on the corpus, not on any single document. It is large for terms that appear in few documents and small for terms that appear in many. The next chapter multiplies it with term frequency to get TF-IDF.
Document frequency
The document frequency of a term, written df(t), is the number of documents that contain the term at least once. It counts documents, not occurrences. If "the" appears five times in one document, that document still adds only 1 to df("the").
Here is df for the three-document corpus used throughout this tutorial.
| Term | df | Documents |
|---|---|---|
| cat | 2 | 1, 3 |
| chased | 1 | 3 |
| dog | 2 | 2, 3 |
| log | 1 | 2 |
| mat | 1 | 1 |
| on | 2 | 1, 2 |
| sat | 2 | 1, 2 |
| the | 3 | 1, 2, 3 |
The formulas
The textbook definition is:
idf(t) = ln(n / df(t))
Here n is the number of documents. A term that appears in every document gets ln(1) = 0, so it contributes nothing. A term that appears in one of three documents gets ln(3) ≈ 1.10.
This version breaks in two ways. A term with df = 0 causes a division by zero. A term that appears everywhere is erased completely. scikit-learn's default, smooth_idf=True, changes the formula to:
idf(t) = ln((1 + n) / (1 + df(t))) + 1
The "1 +" terms act as if one extra document contained every term exactly once. This removes the division by zero. The final "+ 1" keeps ubiquitous terms at weight 1 instead of 0. With smooth_idf=False, scikit-learn uses ln(n / df) + 1, which keeps the "+ 1" but drops the smoothing.
For n = 3, the three variants give these values:
| df | ln(n / df) | smooth_idf=False | smooth_idf=True (default) |
|---|---|---|---|
| 1 | 1.099 | 2.099 | 1.693 |
| 2 | 0.405 | 1.405 | 1.288 |
| 3 | 0.000 | 1.000 | 1.000 |
Other libraries differ here. If you compare scores from another tool, check which variant it uses before you compare numbers.
Computing IDF in code
The following script computes document frequency and IDF by hand, then compares the result with the idf_ attribute that a fitted TfidfVectorizer exposes.
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",
]
cv = CountVectorizer()
counts = cv.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 = TfidfVectorizer().fit(docs)
for term, d, w in zip(cv.get_feature_names_out(), df, idf):
print(f"{term:8s} df={d} idf={w:.3f}")
print(np.allclose(idf, tfidf.idf_))The line (counts > 0).sum(axis=0) is the key step. Converting counts to booleans before summing is what makes the result a document count rather than a total occurrence count. The last line prints True.
You can also switch off smoothing and see the other column of the table:
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",
]
raw = TfidfVectorizer(smooth_idf=False).fit(docs)
print(raw.idf_.round(3))This prints [1.405 2.099 1.405 2.099 2.099 1.405 1.405 1. ], in the alphabetical order cat, chased, dog, log, mat, on, sat, the.
Why the logarithm
The logarithm compresses the range. Without it, a term in 1 of 1,000,000 documents would weigh 1,000,000 times more than a term in every document. With it, the ratio is about 14. Doubling the rarity adds a constant (ln 2 ≈ 0.69) instead of doubling the weight. This keeps one extremely rare token, such as a typo, from dominating a document's vector.
Gotchas
- IDF is learned, not computed per document.
fitcomputes df over the training corpus and stores the IDF values.transformreuses them. A new document does not change the weights. The later chapter on fitting vectorizers explains why fitting on test data leaks information. - Unseen terms are ignored. A term that was not in the training vocabulary has no column, so it receives no weight at prediction time.
- IDF depends on corpus size and composition. A term that is rare in a corpus of cooking articles may be common in a corpus of recipes. The same word can get different weights in different corpora.
- The
binaryoption does not change IDF.binary=Truecaps counts at 1, but df already counts documents, soidf_stays the same. - Stop-word removal and IDF overlap. IDF already pushes very common words toward the lowest weight. Because of the "+ 1", though, they are never zero, so
stop_wordsormax_dfcan still help. idf_exists only whenuse_idf=True. Reading it from a vectorizer built withuse_idf=Falseraises an error.
Choosing a variant
Keep the default for most work. Smoothing is safer on small corpora, where a single document changes df a lot. The unsmoothed variant mainly matters when you need to reproduce another system's output exactly. If you need to suppress common words more aggressively than IDF does, use max_df rather than editing the formula.
Exercise
A corpus has n = 9 documents. The term "model" appears in 3 of them, in one of those documents 10 times. What is its smoothed IDF with scikit-learn's default formula, rounded to three decimals?
Show answer
Document frequency counts documents, not occurrences, so df = 3. The formula is ln((1 + 9) / (1 + 3)) + 1 = ln(2.5) + 1 ≈ 0.916 + 1 = 1.916.
Exercise
Why does scikit-learn add 1 to the logarithm, and what would happen to the word "the" in the example corpus without it?
Show answer
Without the "+ 1", a term in every document gets ln(1) = 0. "the" appears in all three documents, so its TF-IDF weight would be exactly 0 and it would vanish from every vector. With the "+ 1" it keeps an IDF of 1.0, so it is down-weighted relative to rarer terms but still present.