Inverse Document Frequency › The IDF Formula
Language AI HandbookAll chapters Inverse Document Frequency › The IDF FormulaOne section · Sections in this chapter3 / 14 ↓
Reading tools Definitions & inline links
Choose your expertise level to adjust how many terms are explained. Beginners see more tooltips, experts see fewer to maintain reading flow. Hover over underlined terms for instant definitions.
Article links
Make inline references clickable
We've established that document frequency reveals which words are common versus rare across a corpus. But document frequency measures commonality, while the task requires a measure of informativeness. The more documents a word appears in, the less useful it is for distinguishing between documents. We need to flip the relationship.
From Commonality to Informativeness
Think about what makes a word useful for identifying a document's topic. If someone mentions "convolutional" in a conversation about machine learning papers, you immediately know they're discussing computer vision or deep learning architectures. That single word narrows down the possibilities dramatically. But if they mention "learning", you've learned almost nothing, because every paper in the corpus discusses learning in some form.
This intuition suggests a simple principle: the fewer documents a word appears in, the more informative it is. A word appearing in 1 out of 100 documents carries far more signal than a word appearing in 99 out of 100. We want to assign weights that reflect this inverse relationship.
The most direct approach would be to use the inverse of the document frequency fraction. If a word appears in documents out of total, its "rarity" could be measured as:
where:
- : the total number of documents in the corpus
- : the document frequency of term (how many documents contain it)
This ratio captures the essence of what we want. For a word appearing in just 1 document out of 100, the ratio is . For a word appearing in all 100 documents, the ratio is . Rare words get high values; common words get low values.
But there's a problem with using this ratio directly.
Why We Need the Logarithm
Consider a corpus of 1 million documents. A word appearing once would get weight 1,000,000. A word appearing in half the documents would get weight 2. This 500,000-fold difference is extreme. In practice, it would mean that a single rare word would completely dominate any calculation, drowning out the contribution of all other words.
What we need is a function that preserves the ordering (rare words still get higher weights than common words) but compresses the range of values. The logarithm is the natural choice for this transformation. It converts multiplicative differences into additive ones, turning that 500,000x gap into something more manageable.
With the logarithm applied to our 1-million-document example, the IDF values become:
- Word appearing once:
- Word appearing in 500,000 documents:
The ratio is now about 20:1 instead of 500,000:1. Rare words still matter more, but they don't completely overwhelm everything else.
There is also a deeper reason why logarithm fits here. When you combine IDF with term frequency to produce TF-IDF, both components should contribute to the final weight. If IDF ranged from 1 to 1,000,000, a word's corpus-wide rarity would completely swamp its within-document frequency. The logarithm brings both factors into a compatible scale, allowing each to shape the final weight proportionally.
This brings us to the complete IDF formula:
Inverse Document Frequency measures how informative a term is across the corpus:
where:
- : the total number of documents in the corpus
- : the document frequency of term (how many documents contain it)
- : the natural logarithm (though any base works; the choice affects scale but not relative ordering)
The logarithm compresses the range of weights, preventing rare words from dominating completely while still giving them higher importance than common words.
Understanding the Formula's Behavior
Let's trace through what happens at the extremes to build intuition:
When a word appears in every document ():
Substituting into the IDF formula gives:
A word appearing everywhere provides zero discriminative information. This makes sense: if every document contains "the", knowing a document contains "the" tells you nothing about which document it is.
When a word appears in exactly one document ():
Substituting into the IDF formula gives:
This is the maximum possible IDF value for a given corpus size. Such words are maximally informative because they uniquely identify specific documents.
When a word appears in half the documents ():
Substituting into the IDF formula gives:
This value is independent of corpus size. A word appearing in half the documents always has the same IDF, whether the corpus has 10 documents or 10 million. This corpus-size invariance for fractional document frequencies is a useful property: IDF weights are comparable across corpora of different sizes, as long as you express document frequency as a fraction rather than an absolute count.
The choice of logarithm base affects the scale of IDF values but not their relative ordering. Natural log (ln), log base 2, and log base 10 are all common choices. scikit-learn uses natural log by default, which gives IDF values in the range .
Implementing IDF from Scratch
Let's translate the formula into code. The implementation is straightforward: for each term, we compute the log of the ratio of total documents to document frequency.
import numpy as np
def compute_idf(doc_freq, num_docs):
"""Compute IDF for all terms.
Args:
doc_freq: Dictionary mapping terms to their document frequencies
num_docs: Total number of documents in the corpus
Returns:
Dictionary mapping terms to their IDF values
"""
idf = {}
for term, df in doc_freq.items():
# Apply the IDF formula: log(N / df)
idf[term] = np.log(num_docs / df)
return idf
# Compute IDF values using the document frequencies we calculated earlier
idf_values = compute_idf(doc_freq, num_docs)Now let's examine the IDF values for our corpus. We'll display each term alongside its document frequency, the raw ratio , and the final IDF value. This breakdown helps us see how the logarithm transforms the raw ratios.
IDF Values (natural log): ================================================================= Term DF N/DF IDF ----------------------------------------------------------------- hierarchical 1 5.00 1.6094 representations 1 5.00 1.6094 algorithms 1 5.00 1.6094 labeled 1 5.00 1.6094 machine 1 5.00 1.6094 patterns 1 5.00 1.6094 requires 1 5.00 1.6094 supervised 1 5.00 1.6094 training 1 5.00 1.6094 for 1 5.00 1.6094 language 1 5.00 1.6094 models 1 5.00 1.6094 natural 1 5.00 1.6094 processing 1 5.00 1.6094 text 1 5.00 1.6094
The output confirms what we predicted. Words appearing in all 5 documents (like "learning" and "from") have IDF = 0, since . Words appearing in only 1 document (like "reinforcement" and "convolutional") achieve the maximum IDF of . This range, from 0 to , is characteristic of the standard IDF formula.
IDF Values for Different Document Frequencies
The relationship between document frequency and IDF follows a logarithmic curve. As document frequency increases, IDF decreases, but the rate of decrease slows down. The table below shows the exact IDF values for each possible document frequency in our 5-document corpus:
| Document Frequency (df) | N/df Ratio | IDF = log(N/df) | Interpretation |
|---|---|---|---|
| 1 | 5.00 | 1.61 | Maximum: term appears in only one document |
| 2 | 2.50 | 0.92 | High: term is relatively rare |
| 3 | 1.67 | 0.51 | Medium: term appears in over half the corpus |
| 4 | 1.25 | 0.22 | Low: term is quite common |
| 5 | 1.00 | 0.00 | Zero: term appears in every document |
Notice how the IDF decrease is steeper between DF=1 and DF=2 (dropping by 0.69) than between DF=4 and DF=5 (dropping by only 0.22). This non-linear relationship means that the distinction between "unique" and "appears twice" matters more than the distinction between "very common" and "ubiquitous." At the top end of the rarity scale, small differences in document frequency translate to large differences in IDF weight. This is by design: a term appearing in only 2 documents has one-fifth the document frequency of one appearing in 10 documents, and IDF captures this with appropriately scaled weights.
Why the Logarithm Matters
The logarithm's importance becomes apparent at larger corpus scales. Without it, rare words receive weights that completely dominate calculations.

The figure reveals why the logarithm matters at scale. Without it (red dashed line, scaled down 100x for visibility), the curve is extremely steep, with rare words receiving weights hundreds of times larger than common words. The logarithmic version (blue) provides a gentler gradient that maintains the ordering while keeping weights in a manageable range.
Notice also how the logarithmic curve flattens as document frequency increases. The difference between appearing in 1 document versus 2 documents is much larger than the difference between appearing in 500 versus 1000 documents. This makes intuitive sense: the jump from "unique" to "appears twice" is more significant than the jump from "pretty common" to "slightly more common."