Search

Search papers and lessons

TF-IDF

Level 3 · 11 min read

TF-IDF scores a word in a document by how often it appears there, times how rare it is across all documents, so that words which distinguish a document count the most.

On this page

  • Colour = topic mix
  • Discrete math
  • Probability
  • Algorithms
  • Calculus
  • Language & LLMs
  • Linear algebra
  • ReadReady to readNot yet

TL;DR

A search engine has to decide which documents match a query, and which words in a document matter most. TF-IDF gives each word in each document a weight: how often the word appears in that document, multiplied by how rare the word is across the whole collection. Common words such as "the" get weight near zero, and words that set one document apart get high weight.

Builds on: Bag of Words, Logarithm · Leads to: Cosine Similarity, Inverted Index

Where it's used

Keyword search over document collections. A law firm stores tens of thousands of contracts and needs the ones that mention "force majeure" clauses. Ranking by raw word counts would favour long contracts that repeat common words. TF-IDF down-weights the words that every contract contains and lifts the words that a few contracts share, so the most relevant contracts rise to the top.

Baseline ranking in search systems. Many search systems keep a TF-IDF or closely related score as a first pass; BM25 is the best-known refinement. It is fast to compute from an Inverted Index, easy to explain to a user ("this document uses your rare words often"), and it is hard to beat on simple keyword queries without extra signals. Unlike link-based scores such as PageRank, it uses only the text of the documents.

Finding related items. A news site groups articles by topic. Each article becomes a vector of TF-IDF weights, and articles whose vectors point in similar directions, measured with Cosine Similarity, are shown together as related reading. Words such as "said" or "reported" carry little weight, so the grouping depends on the subject words.

How it works

Take a tiny collection of four documents, with lowercase words and no stop-word removal. The collection has N=4N = 4 documents.

  • D1: "the cat sat on the mat"
  • D2: "the dog sat on the log"
  • D3: "the cat chased the dog"
  • D4: "a bird flew over the mat"

The question is which document best matches the query "cat chased".

  1. Count the words in each document. This is the bag-of-words step: forget the order and record counts. In D1, "the" appears twice, and "cat", "sat", "on" and "mat" appear once each. Check: the counts add up to six, the number of words in D1.
  2. Count the documents each word appears in. Call this the document frequency. "the" appears in all four documents. "cat", "sat", "on", "mat" and "dog" each appear in two. "log", "chased", "bird", "flew", "over" and "a" each appear in one. Check: every word that appears in D1 appears in at least one document, so none has a document frequency of zero.
  3. Turn each document frequency into a rarity score. The rarity score is the logarithm of NN divided by the document frequency. Words in all four documents get log⁡10(4/4)=0\log_{10}(4/4) = 0. Words in two get log⁡10(2)≈0.301\log_{10}(2) \approx 0.301. Words in one get log⁡10(4)≈0.602\log_{10}(4) \approx 0.602. Check: the rarer the word, the larger its score.
  4. Multiply counts by rarity to get the weight. In D1, "the" gets 2×0=02 \times 0 = 0, and "cat", "sat", "on" and "mat" each get 1×0.301=0.3011 \times 0.301 = 0.301. Check: "the" contributes nothing to D1, even though it appears most often.
  5. Score the query. Add the weights of the query words in each document. D3 has "cat" with weight 0.301 and "chased" with weight 1×0.602=0.6021 \times 0.602 = 0.602, so its score is 0.9030.903. D1 has "cat" only, with score 0.3010.301. D2 and D4 contain neither word, so they score 0. Check: D3 ranks first, then D1, then D2 and D4 tied at zero.

The figure shows how the rarity score falls as a word appears in more documents. It reaches zero when the word is in every document.

11.522.533.5400.20.40.6documents containing the wordrarity score (idf)
  • rarity score for N = 4
A word in one document scores 0.602, in two documents 0.301, and in all four documents 0.

The math

Definition: TF-IDF

For a term tt, a document dd and a collection of NN documents, let tf(t,d)\mathrm{tf}(t, d) be the number of times tt occurs in dd, let df(t)\mathrm{df}(t) be the number of documents that contain tt, and let

idf(t)=log⁡10 ⁣(Ndf(t)),tfidf(t,d)=tf(t,d)×idf(t).\mathrm{idf}(t) = \log_{10}\!\left(\frac{N}{\mathrm{df}(t)}\right), \qquad \mathrm{tfidf}(t, d) = \mathrm{tf}(t, d) \times \mathrm{idf}(t).

The score of a query qq, a set of terms, for document dd is score(q,d)=∑t∈qtfidf(t,d)\mathrm{score}(q, d) = \sum_{t \in q} \mathrm{tfidf}(t, d).

Different textbooks use different logarithm bases and different smoothing rules. This lesson uses base 10 so the numbers stay easy to check. The shape of the formula is the same in every version.

Step 1 in symbols: term frequency

tf(t,d)\mathrm{tf}(t, d) is the count from the bag of words. In the example, tf(the,D1)=2\mathrm{tf}(\text{the}, D_1) = 2 and tf(cat,D1)=1\mathrm{tf}(\text{cat}, D_1) = 1.

Step 2 in symbols: document frequency

df(t)\mathrm{df}(t) counts documents, not occurrences. A word that appears three times in one document has df=1\mathrm{df} = 1 and tf=3\mathrm{tf} = 3. In the example, df(the)=4\mathrm{df}(\text{the}) = 4 and df(cat)=2\mathrm{df}(\text{cat}) = 2.

Step 3 in symbols: inverse document frequency

The ratio N/df(t)N / \mathrm{df}(t) is at least 1, because a word cannot appear in more documents than exist. Its logarithm is zero when the ratio is 1, which happens when the word is in every document. In the example,

idf(the)=log⁡10 ⁣(44)=0,idf(cat)=log⁡10 ⁣(42)≈0.301.\mathrm{idf}(\text{the}) = \log_{10}\!\left(\frac{4}{4}\right) = 0, \qquad \mathrm{idf}(\text{cat}) = \log_{10}\!\left(\frac{4}{2}\right) \approx 0.301.

The logarithm also keeps the scores moderate. Doubling the collection adds a fixed amount, log⁡102\log_{10} 2, to every word's rarity score rather than doubling it.

Step 4 in symbols: the weight

Multiplying term frequency by inverse document frequency gives the weight. For D1 and "cat", tfidf=1×0.301=0.301\mathrm{tfidf} = 1 \times 0.301 = 0.301. For D1 and "the", tfidf=2×0=0\mathrm{tfidf} = 2 \times 0 = 0.

Step 5 in symbols: the score

The query score is the sum over the query's terms. For the query "cat chased" and document D3,

score(q,D3)=tfidf(cat,D3)+tfidf(chased,D3)=0.301+0.602=0.903.\mathrm{score}(q, D_3) = \mathrm{tfidf}(\text{cat}, D_3) + \mathrm{tfidf}(\text{chased}, D_3) = 0.301 + 0.602 = 0.903.

Worked examples

Example
Example 1: two documents (tiny)

The collection has two documents: "red apple" and "red pear". So N=2N = 2.

  1. Document frequencies: "red" appears in 2 documents, "apple" in 1, "pear" in 1.
  2. Inverse document frequencies: log⁡10(2/2)=0\log_{10}(2/2) = 0 for "red", and log⁡10(2/1)≈0.301\log_{10}(2/1) \approx 0.301 for "apple" and "pear".
  3. Weights in document 1: "red" gets 1×0=01 \times 0 = 0, and "apple" gets 1×0.301=0.3011 \times 0.301 = 0.301.
  4. The query "apple" scores document 1 at 0.301 and document 2 at 0.
  5. Check: document 1 ranks first, as it should, because it is the only one with the word "apple".

The interpretation: "red" appears in both documents, so it tells us nothing about which one the reader wants. The rarer word decides the ranking.

Example
Example 2: the four-document collection (standard)

Use the collection from "How it works". Compute the weights of D1 for every word and rank the documents for the query "cat chased".

  1. Document D1 has counts: "the" 2, "cat" 1, "sat" 1, "on" 1, "mat" 1.
  2. Their rarity scores: "the" 0, and the four others each 0.301, since each of them appears in exactly two documents.
  3. Weights in D1: "the" 2×0=02 \times 0 = 0; "cat" 1×0.301=0.3011 \times 0.301 = 0.301; "sat" 0.3010.301; "on" 0.3010.301; "mat" 0.3010.301.
  4. Score for D1 with the query "cat chased": only "cat" appears in D1, so the score is 0.3010.301.
  5. Score for D3: "cat" 0.301 and "chased" 1×0.602=0.6021 \times 0.602 = 0.602, total 0.9030.903.
  6. Score for D2 and D4: both 0, since they contain neither word.
  7. Check: D3 at 0.903, then D1 at 0.301, then D2 and D4 at 0.

The interpretation: "chased" appears only in D3, so it is worth more than "cat", which appears in two documents. The score rewards the rarer word, and D3 wins because it contains both.

Example
Example 3: a large collection (realistic)

A collection has 1,000,000 documents. Two terms are compared in one article of 200 words.

  • "solar" appears in 2,000 documents and 6 times in this article.
  • "the" appears in 990,000 documents and 12 times in this article.
  1. Inverse document frequency of "solar": log⁡10(1,000,000/2,000)=log⁡10(500)≈2.699\log_{10}(1{,}000{,}000 / 2{,}000) = \log_{10}(500) \approx 2.699.
  2. Weight of "solar" in the article: 6×2.699≈16.196 \times 2.699 \approx 16.19.
  3. Inverse document frequency of "the": log⁡10(1,000,000/990,000)=log⁡10(1.0101)≈0.0044\log_{10}(1{,}000{,}000 / 990{,}000) = \log_{10}(1.0101) \approx 0.0044.
  4. Weight of "the" in the article: 12×0.0044≈0.05212 \times 0.0044 \approx 0.052.
  5. Check: "the" appears twice as often as "solar", yet its weight is about 300 times smaller.

The interpretation: an article about solar energy is found by its subject words, not by how often it uses "the". The rarity term does the work that a stop-word list would otherwise do by hand.

Try it: a term appears in 50 of 1,000 documents and 4 times in an article. Find its TF-IDF weight. Answer: idf=log⁡10(1000/50)=log⁡10(20)≈1.301\mathrm{idf} = \log_{10}(1000 / 50) = \log_{10}(20) \approx 1.301, and the weight is 4×1.301≈5.204 \times 1.301 \approx 5.20.

Common mistakes and tradeoffs

It is tempting to think that a high IDF makes a word important. In fact IDF measures only rarity across the collection. A misspelling that appears in one document has the highest IDF and is useless to the reader. Rarity is necessary for a useful keyword but not sufficient.

It is tempting to think that TF-IDF understands meaning. In fact it matches the exact words. "Car" and "automobile" count as different words, and word order is lost in the bag-of-words step, so "dog bites man" and "man bites dog" get identical scores. Embeddings and neural models handle meaning; TF-IDF handles shared vocabulary.

It is tempting to think that long documents are fairly treated by raw counts. In fact a document of 10,000 words will usually have higher counts than a document of 100 words on the same subject. Practical systems divide term frequency by document length, or normalise the whole weight vector to unit length, so that length does not dominate the score.

It is tempting to think that IDF is computed from the query. In fact it must come from the collection, because the query is too small to show which words are common. A query word that never appears in the collection has document frequency zero, and the formula breaks, so implementations use smoothing, such as adding 1 to the document frequency.

TF-IDF is cheap, explainable and works well on keyword queries over large text collections. Use it as a baseline, or when users search with specific words. Do not rely on it alone for synonyms, paraphrases or questions whose answers use different words from the query. Alternatives include BM25, a refinement that also controls the effect of document length, and dense embeddings for meaning-based search.

History

Before the 1970s, information retrieval systems mostly matched whether a document contained a query word, and they had no good way to rank documents by relevance. In the 1960s and early 1970s Gerard Salton and his group at Cornell developed the vector space model, which represents each document as a vector of word weights and ranks documents by the similarity of vectors.

In 1972 Karen Spärck Jones published a short paper on term specificity. She showed that a word's value for retrieval depends on how many documents it appears in, and she introduced the inverse document frequency idea. The idea was simple and effective, and it caught on because it gave a principled reason to ignore common words without a hand-written list.

In the late 1980s Salton and Christopher Buckley compared many weighting schemes and found that combining term frequency with inverse document frequency worked consistently well, which established the combination under the name TF-IDF. It became the default weighting for text search and remained so through the rise of web search engines.

Recap

  • A bag of words turns each document into counts of its words, with word order discarded.
  • Document frequency counts how many documents contain each word, and inverse document frequency is the logarithm of the collection size divided by that count.
  • TF-IDF multiplies a word's count in a document by its inverse document frequency, so common words get weight near zero.
  • A query is scored by adding the TF-IDF weights of its words in each document, which ranks documents by shared rare words.

Read next: Cosine Similarity, which compares whole TF-IDF vectors to find related documents, and Inverted Index, which stores the weights so that a search reads only the documents that contain the query words.

Check yourself

QuestionWhy does the word 'the' have weight zero in every document of the four-document collection?Show answer

Its document frequency is 4, which equals NN. The inverse document frequency is log⁡10(4/4)=log⁡10(1)=0\log_{10}(4/4) = \log_{10}(1) = 0, and any count multiplied by zero gives zero. The word appears everywhere, so it cannot tell documents apart.

QuestionA collection has 100 documents. A word appears in 10 of them, 3 times in one document. What is its TF-IDF weight in that document?Show answer

The inverse document frequency is log⁡10(100/10)=log⁡10(10)=1\log_{10}(100 / 10) = \log_{10}(10) = 1. The weight is 3×1=33 \times 1 = 3. Answer: 3.

QuestionA search for 'cheap flights' ranks a long travel blog above a short page that is exactly about cheap flights. What is the likely cause, and how is it fixed?Show answer

Raw counts favour long documents, which contain more occurrences of the query words. The fix is to normalise term frequency by document length, or to normalise the weight vector, so that a short page with a high proportion of the query words can score higher.

QuestionA user searches for 'automobile insurance', but the best page says 'car insurance' throughout. Why does TF-IDF miss it, and what would help?Show answer

TF-IDF matches exact words, and 'automobile' and 'car' are different terms with no shared weight, so the page gets only the score for 'insurance'. Synonym expansion, where the query is extended with related words, or a meaning-based embedding model would reach the page.

Sources