Sub topic 4
TF-IDF: weighting terms by how informative they are
This chapter assumes you can read basic Python and NumPy, you know what a training and test split is, and you are comfortable with the natural logarithm. It also assumes you have seen a document-term matrix of raw word counts, which the previous chapter covered. Here we turn those counts into weights that a linear classifier can use better.
Why raw counts are a poor signal
A count matrix says how often each term appears in each document. That is not the same as how useful the term is for telling documents apart. In a corpus of news posts, "the" may appear 40 times in a document and "telescope" only 3 times. The first number is bigger, but only the second tells you anything about the topic.
Two problems follow from this:
- Words that occur in nearly every document dominate the counts but carry almost no class information.
- Long documents have larger counts than short ones, even when they are about the same thing.
TF-IDF addresses the first problem with a per-term weight and the second with a per-document normalization.
The two factors
TF-IDF is the product of two numbers for each term t in each document d:
- Term frequency (TF) is how often
tappears ind. In the plain version, it is the raw count. - Inverse document frequency (IDF) measures how rare
tis across the whole corpus. Terms found in few documents get a high IDF. Terms found in almost every document get a low IDF.
The weight is tfidf(t, d) = tf(t, d) × idf(t).
The classic definition is idf(t) = ln(n / df(t)), where n is the number of documents and df(t) is the number of documents containing t. scikit-learn uses a smoothed variant by default:
idf(t) = ln((1 + n) / (1 + df(t))) + 1
Two details of this formula matter:
- The
1 +terms inside the logarithm behave as if one extra document contained every term once. This prevents division by zero and keeps IDF finite. - The
+ 1outside the logarithm means a term that appears in every document still gets an IDF of 1, not 0. Such a term is down-weighted relative to rare terms, but it is not erased.
After multiplying TF by IDF, scikit-learn divides each document's vector by its Euclidean length (L2 norm). Every row then has length 1, so document length stops affecting the magnitude of the features.
A worked example
Take the three documents from the spine and run TfidfVectorizer on them.
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(X.shape)
print(vectorizer.get_feature_names_out())
print(X.toarray().round(2))The matrix has shape (3, 12): three documents and twelve distinct terms. The default tokenizer lowercases the text and keeps tokens of two or more word characters, so "cat" and "cats" are separate terms.
Now compute the numbers by hand. There are n = 3 documents.
- "the", "sat", and "on" each appear in 2 documents, so
idf = ln(4/3) + 1 ≈ 1.288. - Every other term appears in 1 document, so
idf = ln(4/2) + 1 ≈ 1.693.
For the first document, "the" appears twice, and "cat", "sat", "on", and "mat" once each:
| Term | Count | IDF | Count × IDF |
|---|---|---|---|
| the | 2 | 1.288 | 2.575 |
| cat | 1 | 1.693 | 1.693 |
| sat | 1 | 1.288 | 1.288 |
| on | 1 | 1.288 | 1.288 |
| mat | 1 | 1.693 | 1.693 |
The squares sum to about 15.68, so the L2 norm is about 3.96. Dividing each weight by 3.96 gives the final row: "the" ≈ 0.65, "cat" and "mat" ≈ 0.43, "sat" and "on" ≈ 0.33.
"the" still has the largest weight in this row, because it appears twice. Its IDF is lower than that of "cat", but a count of 2 outweighs that gap. With only three documents, IDF has little to work with. On a corpus of thousands of documents, a word like "the" gets an IDF close to 1 while a topical word gets an IDF of 5 or more, and the ordering changes.
You can confirm the formula by recomputing the matrix yourself:
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
docs = [
"the cat sat on the mat",
"the dog sat on the log",
"cats and dogs are pets",
]
counts = CountVectorizer().fit_transform(docs).toarray()
n_docs = counts.shape[0]
df = (counts > 0).sum(axis=0)
idf = np.log((1 + n_docs) / (1 + df)) + 1
raw = counts * idf
manual = raw / np.linalg.norm(raw, axis=1, keepdims=True)
sklearn_matrix = TfidfVectorizer().fit_transform(docs).toarray()
print(np.allclose(manual, sklearn_matrix))This prints True. The CountVectorizer and TfidfVectorizer share the same default tokenizer, so their vocabularies match.
You can read the learned IDF values from a fitted vectorizer through its idf_ attribute:
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().fit(docs)
for term, value in zip(vectorizer.get_feature_names_out(), vectorizer.idf_):
print(f"{term:5s} {value:.3f}")The parameters that change the weighting
TfidfVectorizer exposes each step of the formula as a setting.
| Parameter | Default | Effect |
|---|---|---|
| `use_idf` | `True` | If `False`, skips the IDF factor and uses only term frequency (still normalized). |
| `smooth_idf` | `True` | Adds the extra pseudo-document. If `False`, a term seen in no training document would divide by zero. |
| `sublinear_tf` | `False` | Replaces `tf` with `1 + ln(tf)`. |
| `norm` | `"l2"` | Row normalization. `"l1"` and `None` are also allowed. |
| `max_df` | `1.0` | Drops terms appearing in more than this fraction (or count) of documents. |
| `min_df` | `1` | Drops terms appearing in fewer than this many documents. |
Sublinear term frequency
Repeating a word 20 times does not make a document 20 times more about that word. With sublinear_tf=True, the TF contribution grows slowly:
| Raw count | Weight used |
|---|---|
| 1 | 1.00 |
| 2 | 1.69 |
| 5 | 2.61 |
| 20 | 4.00 |
On text classification tasks this setting often helps a little, especially when documents vary widely in length or contain repeated boilerplate. It is cheap to try and is usually worth including in a tuning search.
Normalization and linear models
L2 normalization matters for logistic regression in particular. Every feature row lies on the unit sphere, so a long document cannot produce a larger score simply by having more words. It also puts the features on a comparable scale, which keeps regularization behaving predictably in later chapters.
Stop words and max_df
IDF already shrinks the weight of very common words, but it does not remove them. A stop-word list (stop_words="english") removes a fixed set of function words before weighting. max_df=0.9, for example, removes terms by their actual frequency in your corpus, which adapts to your domain. Domain-specific filler such as "subject" or "wrote" in email corpora is better handled by max_df than by a generic list.
Where TF-IDF goes wrong
Fitting on the wrong data
The IDF values are learned from the data you call fit on. If you fit the vectorizer on the full dataset before splitting, the test documents influence the vocabulary and IDF values, and your evaluation scores are too optimistic. Fit on the training text only, then call transform on the test text.
from sklearn.feature_extraction.text import TfidfVectorizer
train_docs = ["the cat sat on the mat", "the dog sat on the log"]
test_docs = ["the cat chased the dog"]
vectorizer = TfidfVectorizer()
X_train = vectorizer.fit_transform(train_docs)
X_test = vectorizer.transform(test_docs)
print(X_train.shape, X_test.shape)Both matrices have the same number of columns. Words in the test document that are missing from the training vocabulary, such as "chased", are silently ignored. A Pipeline, covered later in this tutorial, enforces this fit-then-transform order automatically, including inside cross-validation.
Rare terms with huge weights
A term that appears in exactly one training document gets the highest possible IDF. If it is a typo, a name, or an ID number, it carries a large weight but cannot generalize. This is why min_df=2 is a common setting: it removes terms that cannot appear in both a training and a validation document.
Reading weights as probabilities
TF-IDF values are not probabilities and do not sum to 1 across a row (the squares do). They are inputs to a model, not a model output. Comparing a weight in one document against a weight in another is only meaningful after normalization, and even then only roughly.
Small corpora
IDF is an estimate of how common a term is across documents. With a few dozen documents, the estimate is noisy, as the three-document example showed. In that case, the benefit of IDF over plain counts may be small, and use_idf=False is a reasonable comparison.
Out-of-vocabulary drift
The IDF vector is fixed once the vectorizer is fitted. If the language in production shifts (new product names, new slang), those terms have no column and no weight. Plan to refit periodically on fresh data, and monitor how many tokens in incoming documents fall outside the vocabulary.
Checking your understanding
Exercise
A corpus has 9 documents. The term "orbit" appears in 2 of them and the term "report" appears in 8 of them. Using scikit-learn's default smoothed IDF, ln((1 + n) / (1 + df)) + 1, which term gets the higher IDF, and what are the two values to two decimal places?
Show answer
"orbit" gets the higher IDF. For "orbit": ln(10/3) + 1 ≈ 1.20 + 1 = 2.20. For "report": ln(10/9) + 1 ≈ 0.11 + 1 = 1.11. The rarer term is weighted about twice as heavily per occurrence.
Exercise
You fit a TfidfVectorizer on your whole dataset, then split it into training and test sets, then train a classifier and report test F1. What is wrong with this procedure, and how do you fix it?
Show answer
The IDF values and vocabulary were computed using the test documents, so information from the test set leaked into the features. Split first, fit the vectorizer on the training text only, and transform the test text with the fitted vectorizer. Putting the vectorizer and classifier in a Pipeline does this automatically, including inside cross-validation.
Exercise
Why does a term that appears in every document still get a nonzero weight in scikit-learn, and when might you still want to remove it?
Show answer
The smoothed formula adds 1 outside the logarithm, so a term with df = n gets IDF = ln((1 + n) / (1 + n)) + 1 = 1. It is down-weighted relative to rarer terms but not zeroed out. You may still remove such terms with max_df or a stop-word list, because they add columns without adding class information.