Sub topic 9
Inverse Document Frequency
This chapter assumes you understand tokenization, vocabularies, and document-term matrices. You should also be comfortable with basic logarithms. We will focus on how a corpus-wide statistic identifies terms that are common or distinctive across documents.
Why document frequency matters
A term that appears in every document usually says little about which document you are reading. A term that appears in only one document can be much more informative.
Document frequency (DF) is the number of documents containing a term at least once. It is different from the total number of times the term appears. Repeating a word inside one document does not increase its document frequency beyond one.
For a corpus with N documents, the unsmoothed inverse document frequency is:
IDF(term) = log(N / DF(term))
The logarithm reduces the difference between extremely common and extremely rare terms. A term in every document has an IDF of zero because log(1) = 0.
A small calculation
Consider this corpus:
- Document 1:
cat sat - Document 2:
cat slept - Document 3:
dog slept
The vocabulary is cat, dog, sat, and slept.
| Term | Documents containing it | DF | IDF, using natural log |
|---|---|---|---|
| cat | 1 and 2 | 2 | log(3/2) = 0.405 |
| dog | 3 | 1 | log(3) = 1.099 |
| sat | 1 | 1 | log(3) = 1.099 |
| slept | 2 and 3 | 2 | log(3/2) = 0.405 |
dog and sat receive larger weights because they occur in fewer documents. IDF does not know whether a word is meaningful to a person. It only measures how unevenly the word is distributed across the corpus.
Smoothing and scikit-learn
In practice, vectorizers often use smoothed IDF:
IDF(term) = log((1 + N) / (1 + DF(term))) + 1
Smoothing prevents unusual values when a term appears in every document and keeps every learned IDF positive. The added 1 also avoids division by zero in related settings.
import numpy as np
n_documents = 3
document_frequency = np.array([2, 1, 1, 2])
idf = np.log((1 + n_documents) / (1 + document_frequency)) + 1
print(np.round(idf, 3))The order of the output matches the order of document_frequency. A real vectorizer stores the same values alongside its learned vocabulary.
Exercise
In a corpus of five documents, a term appears in four documents. Which term has the larger smoothed IDF: this term or one appearing in one document?
Show answer
The term appearing in one document. Its document frequency is smaller, so log((1 + 5) / (1 + 1)) + 1 is larger than log((1 + 5) / (1 + 4)) + 1.