Advanced Text Classification: TF-IDF to Transformers
Text classification is the workhorse of applied NLP: routing support tickets, moderating comments, tagging documents, detecting spam, and triaging emails. The gap between a demo notebook and a production classifier is wide â it spans baseline selection, handling label imbalance, multi-label taxonomies, calibration, and the operational cost of serving transformers. This lesson covers the full modeling ladder and the engineering decisions that come with each rung.
You will learn why a TF-IDF + linear SVM baseline remains the correct first model for almost every problem, when fastText earns its place, how to fine-tune BERT without overfitting small datasets, and how to structure multi-label and hierarchical problems so metrics mean something. The emphasis is on decision-making: each technique is paired with the conditions under which it wins.
What You'll Learn
- 1Train and interpret a TF-IDF + LinearSVC baseline with cross-validation
- 2Fine-tune BERT for classification with sensible hyperparameters and class handling
- 3Frame multi-label problems with binary relevance and tune per-label thresholds
- 4Design hierarchical classifiers for deep label taxonomies
Prerequisites
- !scikit-learn pipelines and cross-validation
- !Basic PyTorch or Hugging Face familiarity
- !Classification metrics: precision, recall, F1, confusion matrices
Why the baseline comes first
Teams routinely jump straight to fine-tuned transformers, then cannot explain what the GPU budget bought. A TF-IDF + LinearSVC pipeline trains in seconds, is fully interpretable through per-class feature weights, and on short-text tasks with clear vocabulary signals (topic routing, spam, intent) it frequently lands within one or two F1 points of BERT. Establishing that baseline tells you the headroom available: if SVM scores 0.94, a transformer must justify itself on the remaining 6 points; if SVM scores 0.62, the problem needs richer representations or better labels.
The second reason is diagnostic. SVM feature weights surface the tokens driving decisions, so mislabeled training examples and leakage features (a "refund" token that only appears in one class because of a data-collection artifact) show up immediately. Transformers bury the same problems inside 110 million parameters.
import numpy as np
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.svm import LinearSVC
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline
from sklearn.model_selection import cross_val_score, StratifiedKFold
from sklearn.metrics import classification_report
rng = np.random.default_rng(42)
templates = {
"sports": "team won championship match player goal tournament league coach season playoffs",
"politics": "election campaign vote policy government senate congress legislation debate",
"technology": "software startup app programming algorithm machine learning cloud device",
"entertainment": "movie actor director box office music album concert celebrity streaming",
}
documents, labels = [], []
for label, vocab in templates.items():
words = vocab.split()
for _ in range(500):
picked = rng.choice(words, size=rng.integers(8, 16), replace=True)
documents.append(" ".join(picked))
labels.append(label)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
svm_pipe = Pipeline([
("tfidf", TfidfVectorizer(max_features=20000, ngram_range=(1, 2),
min_df=2, sublinear_tf=True)),
("clf", LinearSVC(C=1.0, max_iter=10000, random_state=42)),
])
scores = cross_val_score(svm_pipe, documents, labels, cv=cv, scoring="f1_macro")
print(f"TF-IDF + LinearSVC macro-F1: {scores.mean():.4f} +/- {scores.std():.4f}")
svm_pipe.fit(documents, labels)
print(classification_report(labels, svm_pipe.predict(documents), zero_division=0))
Two vectorizer settings do most of the work. sublinear_tf=True applies 1 + log(tf), damping the influence of repeated terms â raw term frequency overweights boilerplate. ngram_range=(1, 2) captures negation and light phrasing ("not good", "customer service") without the sparsity explosion of longer n-grams.
When fastText earns its place
fastText trains a shallow classifier over averaged n-gram embeddings, giving it near-BERT accuracy on many short-text tasks at SVM-like training speed and sub-millisecond inference. It shines for large multilingual corpora, low-latency scoring pipelines, and environments without GPUs. Its weakness is long documents where bag-of-n-grams semantics lose word order entirely.
# FastText supervised format: __label__CLASS TEXT
def write_fasttext(path, docs, labs):
with open(path, "w", encoding="utf-8") as f:
for d, l in zip(docs, labs):
f.write(f"__label__{l} {d}\n")
write_fasttext("train.txt", documents[:1600], labels[:1600])
write_fasttext("test.txt", documents[1600:], labels[1600:])
try:
import fasttext
ft = fasttext.train_supervised(
"train.txt", lr=0.5, epoch=25, wordNgrams=2, dim=50, loss="softmax"
)
n, p, r = ft.test("test.txt")
print(f"fastText accuracy={p:.4f} recall@1={r:.4f}")
# Autotune searches hyperparameters for 30 seconds
ft_tuned = fasttext.train_supervised(
"train.txt", autotuneValidationFile="test.txt", autotuneDuration=30
)
except ImportError:
print("pip install fasttext")
fastText also handles subwords natively: words sharing character n-grams share statistical strength, which helps morphology-rich languages and typos. If your corpus is noisy user-generated text in more than one language, try fastText before paying for transformer inference.
Fine-tuning BERT without overfitting
Transformer fine-tuning succeeds or fails on hyperparameters and data scale. With fewer than roughly 1,000 examples per class, full-model fine-tuning overfits quickly; freeze most layers or use a smaller distilled model. With tens of thousands of examples, full fine-tuning with a linear warmup and decay schedule is reliable. The canonical learning rate is 2e-5 â large enough to adapt, small enough to preserve pretrained features.
import torch
import torch.nn as nn
from torch.utils.data import Dataset, DataLoader
from transformers import BertTokenizer, BertModel, AdamW, get_linear_schedule_with_warmup
class TextClsDataset(Dataset):
def __init__(self, texts, label_ids, tokenizer, max_len=128):
self.texts, self.label_ids = texts, label_ids
self.tok, self.max_len = tokenizer, max_len
def __len__(self):
return len(self.texts)
def __getitem__(self, i):
enc = self.tok(self.texts[i], max_length=self.max_len, padding="max_length",
truncation=True, return_tensors="pt")
return {
"input_ids": enc["input_ids"].squeeze(0),
"attention_mask": enc["attention_mask"].squeeze(0),
"label": torch.tensor(self.label_ids[i], dtype=torch.long),
}
class BertClassifier(nn.Module):
def __init__(self, n_classes, model_name="bert-base-uncased", dropout=0.1):
super().__init__()
self.bert = BertModel.from_pretrained(model_name)
self.drop = nn.Dropout(dropout)
self.fc = nn.Linear(self.bert.config.hidden_size, n_classes)
def forward(self, input_ids, attention_mask):
out = self.bert(input_ids=input_ids, attention_mask=attention_mask)
return self.fc(self.drop(out.pooler_output))
def fine_tune(train_texts, train_labels, n_classes=4, epochs=3, batch_size=16, lr=2e-5):
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
tok = BertTokenizer.from_pretrained("bert-base-uncased")
loader = DataLoader(TextClsDataset(train_texts, train_labels, tok),
batch_size=batch_size, shuffle=True)
model = BertClassifier(n_classes).to(device)
opt = AdamW(model.parameters(), lr=lr, weight_decay=0.01)
total_steps = len(loader) * epochs
sched = get_linear_schedule_with_warmup(opt, int(0.1 * total_steps), total_steps)
loss_fn = nn.CrossEntropyLoss()
for epoch in range(epochs):
model.train()
running = 0.0
for batch in loader:
ids = batch["input_ids"].to(device)
mask = batch["attention_mask"].to(device)
y = batch["label"].to(device)
logits = model(ids, mask)
loss = loss_fn(logits, y)
loss.backward()
nn.utils.clip_grad_norm_(model.parameters(), 1.0)
opt.step(); sched.step(); opt.zero_grad()
running += loss.item()
print(f"epoch {epoch+1} loss={running/len(loader):.4f}")
return model, tok
# model, tok = fine_tune(train_texts, train_ids, n_classes=4)
print("BERT fine-tuning utilities ready")
Class imbalance needs explicit handling. For severe imbalance, combine class-weighted cross-entropy (a weight= tensor inversely proportional to class frequency) with stratified batching. For moderate imbalance, oversampling the minority class with careful deduplication usually suffices. Never oversample before splitting â duplicated examples leak across the train/test boundary and inflate metrics.
Multi-label classification
Many real taxonomies allow multiple labels per document: a news article is both politics and economics; a ticket is billing and urgent. Multi-label evaluation uses per-label thresholds tuned on a validation set, and metrics shift to micro/macro F1 over label sets plus example-based F1.
from sklearn.preprocessing import MultiLabelBinarizer
from sklearn.metrics import f1_score
class BinaryRelevance:
"""One logistic regression per label - simple, parallel, strong baseline."""
def __init__(self, max_features=20000):
self.vec = TfidfVectorizer(max_features=max_features, ngram_range=(1, 2),
sublinear_tf=True)
self.clfs = []
def fit(self, texts, Y):
X = self.vec.fit_transform(texts)
self.clfs = []
for col in range(Y.shape[1]):
clf = LogisticRegression(max_iter=1000, class_weight="balanced")
clf.fit(X, Y[:, col])
self.clfs.append(clf)
return self
def predict_proba(self, texts):
X = self.vec.transform(texts)
return np.column_stack([c.predict_proba(X)[:, 1] for c in self.clfs])
mlb = MultiLabelBinarizer()
Y = mlb.fit_transform([
[("politics", "econ")], [("sports",)], [("tech", "econ")], [("politics", "tech")]
] * 100)
docs_ml = documents[:400]
Y = Y[: len(docs_ml)] if len(Y) > len(docs_ml) else np.vstack([Y, Y[: len(docs_ml) - len(Y)]])
br = BinaryRelevance().fit(docs_ml, Y)
proba = br.predict_proba(docs_ml)
# Tune a global threshold on validation data - default 0.5 is rarely optimal
best_t, best = 0.5, 0.0
for t in np.arange(0.2, 0.8, 0.05):
f1 = f1_score(Y, (proba >= t).astype(int), average="micro", zero_division=0)
if f1 > best:
best, best_t = f1, t
print(f"best threshold={best_t:.2f} micro-F1={best:.4f}")
Classifier chains model label dependence by feeding earlier predictions as features to later classifiers â useful when the label set has known correlations (economics implies finance). For very large label sets (thousands of product categories), move to embeddings-based retrieval rather than one classifier per label.
Hierarchical taxonomies
When labels form a tree â Support then Billing then Refund Dispute â flat classification wastes structure and produces impossible outputs (a leaf from the wrong parent). Two-stage hierarchical classification first predicts the coarse branch, then runs a specialist classifier per branch. Errors become interpretable (was the top-level split wrong, or the leaf?), and per-branch models can be trained and refreshed independently.
class HierarchicalClassifier:
def __init__(self):
self.coarse = Pipeline([
("tfidf", TfidfVectorizer(max_features=10000, ngram_range=(1, 2))),
("clf", LinearSVC(C=1.0, random_state=42)),
])
self.fine = {}
def fit(self, texts, coarse_labels, fine_labels):
self.coarse.fit(texts, coarse_labels)
for branch in set(coarse_labels):
mask = np.array([c == branch for c in coarse_labels])
fine_coarse = [f for f, m in zip(fine_labels, mask) if m]
if mask.sum() < 20 or len(set(fine_coarse)) < 2:
continue
pipe = Pipeline([
("tfidf", TfidfVectorizer(max_features=5000)),
("clf", LinearSVC(C=1.0, random_state=42)),
])
pipe.fit(np.array(texts)[mask], np.array(fine_labels)[mask])
self.fine[branch] = pipe
return self
def predict(self, texts):
coarse = self.coarse.predict(texts)
fine = []
for t, c in zip(texts, coarse):
fine.append(self.fine[c].predict([t])[0] if c in self.fine else c)
return coarse, fine
A practical refinement is a confident-routing rule: if the coarse classifier's decision margin is below a threshold, fall back to flat classification over the full leaf set â top-level mistakes otherwise cascade unrecoverably.
Evaluation, calibration, and serving
Accuracy alone conceals the decisions that matter. Track macro F1 (protects rare classes), per-class recall (the metric for safety-critical misses), and calibration (whether a 0.9 confidence means 90% correctness). A well-calibrated model with a 0.8 threshold enables safe auto-acceptance of high-confidence predictions with human review for the rest â the highest-leverage deployment pattern in text classification.
For serving, quantify the real cost: BERT-base inference on CPU runs tens of milliseconds per document; DistilBERT cuts that roughly in half with a small accuracy trade; ONNX quantization to int8 can halve latency again. Batch scoring jobs rarely need any of this â SVM on sparse TF-IDF is usually faster than GPU transfer time.
| Model | Typical latency (CPU) | Labels needed | Interpretability | Best fit |
|---|---|---|---|---|
| TF-IDF + LinearSVC | Under 1 ms | 1k+ | High (feature weights) | Strong default baseline |
| fastText | Under 1 ms | 1k+ | Medium (embeddings) | Multilingual, high throughput |
| DistilBERT fine-tune | 10â30 ms | 5k+ | Low (attributions) | Latency-sensitive neural |
| BERT fine-tune | 30â100 ms | 10k+ | Low | Maximum accuracy |
A deployment pattern that fits almost every label budget is a confidence-routed cascade: run the cheap linear or fastText model first, auto-accept predictions above a calibrated high-confidence threshold (say 0.95 precision at coverage 60%), and escalate only the uncertain remainder to the expensive transformer. This typically cuts GPU spend dramatically while preserving quality on the hard slice where it matters. Version the label schema alongside the model â a taxonomy change is a breaking change just like an API change, and silent label drift is one of the most common post-launch failures in classification systems. When the label space itself evolves (new product categories, renamed classes), plan a migration window where both the old and new models run in parallel against a sampled slice, so you can measure the transition before cutting over completely.
Common Mistakes
Fine-tuning BERT before establishing a TF-IDF baseline
Fix: Always train the linear baseline first; it calibrates expectations and surfaces leakage features the neural model would hide.
Using 0.5 as the decision threshold for multi-label predictions
Fix: Tune thresholds per label (or globally) on a validation set against micro-F1 or precision-at-k; the optimal value is rarely 0.5 with imbalanced labels.
Oversampling minority classes before the train/test split
Fix: Split first, then oversample only the training fold; otherwise duplicate examples leak and inflate evaluation scores.
Reporting micro-F1 alone on a long-tailed label set
Fix: Report macro F1 and per-class recall together; micro metrics are dominated by frequent classes and hide failure on rare ones.
Best Practices
- TF-IDF + LinearSVC is the default first model; graduate to fastText for speed at scale, BERT for accuracy on complex semantics
- Use sublinear TF and bigrams in the vectorizer â they recover most of the cheap performance
- Fine-tune with 2e-5, warmup, gradient clipping, and class weights; freeze layers under 1k examples per class
- Tune multi-label thresholds on validation data and consider classifier chains when labels correlate
- Calibrate probabilities (isotonic or Platt scaling) before setting auto-accept thresholds in production
Interview Questions
Q1: When would you choose fastText over BERT?
High-throughput, latency-sensitive scoring on short texts, multilingual corpora benefiting from subwords, or GPU-free environments. fastText often comes within a point or two of BERT at a fraction of the serving cost.
Q2: How do you handle 100:1 class imbalance in text classification?
Class-weighted loss or balanced logistic regression, macro-F1 as the selection metric, careful oversampling after splitting, and possibly threshold tuning per class. Collect more minority examples when feasible â no trick fully replaces data.
Q3: What is the failure mode of flat multi-class classification on a hierarchical taxonomy?
It allows structurally impossible predictions and wastes shared structure across siblings; hierarchical or coarse-to-fine models improve interpretability and often accuracy, with the risk of error cascades if top-level routing fails.
Key Takeaways
- A TF-IDF + linear SVM baseline defines the accuracy bar and exposes data issues; start there every time
- fastText bridges linear models and transformers when you need speed at scale
- BERT fine-tuning wins on semantic tasks but demands 2e-5 learning rates, warmup, and enough data per class
- Multi-label work is threshold-tuning work: default 0.5 thresholds systematically under-predict rare labels
- Hierarchical taxonomies benefit from coarse-to-fine routing with confident fallbacks, evaluated per branch