TF-IDF: scoring words by how useful they are

Why a rare word says more about a document than a common one, how term frequency and inverse document frequency combine, and where the idea stops working.

On the roadmap:Staff Engineer · step 1: Search and relevance

Lesson 1 of 10 · 10 min read · quiz · exercise

The problem

Given the query "cache invalidation", which of a million documents should come first? Counting matching words is a start, but not all words are equal. "The" appears everywhere and tells you nothing, while "invalidation" is rare and tells you a lot. TF-IDF turns that intuition into a number.

The two ingredients

  • Term frequency (tf): how often the term occurs in this document. More occurrences suggest the document is about it.
  • Document frequency (df): in how many documents of the whole collection the term occurs. A high df means the term is common and weakly informative.
  • Inverse document frequency (idf): log(N / df) where N is the number of documents. Rare terms get a large idf, common ones approach zero.

The weight of a term in a document is tf x idf. The score of a document for a query is the sum of the weights of the query terms it contains.

Figure SDA-SAG-01-1 · From query words to a document score · © forcsguy.com

A worked example

The collection has 10,000 documents. "cache" is in 500 of them, "invalidation" in 20.

Termdfidf = log10(N/df)tf in our documenttf weight 1 + log10(tf)contribution
cache5001.3041.602.08
invalidation202.7021.303.51

The rarer term wins even though it appears fewer times. Note the log on tf: seeing a word four times is not four times as relevant as seeing it once.

Vectors and cosine

A document can be represented as a vector with one weight per term. The query is a vector too, and the cosine of the angle between them measures similarity independent of document length. This is the classic vector space model and the starting point of many later ideas, including embedding search.

Figure SDA-SAG-01-2 · Documents and queries as vectors · © forcsguy.com

Where TF-IDF stops working

  • No saturation: even with a log, repeating a word keeps raising the score, which rewards keyword stuffing.
  • Length is handled crudely: normalising by vector length helps, but does not model that long documents naturally contain more words.
  • Words only: it knows nothing about meaning, synonyms or intent.
  • Collection statistics move: idf changes as documents are added, so engines keep approximate statistics per shard.

The next lesson shows BM25, which fixes the first two and is the default in most engines today.

Real-world reading

Check your understanding

Question 1 of 3

0 correct so far

Why is the word 'the' given almost no weight by TF-IDF?

Go deeper

Topics covered in this lesson

All topics

© 2026 forcsguy.com. Original lesson text and diagrams. Books and sites linked above belong to their authors.