Chapter 10 of 42 · ~18 min read & lab+60 XP
Chapter 10 · Machine Learning

Text Features in Classical ML: Bag of Words, TF-IDF & N-Grams

How to turn raw emails, reviews, and search queries into fast, high-signal numeric vectors for Naive Bayes, Logistic Regression, and Linear SVM

What Is It?

Bag of Words (BoW), N-Grams, and TF-IDF convert raw text documents into sparse numeric feature vectors by counting words/phrases and down-weighting common filler words like 'the' and 'is'.

Why Is It Required?

Classical ML models cannot read raw strings, and a fast TF-IDF + Logistic Regression pipeline often beats a 100× more expensive LLM on spam filtering, support-ticket routing, and sentiment classification.

Everyday Analogy: Highlighting only the rare, topic-defining words on a page ('refund', 'overcharged') while dimming generic words ('the', 'and') that appear on every page.
Why ML Engineers & Data Scientists Actually Need This

TF-IDF + Logistic Regression or Linear SVM is the gold-standard millisecond baseline for every text classification and hybrid search system.

ML / AI Engineer

Serves 10,000+ predictions/sec on a single CPU core with zero GPU cost, and powers lexical retrieval (BM25/TF-IDF) inside modern RAG pipelines.

Data Scientist

Inspecting the top positive/negative TF-IDF weights gives instant, crystal-clear interpretability into which exact words drive churn or spam.

Interview & Debug Edge

Frequently asked: 'Why does Bag of Words fail on "not good", and how do N-grams + TF-IDF fix it?'

Step 0 · Test Your Gut Before Any Math!

Two movie reviews say: (A) 'This movie was good, not bad' and (B) 'This movie was bad, not good'. How do they look to a pure 1-word (unigram) Bag of Words?

What You Will Master in This Chapter
  • Build a Bag-of-Words count matrix from raw text documents.
  • Compute TF-IDF scores by hand and explain why IDF suppresses ubiquitous stopwords while boosting rare discriminative keywords.
  • Use Bigrams / N-Grams ('not good', 'free money') to preserve local word order and negation.
  • Recognize when TF-IDF + Linear Model beats heavy neural embeddings in latency and cost.
Plain-English Symbol Decoder · Click Any Symbol Before We Begin
1 / 2
TF(t,d)\text{TF}(t, d)Say aloud:“Term Frequency”
Plain-English Meaning
How often word t appears inside document d.
Everyday Example
'refund' appears 3 times in a 100-word email → TF = 3/100.
Story-First Intuition, Visual Diagrams & Interactive Walkthroughs

Bag of Words treats a document like a grocery bag of word counts — simple, fast, but blind to word importance and order. TF-IDF upgrades it by multiplying how often a word appears here (TF) by how rare it is everywhere else (IDF), while N-Grams glue adjacent words together ('not happy', 'credit card') so local meaning survives!

1. From Raw Text → Bag of Words → TF-IDF

Everyday Story First (Zero Math Yet!)

Imagine reading 1,000 customer support emails. Every single email contains 'hello' and 'please', so those words tell you nothing. When 'crash' or 'invoice' pops up, you instantly know which team needs the ticket!

The 3-Step Classical Text Pipeline

  1. Tokenize & Normalize: Lowercase text, strip punctuation, optionally remove stopwords.
  2. N-Grams (ngram_range=(1, 2)): Extract both single words ('good') and 2-word phrases ('not good').
  3. TF-IDF Weighting + L2 Normalization: TF-IDF(t,d)=TF(t,d)×IDF(t)\text{TF-IDF}(t, d) = \text{TF}(t, d) \times \text{IDF}(t) L2-normalizing each document vector ensures a 5-page essay doesn't automatically overpower a 2-sentence review.
Interactive Mini-Lab • Naive Bayes + Laplace Smoothing

Toggle Email Words & Watch Unseen-Word Collapse Disappear

Posterior P(Spam | words):
60.6% → SPAM

2. Leakage Rule for Text Vectorizers

Just like scalers and imputers, fit TfidfVectorizer strictly on X_train! Fitting IDF on the test set leaks future document frequencies and vocabulary into training. Any brand-new word at test time is safely ignored.

“Wait, I'm Confused...” · Teacher Office Hours Q&A

The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.

Use TF-IDF first when exact keywords matter (error codes, product SKUs, spam, fast CPU classification). Upgrade to Dense Embeddings when semantic synonyms matter ('car' ≈ 'automobile') or you need cross-lingual meaning.

Interactive Visual Lab
Lab Challenge: See how probabilistic & linear classifiers separate text classes from word features.
Flagship Deep Lab • LDA vs. QDA Covariance Geometry

Shared Variance (LDA) vs. Class-Specific Variance (QDA)

Boundary x=4.3

LDA forces one pooled variance σ, so the x² terms cancel out and you ALWAYS get a single linear boundary!

Intuition Takeaway: TF-IDF + Bigrams (ngram_range=(1, 2)) turns raw text into compact, interpretable vectors by boosting rare discriminative phrases and silencing common filler words.
Production NumPy & PyTorch Code Patterns
import math
from collections import Counter

# Minimal TF-IDF Matrix From Scratch (Pure Python)
docs = [
    "the refund for the broken laptop",
    "the laptop screen is great",
    "fast refund and great support",
]
tokenized = [d.lower().split() for d in docs]
vocab = sorted({w for doc in tokenized for w in doc})
N = len(docs)

# Document frequency df(t) and smoothed IDF
df = {w: sum(1 for doc in tokenized if w in doc) for w in vocab}
idf = {w: math.log((1 + N) / (1 + df[w])) + 1.0 for w in vocab}

for i, doc in enumerate(tokenized):
    counts = Counter(doc)
    scores = {w: round((counts[w] / len(doc)) * idf[w], 3) for w in counts}
    top2 = sorted(scores.items(), key=lambda kv: kv[1], reverse=True)[:2]
    print(f"Doc {i+1} top TF-IDF terms: {top2}")
Common ML Interview Traps & Numerical Pitfalls
Trap #1: Using ngram_range=(1, 5) on a small dataset, exploding vocabulary to millions of sparse features.
Best Practice: Stick to (1, 2) (unigrams + bigrams) with min_df=2 and max_features=20_000 to cap noise.
Chapter Mastery Check (+60 XP)
Score: 0 / 1
1In TF-IDF, what happens to the weight of a word like 'the' that appears in every single document of a corpus?

Apply What You Learned — Solve Matching Coding Problems