Inverse Document Frequency › The Problem with Term Frequency Alone

Michael BrenndoerferMarch 28, 20256 min read
Language AI HandbookAll chapters
Part 2 of 67Classical Text Representations
Chapter 12Inverse Document Frequency › The Problem with Term Frequency Alone
Reading section 2 of 14 · The Problem with Term Frequency Alone · 6 minSection 2 of 14 · 6 min

Book contents

Section 2 of 14 · 6 min read

Inverse Document Frequency › The Problem with Term Frequency AloneOne section · Sections in this chapter2 / 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

In the previous chapter, we computed term frequency to measure word importance within documents. But TF has a blind spot: it treats all words equally regardless of their corpus-wide distribution.

Consider a corpus of research papers about machine learning:

In[3]:
Code
from collections import Counter

# Sample corpus of ML research abstracts
corpus = [
    "Neural networks learn hierarchical representations from data. Deep learning uses neural networks.",
    "Machine learning algorithms learn patterns from training data. Supervised learning requires labeled data.",
    "Natural language processing uses deep learning for text classification. Language models learn from text.",
    "Reinforcement learning agents learn through trial and error. The agent maximizes cumulative reward.",
    "Computer vision uses convolutional neural networks. Image classification is a core vision task.",
]


def tokenize(text):
    """Simple tokenization: lowercase and extract words."""
    import re

    return re.findall(r"\b[a-z]+\b", text.lower())


# Tokenize corpus
tokenized_corpus = [tokenize(doc) for doc in corpus]

# Compute term frequency for Document 1
tf_doc1 = Counter(tokenized_corpus[0])
Out[4]:
Console
Term Frequencies in Document 1:
---------------------------------------------
  neural                2  ██
  networks              2  ██
  learn                 1  █
  hierarchical          1  █
  representations       1  █
  from                  1  █
  data                  1  █
  deep                  1  █
  learning              1  █
  uses                  1  █

Both "neural" and "from" appear twice in Document 1, giving them equal term frequency. But "neural" is specific to this document's topic, while "from" appears in almost every English text. Term frequency alone cannot distinguish between these cases.

This failure has real consequences. Imagine building a search engine that represents every document purely by term frequency and then ranks documents by how many times query terms appear. A query for "neural network architectures" would rank documents containing "the", "of", and "in" almost as high as those containing "neural", because stopwords inflate frequencies. Even removing explicit stopwords doesn't fully solve the problem, since domain-specific filler words ("study", "analysis", "result") are common within a field but vary in how discriminative they are.

The root problem is that TF is a local statistic. It sees only the document in front of it. It has no way to ask, "Compared to everything in my corpus, how unusual is it to see this word here?" That global perspective is exactly what IDF provides.

Document Frequency Reveals Corpus-Wide Patterns

To understand which words are informative, we need to look beyond individual documents. Document frequency (DF) counts how many documents contain each word:

Document Frequency (DF)

Document frequency measures how many documents in the corpus contain a given term. For term tt in a corpus DD, the document frequency is:

df(t)=∣{d∈D:t∈d}∣\text{df}(t) = |\{d \in D : t \in d\}|

where:

  • tt: the term (word) we're measuring
  • DD: the collection of all documents in the corpus
  • dd: an individual document in the corpus
  • {d∈D:t∈d}\{d \in D : t \in d\}: the set of documents that contain term tt
  • ∣⋅∣|\cdot|: the cardinality (size) of the set, i.e., the count of documents

A high DF indicates a common word appearing across many documents. A low DF indicates a rare word appearing in few documents.

In[5]:
Code
def compute_document_frequency(tokenized_corpus):
    """Count how many documents contain each term."""
    df = Counter()
    for doc in tokenized_corpus:
        # Sort the per-document set so repeated theme renders are identical.
        unique_terms = sorted(set(doc))
        df.update(unique_terms)
    return df


# Compute document frequency across corpus
doc_freq = compute_document_frequency(tokenized_corpus)
num_docs = len(tokenized_corpus)
Out[6]:
Console
Document Frequency Analysis (5 documents):
=======================================================
Term                     DF     Fraction Appears in
-------------------------------------------------------
  learn                   4        80%   ████░
  learning                4        80%   ████░
  from                    3        60%   ███░░
  uses                    3        60%   ███░░
  classification          2        40%   ██░░░
  data                    2        40%   ██░░░
  deep                    2        40%   ██░░░
  networks                2        40%   ██░░░
  neural                  2        40%   ██░░░
  a                       1        20%   █░░░░
  agent                   1        20%   █░░░░
  agents                  1        20%   █░░░░
  algorithms              1        20%   █░░░░
  and                     1        20%   █░░░░
  computer                1        20%   █░░░░

The pattern emerges clearly. Words like "learning" and "from" appear in most documents. This provides little discriminative power. Words like "reinforcement", "vision", and "convolutional" appear in only one document. This makes them highly specific to particular topics.

Out[7]:
Visualization
Histogram showing 34 terms at document frequency 1, five at frequency 2, two at frequency 3, two at frequency 4, and none at frequency 5.
Distribution of document frequencies across all terms in the corpus. Of the 43 terms, 34 appear in one document, five appear in two, and two each appear in three and four documents; none appear in all five. This characteristic shape motivates giving lower weights to high-DF terms.
Horizontal bar chart showing terms grouped by their document frequency.
Terms grouped by document frequency. Rare terms at DF=1 are topic-specific identifiers for individual documents, while the most widely shared terms in this corpus reach DF=4 rather than appearing universally.

The Discriminative Power Gap

The histograms make the core problem visual. A massive number of terms sit at DF=1, where they are uniquely tied to a single document. In this corpus, the most widely shared terms reach DF=4; a hypothetical DF=5 term would appear everywhere. The terms in the middle ground, appearing in two or three documents, occupy an interesting position: they distinguish subsets of documents from one another.

A good weighting scheme should assign weights that reflect this hierarchy. Maximum weight for DF=1 terms (they identify individual documents uniquely). Zero or minimal weight for DF=N terms (they tell you nothing about which document you're looking at). Intermediate weights for everything in between.

That's exactly what IDF does.