Sub topic 4
TF-IDF: Weighting Terms by How Informative They Are
Assume you know basic Python, training and test sets, sparse matrices, and logarithms. This chapter explains how term frequency–inverse document frequency (TF-IDF) turns documents into numeric features for a machine-learning model.
Why raw counts are not enough
A bag-of-words representation counts how often each term appears in each document. Counts are useful, but they treat every term as equally informative.
Suppose a collection contains the documents:
| Document | Text |
|---|---|
| D1 | the cat sat |
| D2 | the dog sat |
| D3 | the cat slept |
The word the appears in every document. It helps identify the writing style of the collection, but it does not help distinguish one document from another. The words cat, dog, and slept are more useful because they occur in fewer documents.
TF-IDF gives a high weight to terms that are frequent in one document but uncommon across the collection.
Term frequency
Term frequency (TF) measures how strongly a term is associated with one document. The simplest version is the raw count:
TF(term, document) = number of times the term appearsA document containing cat three times receives a larger TF value for cat than a document containing it once.
Raw counts can favor long documents. A longer document naturally has more opportunities to repeat a term. A common alternative is normalized term frequency:
TF(t, d) = count(t, d) / total number of terms in dScikit-learn's TfidfVectorizer uses a sublinear option when sublinear_tf=True. This replaces a count with:
1 + log(count)The first occurrence still matters, but repeated occurrences have diminishing influence.
Inverse document frequency
Inverse document frequency (IDF) measures how rare a term is across the document collection. Let:
Nbe the number of documents.df(t)be the number of documents containing termt.
A common smoothed definition is:
IDF(t) = log((1 + N) / (1 + df(t))) + 1A term appearing in every document has a low IDF. A term appearing in only one document has a higher IDF.
TF-IDF combines the two values:
TF-IDF(t, d) = TF(t, d) × IDF(t)The multiplication captures both conditions needed for a useful feature:
- The term appears in the current document.
- The term is relatively unusual in the collection.
Normalizing document vectors
After calculating TF-IDF values, scikit-learn normally applies L2 normalization to each document vector. L2 normalization scales the vector so that the sum of its squared values is 1.
This reduces the effect of document length. A long document should not automatically look more important merely because it contains more terms. With normalized vectors, the classifier focuses more on the pattern of terms.
The complete transformation follows this path:
Computing TF-IDF with scikit-learn
TfidfVectorizer learns the vocabulary and IDF values when you call fit. It then transforms documents into a sparse matrix, which stores mostly nonzero values efficiently.
from sklearn.feature_extraction.text import TfidfVectorizer
docs = [
"the cat sat on the mat",
"the dog sat on the log",
"cats and dogs are pets",
]
vectorizer = TfidfVectorizer()
X = vectorizer.fit_transform(docs)
print("shape:", X.shape)
print("features:", vectorizer.get_feature_names_out())
print("weights:")
print(X.toarray().round(2))Each row in X represents one document. Each column represents one vocabulary term. The matrix value at row d, column t is the normalized TF-IDF weight for term t in document d.
Fit the vectorizer only on training documents. If you calculate the vocabulary or IDF values using test documents, information from the test set enters training. That is data leakage and can make evaluation look better than it should.
Choosing the right interpretation
A high TF-IDF weight means that a term is prominent in a document relative to the collection. It does not prove that the term is important to a human reader, factually correct, or causally related to the document's label. Stop words, spelling variations, and boilerplate text can still create misleading features.
Exercise
A term appears five times in one document and appears in every document in the collection. Should its TF-IDF weight necessarily be high? Explain.
Show answer
No. Its term frequency is high, but its IDF is low because the term appears everywhere. The product may therefore be modest.