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
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'.
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.
TF-IDF + Logistic Regression or Linear SVM is the gold-standard millisecond baseline for every text classification and hybrid search system.
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.
Inspecting the top positive/negative TF-IDF weights gives instant, crystal-clear interpretability into which exact words drive churn or spam.
Frequently asked: 'Why does Bag of Words fail on "not good", and how do N-grams + TF-IDF fix it?'
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?
- 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.
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
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
- Tokenize & Normalize: Lowercase text, strip punctuation, optionally remove stopwords.
- N-Grams (
ngram_range=(1, 2)): Extract both single words ('good') and 2-word phrases ('not good'). - TF-IDF Weighting + L2 Normalization: L2-normalizing each document vector ensures a 5-page essay doesn't automatically overpower a 2-sentence review.
Toggle Email Words & Watch Unseen-Word Collapse Disappear
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.
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.
Shared Variance (LDA) vs. Class-Specific Variance (QDA)
LDA forces one pooled variance σ, so the x² terms cancel out and you ALWAYS get a single linear boundary!
ngram_range=(1, 2)) turns raw text into compact, interpretable vectors by boosting rare discriminative phrases and silencing common filler words.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}")
ngram_range=(1, 5) on a small dataset, exploding vocabulary to millions of sparse features.(1, 2) (unigrams + bigrams) with min_df=2 and max_features=20_000 to cap noise.'the' that appears in every single document of a corpus?