Level 0: Foundation
★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.Counting words, but weighting the rare ones
One simple way to turn a document into numbers is to count each word in it, ignoring word order: a “bag of words”. But “the” and “and” appear everywhere and say nothing about the topic. TF-IDF fixes this by multiplying each count by how rare the word is across all documents, so “rocket” counts for much more than “the”. The demo shows the weights for one document: “the” gets zero.
TF-IDF search is fast, transparent and needs no training. It is still used to search maintenance manuals, incident databases and requirement documents, and as the first stage (BM25) of many modern retrieval systems.
- 1. A bag of words ignores…
- 2. IDF gives high weight to words that are…
- 3. The word 'the' usually gets a TF-IDF weight near…
Level 1: Beginner
★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.By hand
- Vectors: with vocabulary V, each document is a vector in ℝ^|V|. Variants: raw counts, binary presence, tf = count / document length.
- IDF: idf(w) = log(N / df(w)), where df(w) is the number of documents containing w. A word in every document gets idf 0; scikit-learn’s smoothed version is log((1 + N)/(1 + df)) + 1.
- TF-IDF: tf(w, d) × idf(w). Sublinear tf uses 1 + log(count) so that 100 occurrences count only about 5.6 times as much as one.
- Cosine similarity: cos(a, b) = a·b / (‖a‖‖b‖). It ignores vector length, hence document length. Raw dot products favour long documents.
- Sparsity: each document uses a tiny fraction of the vocabulary (5000 non-zeros in a 1000 × 50,000 matrix is 99.99% zeros), so sparse matrices are essential.
- Extensions: n-gram features (“not good”), character n-grams for typos, and BM25, which saturates tf and normalises by length.
- 1. idf of a word in every one of N documents:
- 2. Cosine similarity is insensitive to…
- 3. Sublinear tf of a count of 1:
Level 2: Intermediate
★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.TF-IDF in code
Exercise 1.
- Build a vocabulary and count matrix.
- Compute L2-normalised TF-IDF; ‘the’, present in every document, gets weight 0.
- Compare documents by cosine similarity.
Practice.
- scikit-learn’s
TfidfVectorizerhandles tokenisation, n-grams, min/max document frequency, sublinear tf and L2 normalisation, producing sparse matrices. - Fit the vocabulary and idf on training documents only.
- Linear models (logistic regression, linear SVM) on TF-IDF features are strong, fast text-classification baselines.
- For search, BM25 (rank_bm25, Elasticsearch, Lucene) usually beats plain TF-IDF.
from sklearn.feature_extraction.text import TfidfVectorizer
vec = TfidfVectorizer(ngram_range=(1, 2), min_df=2, sublinear_tf=True)
Xtr = vec.fit_transform(train_docs); Xte = vec.transform(test_docs) # sparse, rows L2-normalised
sims = Xte @ Xtr.T # cosine similarities- 1. scikit-learn's TF-IDF class:
- 2. Idf is fitted on…
- 3. Strong TF-IDF classifiers are…
Level 3: Advanced
★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.Theory
Why idf works. idf is the self-information −log P(w appears in a document) of the event “a document contains w”. Rare words carry more information about which document we are looking at. Robertson (2004) connects idf to probabilistic relevance models, which lead to BM25.
Why normalise. A document twice as long has roughly twice the counts. Unnormalised dot products then grow with length, so long documents look similar to everything. L2 normalisation (cosine similarity) compares only the direction, that is, the relative word proportions.
Limits. Bags of words ignore order (“dog bites man” = “man bites dog”), treat synonyms as unrelated dimensions, and grow with the vocabulary. Dense embeddings (F3) address the last two.
- 1. idf can be read as…
- 2. Without normalisation, dot products favour…
- 3. Bags of words cannot distinguish…
Level 4: Expert
★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.How much do weighting and normalisation matter for document similarity?
History.
- K. Spärck Jones, “A statistical interpretation of term specificity and its application in retrieval” (Journal of Documentation, 1972), which introduced idf.
- G. Salton and C. Buckley, “Term-weighting approaches in automatic text retrieval” (1988).
Exercise 2.
- Data: synthetic documents from 4 topics. Each has 15 topic words making up 10% of its words; the rest come from a shared Zipfian pool of 200 general words. Lengths are log-normal, from 20 to 800 words.
- Task: classify 1000 test documents by their most similar of 400 training documents (1-nearest-neighbour).
- Representations: raw counts, binary, tf, tf-idf and sublinear tf-idf (smoothed idf), each with cosine similarity or a raw dot product.
| representation | cosine | dot product |
|---|---|---|
| counts | 0.813 | 0.300 |
| binary | 0.903 | 0.968 |
| tf | 0.813 | 0.247 |
| tf-idf | 0.970 | 0.525 |
| sublinear tf-idf | 0.979 | 0.984 |
- idf suppresses the shared vocabulary: tf-idf with cosine scores 0.97 against 0.81 for counts. Mean idf was 3.09 for topic words against 2.60 for general words.
- Length bias breaks raw dot products: counts with dot products score 0.30, close to chance (0.25), because the longest training documents match everything.
- Dampening the counts also removes the length effect: binary and sublinear tf-idf vectors grow slowly with length, so they work even without normalisation.
- A surprise: binary vectors did better with dot products (0.968) than with cosine (0.903). Normalising by the number of distinct words penalises long documents, which also contain more of the topic words.
- Seeds: seeds 1 and 2 gave tf-idf cosine 0.971/0.969 against counts cosine 0.797/0.800, and counts dot product 0.272/0.339.
TF-IDF in AI, robotics and aerospace
- Technical document search: finding relevant sections in manuals, standards and incident reports.
- Report triage: fast linear classifiers routing maintenance or anomaly reports.
- Retrieval-augmented generation: BM25, a TF-IDF descendant, as the sparse half of hybrid search (F10).
- Design lesson: weight by rarity and normalise for length before comparing documents.
References
- K. Spärck Jones (1972). “A statistical interpretation of term specificity and its application in retrieval.” Journal of Documentation 28(1).
- G. Salton and C. Buckley (1988). “Term-weighting approaches in automatic text retrieval.” Information Processing and Management 24(5).
- S. Robertson (2004). “Understanding inverse document frequency: on theoretical arguments for IDF.” Journal of Documentation 60(5).