Inverse Document Frequency › The IDF Formula

Michael BrenndoerferMarch 28, 20259 min read
Language AI HandbookAll chapters
Part 2 of 67Classical Text Representations
Chapter 12Inverse Document Frequency › The IDF Formula
Reading section 3 of 14 · The IDF Formula · 9 minSection 3 of 14 · 9 min

Book contents

Section 3 of 14 · 9 min read

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 df(t)\text{df}(t) documents out of NN total, its "rarity" could be measured as:

Ndf(t)\frac{N}{\text{df}(t)}

where:

  • NN: the total number of documents in the corpus
  • df(t)\text{df}(t): the document frequency of term tt (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 100/1=100100/1 = 100. For a word appearing in all 100 documents, the ratio is 100/100=1100/100 = 1. 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: idf=log⁡(1,000,000/1)=log⁡(1,000,000)≈13.8\text{idf} = \log(1{,}000{,}000 / 1) = \log(1{,}000{,}000) \approx 13.8
  • Word appearing in 500,000 documents: idf=log⁡(1,000,000/500,000)=log⁡(2)≈0.69\text{idf} = \log(1{,}000{,}000 / 500{,}000) = \log(2) \approx 0.69

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 (IDF)

Inverse Document Frequency measures how informative a term is across the corpus:

idf(t)=log⁡(Ndf(t))\text{idf}(t) = \log\left(\frac{N}{\text{df}(t)}\right)

where:

  • NN: the total number of documents in the corpus
  • df(t)\text{df}(t): the document frequency of term tt (how many documents contain it)
  • log⁡\log: 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 (df(t)=N\text{df}(t) = N):

Substituting df(t)=N\text{df}(t) = N into the IDF formula gives:

idf(t)=log⁡(NN)=log⁡(1)=0\text{idf}(t) = \log\left(\frac{N}{N}\right) = \log(1) = 0

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 (df(t)=1\text{df}(t) = 1):

Substituting df(t)=1\text{df}(t) = 1 into the IDF formula gives:

idf(t)=log⁡(N1)=log⁡(N)\text{idf}(t) = \log\left(\frac{N}{1}\right) = \log(N)

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 (df(t)=N/2\text{df}(t) = N/2):

Substituting df(t)=N/2\text{df}(t) = N/2 into the IDF formula gives:

idf(t)=log⁡(NN/2)=log⁡(2)≈0.69\text{idf}(t) = \log\left(\frac{N}{N/2}\right) = \log(2) \approx 0.69

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 [0,ln⁡(N)][0, \ln(N)].

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.

In[8]:
Code
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 N/df(t)N/\text{df}(t), and the final IDF value. This breakdown helps us see how the logarithm transforms the raw ratios.

Out[9]:
Console
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 log⁡(5/5)=log⁡(1)=0\log(5/5) = \log(1) = 0. Words appearing in only 1 document (like "reinforcement" and "convolutional") achieve the maximum IDF of log⁡(5)≈1.61\log(5) \approx 1.61. This range, from 0 to log⁡(N)\log(N), 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:

IDF values for a 5-document corpus. Terms appearing in only one document achieve maximum IDF (1.61), while terms appearing in all documents receive zero IDF weight. The logarithm compresses the 5:1 ratio range into a 0-1.61 IDF range.
Document Frequency (df)N/df RatioIDF = log(N/df)Interpretation
15.001.61Maximum: term appears in only one document
22.500.92High: term is relatively rare
31.670.51Medium: term appears in over half the corpus
41.250.22Low: term is quite common
51.000.00Zero: 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.

Out[10]:
Visualization
Line plot comparing logarithmic IDF with raw ratio, showing the log compresses extreme values at the rare-term end.
Comparison of IDF with and without the logarithm for a 1,000-document corpus. The log-transformed version (blue) compresses the weight range to roughly 0-7, while the raw ratio (red, scaled down 100x for visibility) spans 0-1,000. Without the log, a single term appearing in one document would receive a weight 1,000 times larger than a term appearing in all documents, causing rare words to dominate any downstream calculation.

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."