Notes

TF-IDF

Count the words in a document and the list is dominated by the, of and and — words that tell you nothing about what the document is about. TF-IDF is the fix: weight each word by how much it distinguishes this document from every other one.

Two numbers multiplied
Term frequency counts how often a word appears in a single document, and inverse document frequency measures how rare that word is across the collection — the log of the ratio between the number of documents and the number containing the word. Multiplying them gives a weight that is high only when a word is frequent here and uncommon elsewhere. Diabetes in a medical note scores heavily; the, which appears everywhere, collapses to near zero without anyone writing a stop-word list.

Where you meet it
It is the default weighting on a document-term matrix, and it is what makes cosine similarity between two documents mean something. Scikit-learn ships it as TfidfVectorizer, and a few lines of it are enough to:

  • retrieve documents matching a keyword query, ranked by shared rare terms;
  • cluster news articles by theme with no labels at all;
  • train a spam or sentiment classifier that beats a raw-count baseline.

Its limits
TF-IDF knows nothing about meaning. Trainers and running shoes are unrelated dimensions to it, so a search box built on it misses a match any embedding would catch. It also assumes the collection is representative: IDF computed on one corpus and applied to another weights words by the wrong rarity. Those gaps are what dense retrieval and BM25's length handling were built to address.

TF-IDF weights a word in a document by multiplying its term frequency in that document by its inverse document frequency across the collection, so a term scores highly only when it is common here and rare elsewhere. It turns raw counts into a document-term matrix where cosine similarity is meaningful, which is why it underpins keyword retrieval and strong text-classification baselines. It captures distinctiveness, not meaning — synonyms stay unrelated.

Suppose you want to describe what a book is about using only a handful of its words. The most common ones are useless — every book is full of the and and. What tells you something is a word that appears a lot in this book and hardly anywhere else.

That is the whole idea behind TF-IDF. Software scores each word twice: once for how often it appears in the document in front of it, and once for how unusual the word is across everything else it has seen. Words that score well on both become the document's fingerprint. It is how a search box decides which pages are really about what you typed, not just which ones mention it.