Sub topic 10
Combining TF and IDF
This chapter assumes you know Python lists and functions, NumPy vectors, basic classifier terminology, and logarithms. You also need to know that a document-term matrix stores one row per document and one column per vocabulary term.
From counts to weights
Term frequency (TF) measures how often a term occurs in one document. The simplest version uses the raw count:
TF(t, d) = count of term t in document d
Raw counts favor long documents and terms repeated many times. A common alternative divides by the document length:
TF(t, d) = count(t, d) / number of terms in d
Inverse document frequency (IDF) measures how unusual a term is across the collection. Let N be the number of documents and df(t) the number of documents containing term t:
IDF(t) = log(N / df(t))
A term in every document has IDF 0. A term found in only a few documents has a larger value.
Scikit-learn uses smoothed IDF by default:
IDF(t) = log((1 + N) / (1 + df(t))) + 1
Smoothing prevents division by zero and keeps common terms from receiving a weight of exactly zero.
TF-IDF
TF-IDF multiplies the two measurements:
TF-IDF(t, d) = TF(t, d) × IDF(t)
The result is high when a term appears often in one document but appears in relatively few documents overall. Common terms receive less emphasis.
Consider three documents:
| Term | Count in document 1 | Document frequency | Smoothed IDF |
|---|---|---|---|
| cat | 2 | 2 | log(4/3) + 1 ≈ 1.288 |
| dog | 1 | 2 | log(4/3) + 1 ≈ 1.288 |
| iguana | 0 | 1 | log(4/2) + 1 ≈ 1.693 |
Using raw TF, the TF-IDF weight for cat in document 1 is 2 × 1.288 = 2.576. The term iguana is more distinctive, but it has weight zero in this document because it does not occur there.
Normalizing the vectors
After weighting, vectorizers usually apply L2 normalization. L2 normalization divides every value in a row by the row's Euclidean length:
length(x) = sqrt(x1² + x2² + ... + xn²)
This makes each document vector have length 1. It reduces the effect of document length and makes cosine similarity equal to the dot product of normalized vectors.
import numpy as np
counts = np.array([[2, 1, 0], [0, 2, 1], [1, 0, 1]])
n_documents = counts.shape[0]
document_frequency = (counts > 0).sum(axis=0)
idf = np.log((1 + n_documents) / (1 + document_frequency)) + 1
tfidf = counts * idf
normalized = tfidf / np.linalg.norm(tfidf, axis=1, keepdims=True)
print(np.round(idf, 3))
print(np.round(normalized, 3))The calculation pipeline
Exercise
A term appears twice in one document. The collection has four documents, and the term appears in two of them. Using smoothed IDF and raw TF, what is its TF-IDF weight?
Show answer
Smoothed IDF is log(5/3) + 1, approximately 1.511. Raw TF is 2, so the TF-IDF weight is approximately 3.022.