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 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".
- 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.
- 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.
- Turn each document frequency into a rarity score. The rarity score is the logarithm of divided by the document frequency. Words in all four documents get . Words in two get . Words in one get . Check: the rarer the word, the larger its score.
- Multiply counts by rarity to get the weight. In D1, "the" gets , and "cat", "sat", "on" and "mat" each get . Check: "the" contributes nothing to D1, even though it appears most often.
- Score the query. Add the weights of the query words in each document. D3 has "cat" with weight 0.301 and "chased" with weight , so its score is . D1 has "cat" only, with score . 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.
- rarity score for N = 4
The math
For a term , a document and a collection of documents, let be the number of times occurs in , let be the number of documents that contain , and let
The score of a query , a set of terms, for document is .
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
is the count from the bag of words. In the example, and .
Step 2 in symbols: document frequency
counts documents, not occurrences. A word that appears three times in one document has and . In the example, and .
Step 3 in symbols: inverse document frequency
The ratio 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,
The logarithm also keeps the scores moderate. Doubling the collection adds a fixed amount, , 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", . For D1 and "the", .
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,
Worked examples
The collection has two documents: "red apple" and "red pear". So .
- Document frequencies: "red" appears in 2 documents, "apple" in 1, "pear" in 1.
- Inverse document frequencies: for "red", and for "apple" and "pear".
- Weights in document 1: "red" gets , and "apple" gets .
- The query "apple" scores document 1 at 0.301 and document 2 at 0.
- 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.
Use the collection from "How it works". Compute the weights of D1 for every word and rank the documents for the query "cat chased".
- Document D1 has counts: "the" 2, "cat" 1, "sat" 1, "on" 1, "mat" 1.
- Their rarity scores: "the" 0, and the four others each 0.301, since each of them appears in exactly two documents.
- Weights in D1: "the" ; "cat" ; "sat" ; "on" ; "mat" .
- Score for D1 with the query "cat chased": only "cat" appears in D1, so the score is .
- Score for D3: "cat" 0.301 and "chased" , total .
- Score for D2 and D4: both 0, since they contain neither word.
- 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.
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.
- Inverse document frequency of "solar": .
- Weight of "solar" in the article: .
- Inverse document frequency of "the": .
- Weight of "the" in the article: .
- 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: , and the weight is .
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 . The inverse document frequency is , 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 . The weight is . 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
- Manning, Raghavan and Schütze, Introduction to Information Retrieval, Chapter 6: https://nlp.stanford.edu/IR-book/
- Tf-idf, Wikipedia: https://en.wikipedia.org/wiki/Tf%E2%80%93idf
- Karen Spärck Jones, Wikipedia: https://en.wikipedia.org/wiki/Karen_Sp%C3%A4rck_Jones