Bag-of-Words & TF-IDF
Vectorize documents with counts and TF-IDF for strong classical text baselines.
In plain words
Count how many times each word appears in a piece of text, then give extra credit to words that are special to that text and little credit to words every text uses.
Think of it like…
Judging a library book by its index. Every word is tallied, but words that appear in every book (the, of) tell you nothing about which book to pick, while a rare word that appears many times in one book ("mitochondria") is a strong clue.
Where you’ve seen it
A three-document corpus: d1 "the cat sat", d2 "the dog sat", d3 "the cat ate the fish", with a six-word vocabulary (the, cat, sat, dog, ate, fish). Counts for d3 are the 2, cat 1, ate 1, fish 1. Document frequencies are the 3, cat 2, sat 2, dog 1, ate 1, fish 1, so scikit-learn's smoothed idf is 1.000 for the, 1.288 for cat (ln(4/3) + 1) and 1.693 for the rare words (ln(4/2) + 1). The raw TF-IDF for d3 is the 2 × 1.000 = 2.000, cat 1.288, ate 1.693, fish 1.693, with L2 norm √(4 + 1.658 + 2.867 + 2.867) = 3.375, so the normalised vector is the 0.593, cat 0.382, ate 0.502, fish 0.502. Notice that the still has the largest weight in d3 because it appears twice and its smoothed idf is never below 1, which is why stop words are removed or max_df is set. Cosine similarity between d1 and d2 on raw counts is 2 / (√3 × √3) = 0.667. At scale, a 10,000-document corpus with a 50,000-word vocabulary stored densely in float64 would need 10,000 × 50,000 × 8 = 4 GB, but with about 100 non-zero words per document the sparse matrix has 1,000,000 stored values (about 12 MB with 8-byte values and 4-byte indices), 0.2% density. A logistic regression on unigrams and bigrams (min_df = 3, sublinear_tf) is the team's baseline before trying embeddings.
Words you’ll hear
- Term frequency (TF)
- How often a term occurs in a document, optionally log-scaled.
- Document frequency (DF)
- The number of documents that contain a term.
- IDF
- Inverse document frequency: larger for terms found in few documents.
- Sparse matrix
- A matrix storing only non-zero entries, essential for text vectors.
Visual diagram
Theory & deep dive
Counts, TF-IDF and normalisation by hand
In the textbook form tf-idf(t, d) = tf(t, d) × ln(N / df(t)). Scikit-learn uses a smoothed idf, ln((1 + N) / (1 + df)) + 1, so terms in every document still get weight 1 and nothing divides by zero, then L2-normalises each row so documents of different length are comparable. For N = 3: df 3 → idf 1.000; df 2 → ln(4/3) + 1 = 1.288; df 1 → ln(4/2) + 1 = 1.693. For d3 (the ×2, cat, ate, fish) the weights are 2.000, 1.288, 1.693 and 1.693; the sum of squares is 4 + 1.658 + 2.867 + 2.867 = 11.392, so the norm is 3.375 and the normalised vector is (0.593, 0.382, 0.502, 0.502), with squares summing to 1.
Useful options: ngram_range=(1, 2) adds bigrams such as "not good" that recover some word order; min_df removes rare typos and max_df removes ubiquitous words (an alternative to stop-word lists); sublinear_tf=True replaces tf by 1 + ln(tf) so a word repeated 50 times does not swamp one repeated twice; max_features caps the vocabulary. Fit the vectoriser on the training split only inside a pipeline, and reuse it for validation, test and serving.
Vocabulary order (the, cat, sat, dog, ate, fish). d1 = (1, 1, 1, 0, 0, 0), d2 = (1, 0, 1, 1, 0, 0). Dot product 2, norms √3 each, cosine = 2 / 3 = 0.667. d1 versus d3 = (2, 1, 0, 0, 1, 1): dot 3, norms √3 and √7, cosine 3 / 4.583 = 0.655.
Sparsity, models and limits
Text matrices are extremely sparse: a 50,000-word vocabulary with 100 distinct words per document is 0.2% dense. Stored densely, 10,000 documents × 50,000 columns × 8 bytes = 4 GB; stored sparsely, 1,000,000 non-zeros need about 12 MB (value plus column index). That is why scipy.sparse and algorithms that exploit it (logistic regression with liblinear or saga, linear SVMs, Naive Bayes, SGD classifiers) are the default, while tree ensembles and distance computations on dense vectors are awkward. Linear models also give interpretability: sort coefficients to see which words push towards each class and sanity-check for spurious features such as boilerplate or IDs.
Limits: no word order or context ("dog bites man" equals "man bites dog" without n-grams), no synonyms ("car" and "automobile" are unrelated columns), a vocabulary frozen at training time and high dimensionality. Embeddings and transformers address these, but TF-IDF stays competitive on long documents, small datasets and keyword-heavy tasks, trains in seconds and is easy to debug. Use it as the baseline, tune C, n-grams and min_df by cross-validation, and measure the lift from anything more complex against it.
10,000 documents × 50,000 columns, float64 dense: 4,000,000,000 bytes = 4 GB. Sparse with 100 non-zeros per document: 1,000,000 values × (8 + 4 bytes) ≈ 12 MB plus row pointers, a 300× saving.
How it works, step by step
Step 1 of 41. Split first
Create train, validation and test splits before fitting any vectoriser.
- Avoid
- leakage
When to use it & trade-offs
What it is
Bag of words (BoW) represents each document as a vector of word counts over a fixed vocabulary, ignoring word order. TF-IDF reweights those counts: term frequency (TF) rewards words that appear often in a document and inverse document frequency (IDF) penalises words that appear in many documents, so distinctive terms dominate. In scikit-learn, CountVectorizer builds counts and TfidfVectorizer builds smoothed, L2-normalised TF-IDF with idf = ln((1 + N) / (1 + df)) + 1. The result is a very sparse matrix that feeds linear models (logistic regression, linear SVM), Naive Bayes and nearest-neighbour search, forming one of the strongest cheap baselines for text classification and retrieval.
Why it matters: A linear model on TF-IDF is fast, interpretable (each word has a coefficient), needs little data and often comes within a few points of far heavier neural models. It is also the right first baseline: if a fine-tuned transformer cannot beat it by enough to justify the cost, the heavier model isn't worth shipping. Knowing the formula, the sparsity arithmetic and the options (n-grams, min_df, max_df, sublinear tf) lets you tune it intelligently and explain what it can and cannot capture (no word order, no synonyms).
When to reach for it
- A first baseline for any text classification task
- Keyword-oriented retrieval and document similarity
- Interpretable models where coefficients must be reviewed
When to avoid or be careful
- Fitting the vectoriser on the full dataset before splitting
- Converting a large TF-IDF matrix to a dense array
- Expecting synonyms or word order to be captured without n-grams
Text representations
Strengths: Simple and fast.
Watch out: Common words dominate.
Strengths: Highlights distinctive terms; strong baseline.
Watch out: No order or semantics.
Strengths: Captures meaning and synonyms.
Watch out: Costlier and harder to interpret.
Interview signals & numbers to know
When this topic comes up
- “Compute TF-IDF for this tiny corpus”
- Why IDF down-weights common words
- Sparse versus dense storage
- How n-grams recover some order
- When TF-IDF beats embeddings
Benchmarks & rules of thumb
- ln((1 + N)/(1 + df)) + 1
- scikit-learn's smoothed idf
- 0.2%
- density when 100 of 50,000 vocabulary words appear in a document
- 4 GB vs ≈ 12 MB
- dense versus sparse storage for 10,000 documents
Common mistakes & follow-ups
Common interview mistakes
- Leaving stop words in without max_df and wondering why they dominate.
- Using raw counts without normalising document length.
- Skipping the TF-IDF baseline and jumping to a transformer.
Likely interviewer follow-ups
- Why does TF-IDF smooth the idf?
- How would you capture negation in a TF-IDF model?
- What do you lose compared with embeddings?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Bag-of-Words & TF-IDF with data science interview Q&A and hands-on practice.