TF-IDF Weighting
In a raw count vector, the most prominent coordinates of almost every document are "the", "is", "my" and "and". They occur everywhere, so they say nothing about what a particular document is about, yet they dominate any dot product or distance computed from counts. Two support tickets that share six function words and no content word look more similar than a ticket and its exact answer phrased differently. Stop-word lists remove some of these words, but as Bag of Words showed, a fixed list also removes "not" and "full".
TF-IDF (term frequency times inverse document frequency) fixes this with statistics instead of a list. A word's weight in a document grows with how often it occurs there (term frequency) and shrinks with how many documents contain it (document frequency). "the", present in every ticket, gets a small weight everywhere; "refund", present in a few, gets a large weight where it occurs. The idea goes back to Karen Spärck Jones's term specificity (1972), and TF-IDF vectors with cosine similarity were the core of search engines for decades.
Definitions
Let be the number of documents, the number of times term occurs in document , and the number of documents that contain at least once. The textbook inverse document frequency is
which is 0 for a term in every document and for a term in one. scikit-learn's TfidfVectorizer uses a slightly different version by default. With smooth_idf=True it adds one to both counts, as if one extra document contained every term once (so a term with at transform time cannot cause a division by zero), and it adds 1 to the result so that terms present in every document keep a small positive weight instead of vanishing:
The weight of term in document and the final vector are
The l2 normalisation (norm="l2", the default) gives every document vector length 1, so long documents do not get larger scores just for being long, and the dot product of two vectors is their cosine similarity. With smooth_idf=False the idf is , and with sublinear_tf=True the term frequency is replaced by (for ).
A worked example with documents: a term in all four has ; a term in two has ; a term in one has . The rarest terms weigh about twice as much as the most common ones here. In a corpus of a million documents the spread is much larger: against 1.
From scratch, matching scikit-learn exactly
The example builds the count matrix, computes document frequencies and smoothed idf, multiplies and normalises, and compares every entry with TfidfVectorizer() at its defaults.
import re
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
docs = ["the bike lock is broken and the bike app crashed",
"the app charged my card twice",
"refund the double charge on my card",
"the lock will not open"]
tok = lambda d: re.findall(r"(?u)\b\w\w+\b", d.lower())
vocab = sorted({w for d in docs for w in tok(d)})
col = {w: j for j, w in enumerate(vocab)}
tf = np.zeros((len(docs), len(vocab)))
for i, d in enumerate(docs):
for w in tok(d):
tf[i, col[w]] += 1
n = len(docs)
df = (tf > 0).sum(axis=0)
idf = np.log((1 + n) / (1 + df)) + 1 # smooth_idf=True
W = tf * idf
W /= np.linalg.norm(W, axis=1, keepdims=True) # norm="l2"
vec = TfidfVectorizer()
S = vec.fit_transform(docs).toarray()
print("same vocabulary:", list(vec.get_feature_names_out()) == vocab)
print("same matrix (max difference < 1e-12):", bool(np.abs(S - W).max() < 1e-12))
for w in ["the", "app", "card", "bike", "crashed"]:
j = col[w]
print(f"{w:8} df={df[j]} idf={idf[j]:.3f} sklearn idf={vec.idf_[j]:.3f}")same vocabulary: True
same matrix (max difference < 1e-12): True
the df=4 idf=1.000 sklearn idf=1.000
app df=2 idf=1.511 sklearn idf=1.511
card df=2 idf=1.511 sklearn idf=1.511
bike df=1 idf=1.916 sklearn idf=1.916
crashed df=1 idf=1.916 sklearn idf=1.916
The two matrices agree to rounding error, and the idf values are those of the worked example: "the" occurs in all four documents and gets 1.000, "app" and "card" occur in two and get 1.511, "bike" and "crashed" occur in one and get 1.916. Note that "bike" occurs twice in the first document but has : document frequency counts documents, not occurrences.
The knobs: sublinear tf, smoothing, idf on or off
A query or document that repeats a word many times ("refund refund refund refund") should count that word more than once, but probably not four times as much: the fourth occurrence adds less evidence than the first. The example vectorises such a text with four settings, fitted on the same four documents.
from sklearn.feature_extraction.text import TfidfVectorizer
docs = ["the bike lock is broken and the bike app crashed",
"the app charged my card twice",
"refund the double charge on my card",
"the lock will not open"]
query = "refund refund refund refund the card"
for kw in [dict(use_idf=False), dict(), dict(sublinear_tf=True), dict(smooth_idf=False)]:
vec = TfidfVectorizer(**kw).fit(docs)
v = vec.transform([query]).toarray()[0]
col = vec.vocabulary_
idf = [round(float(vec.idf_[col[w]]), 3) for w in ("the", "card", "refund")] if vec.use_idf else "-"
print(f"{str(kw):22} idf(the, card, refund)={idf}")
print(f"{'':22} weights: " + ", ".join(f"{w} {v[col[w]]:.3f}" for w in ("the", "card", "refund"))){'use_idf': False} idf(the, card, refund)=-
weights: the 0.236, card 0.236, refund 0.943
{} idf(the, card, refund)=[1.0, 1.511, 1.916]
weights: the 0.127, card 0.192, refund 0.973
{'sublinear_tf': True} idf(the, card, refund)=[1.0, 1.511, 1.916]
weights: the 0.203, card 0.307, refund 0.930
{'smooth_idf': False} idf(the, card, refund)=[1.0, 1.693, 2.386]
weights: the 0.103, card 0.174, refund 0.979
Read the weights of the three words, all of which occur in the text: "the" once, "card" once, "refund" four times.
| Setting | idf of the, card, refund | weights after l2 norm |
|---|---|---|
counts only (use_idf=False) |
none | 0.236, 0.236, 0.943 |
| default | 1.0, 1.511, 1.916 | 0.127, 0.192, 0.973 |
sublinear_tf=True |
1.0, 1.511, 1.916 | 0.203, 0.307, 0.930 |
smooth_idf=False |
1.0, 1.693, 2.386 | 0.103, 0.174, 0.979 |
Without idf, "the" and "card" weigh the same. The default idf pushes "card" above "the" (0.192 against 0.127), but the four repetitions make "refund" take almost the whole vector, 0.973. Sublinear tf turns the count 4 into , so "card" keeps a real share (0.307): if this text were a query, documents about cards would still be found. Without smoothing, the idf values spread further ( for a term in one of four documents), which matters on very small corpora and hardly at all on large ones. sublinear_tf=True is a good default for documents of varied length and for user-written text where people repeat themselves; it is one of the ideas that BM25 develops further with its saturation parameter.
What IDF does on a corpus
On four documents the effect is easy to compute by hand. On a corpus it changes which words a document vector is "about". The example generates 60 short support messages: each mixes nine filler words ("the" three times as likely as the others) with three words from one of three topics. It then measures, for raw counts, TF-IDF and TF-IDF with sublinear tf, the top three words of the first message and the average share of each vector's squared length that falls on topic words.
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
rng = np.random.default_rng(0)
topics = {"billing": ["refund", "charge", "card", "invoice", "twice", "payment"],
"hardware": ["lock", "brake", "chain", "tyre", "battery", "broken"],
"app": ["login", "crash", "update", "screen", "password", "map"]}
filler = ["the", "the", "the", "my", "is", "and", "it", "please", "help", "bike"]
docs, labels = [], []
for _ in range(60):
t = str(rng.choice(list(topics)))
words = list(rng.choice(filler, 9)) + list(rng.choice(topics[t], 3))
rng.shuffle(words)
docs.append(" ".join(words)); labels.append(t)
topic_words = {w for ws in topics.values() for w in ws}
print(labels[0], "|", docs[0])
for name, vec in [("counts", CountVectorizer()), ("tf-idf", TfidfVectorizer()),
("tf-idf sublinear", TfidfVectorizer(sublinear_tf=True))]:
X = vec.fit_transform(docs).toarray().astype(float)
names = vec.get_feature_names_out()
top = np.argsort(-X[0], kind="stable")[:3]
is_topic = np.array([w in topic_words for w in names])
share = ((X ** 2)[:, is_topic].sum(axis=1) / (X ** 2).sum(axis=1)).mean()
print(f"{name:16} top 3 of doc 0: {[names[j] for j in top]}, mean share of squared weight on topic words {share:.2f}")
idf = dict(zip(vec.get_feature_names_out(), vec.idf_))
print("idf:", {w: round(float(idf[w]), 2) for w in ["the", "please", "bike", "refund", "tyre", "login"]})app | my the screen help the it map the screen the the and
counts top 3 of doc 0: ['the', 'screen', 'and'], mean share of squared weight on topic words 0.18
tf-idf top 3 of doc 0: ['screen', 'the', 'map'], mean share of squared weight on topic words 0.49
tf-idf sublinear top 3 of doc 0: ['screen', 'map', 'the'], mean share of squared weight on topic words 0.57
idf: {'the': 1.05, 'please': 1.65, 'bike': 1.42, 'refund': 3.72, 'tyre': 2.81, 'login': 2.63}
The first message contains "the" five times and its topic words "screen" (twice) and "map" once. With counts, "the" is its top word and topic words carry on average only 18% of the squared weight of a message vector: a cosine similarity between two count vectors is mostly a comparison of filler. TF-IDF moves "screen" to the top and raises the topic share to 49%, because "the" (in almost every message) has idf 1.05 while "refund", "tyre" and "login" have 2.6 to 3.7. "the" is still second, since five occurrences beat a low idf; sublinear tf damps that to and the topic share rises to 57%. "please" and "bike" are filler too, but their idf is higher (1.65 and 1.42) because random sampling left them out of more messages: IDF measures how widespread a word is in this corpus, not whether it is a function word.
That last point is also TF-IDF's weakness. IDF has no idea of meaning: a word that is rare by accident gets a high weight, and two documents that use different words for the same thing ("flat tyre" and "puncture") share no weighted term at all. TF-IDF vectors are long, sparse and literal. Word embeddings and, later, dense retrieval replace them with short dense vectors in which related words are close.
Pitfalls
- Computing idf on the whole dataset. Document frequencies are fitted statistics: fit
TfidfVectorizeron the training split (inside aPipeline) and onlytransformthe rest. - Comparing numbers across implementations. Textbooks, Lucene, gensim and scikit-learn use different idf formulas, log bases and normalisations; state which one you use.
- Forgetting that rows are normalised. After
norm="l2", a dot product is already the cosine similarity; dividing by the norms again is harmless but wasteful, andnorm=Nonemakes long documents dominate. - TF-IDF on very short texts. With one or two words per text, tf is almost always 1 and the vector is just idf weights; that works for search, but leaves little to learn for a classifier.
- Treating idf as importance. A typo has the highest idf in the corpus. Combine with
min_dfto drop terms seen in one document.
Practice
- A corpus has documents. Compute scikit-learn's default idf for terms with , 4 and 1.
- Why does scikit-learn add 1 to the logarithm? What would happen to "the" in the four-document example without it?
- A document contains "lock" 9 times. What is its term frequency with
sublinear_tf=True? - In the "refund" table, why does "the" have a smaller weight with
smooth_idf=False(0.103) than with the default (0.127), although its idf is 1.0 in both? - Two messages have cosine similarity 0.9 with count vectors and 0.2 with TF-IDF vectors. What is the likely explanation?
Answers
- ; ; .
- So that terms present in every document keep a positive weight instead of exactly 0 (a document made only of such terms would otherwise become a zero vector, which cannot be normalised). "the" has , so without the it would disappear from every vector.
- , instead of 9.
- The weights are normalised. Without smoothing, "card" and "refund" get larger idf values (1.693 and 2.386), so the vector's length grows and every coordinate is divided by more; "the" keeps idf 1.0, so its share shrinks.
- They share many frequent words (filler, function words) and few rare ones. Counts let the frequent words dominate; TF-IDF down-weights them, and the remaining content words differ.
Test yourself
With smooth_idf=True and documents, what is the idf of a term that occurs in exactly one document?
- 1
What does sublinear_tf=True change?
- It replaces the term frequency by
- It removes the idf
- It normalises by the l1 norm
- It drops terms that occur only once
After TfidfVectorizer with its default norm="l2", the dot product of two document vectors equals:
- The number of shared words
- Their Euclidean distance
- Their cosine similarity
- The sum of their idf values
On the 60 generated messages, what share of the squared vector weight fell on topic words with raw counts, and with TF-IDF?
- 0.49 and 0.18
- 0.18 and 0.49
- 0.57 and 0.18
- 0.18 and 0.18