Text Classification
Prerequisites
- !Train/test splitting and leakage
- !Precision, recall and ROC curves
- !Python and scikit-learn pipelines
What You'll Learn
- 1Design a label taxonomy that annotators can apply consistently
- 2Build and measure a TF-IDF baseline before spending on GPU time
- 3Fine-tune a transformer with early stopping and honest validation splits
- 4Tune decision thresholds with an abstain option and monitor drift after launch
Start with the label set, not the model
Most classification projects that fail do so before a single epoch runs: the labels were ambiguous, overlapping, or defined at a granularity nobody can apply consistently. Three questions settle the design. Is this multi-class (exactly one label) or multi-label (any subset)? Is the taxonomy mutually exclusive, and if not, what happens when two labels both apply? And crucially, what should the system do with text it was never meant to handle?
That last question creates the label everyone forgets: out of scope. Support tickets contain password resets, sales enquiries, and jokes. A classifier forced to choose among your twelve real classes will confidently route a job application to the billing queue. Reserve an explicit reject option, and measure how often it fires.
Before annotating a single example, write a two-page guideline with positive and near-miss examples for each class, then double-annotate a sample of 200 documents. Cohen's kappa between your annotators tells you the ceiling: at 0.55 agreement the label set is not yet a problem a model can solve, because humans do not agree on the answer. Fix the guideline, not the architecture.
| Design choice | Use when | Watch out for |
|---|---|---|
| Multi-class softmax | Exactly one outcome, all text in scope | Overconfidence on out-of-scope input |
| Multi-label sigmoid | Independent tags, e.g. topics on a post | Thresholds must be tuned per label |
| Hierarchical labels | Coarse routing plus fine detail | Coarse errors cascade downward |
| Ordinal classes | Severity or priority has a natural order | Accuracy ignores near-miss cost |
| Reject option | Production traffic is never fully in scope | Reject rate becomes its own SLA |
The baseline you must beat
Every expensive model earns its place by beating a linear model on the same split. On short, keyword-driven text â support tickets, spam, intent detection â TF-IDF with logistic regression is frequently within a point of a fine-tuned transformer at a thousandth of the cost, and it trains on a laptop in seconds.
| Approach | Typical F1 on short text | Train cost | Inference cost | Latency |
|---|---|---|---|---|
| Keyword rules | 0.55â0.70 | Hours of analyst time | Negligible | Sub-millisecond |
| TF-IDF + logistic regression | 0.82â0.90 | Minutes on CPU | Microseconds | ~1 ms |
| Frozen embeddings + linear head | 0.85â0.92 | Minutes on CPU | Embedding call | 20â80 ms |
| Fine-tuned transformer | 0.88â0.94 | GPU-hours | Full forward pass | 10â50 ms |
| LLM prompting with examples | 0.86â0.93 | Prompt iteration | Token generation | 500â3000 ms |
Run the baseline first for a second reason beyond cost: it establishes what the data supports. If logistic regression plateaus at 0.83 and a transformer reaches 0.84, the bottleneck is label quality or missing context, and more parameters will not rescue it.
A TF-IDF baseline with an honest split
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.calibration import CalibratedClassifierCV
def build_baseline(texts, labels, test_size=0.2, seed=42):
# Stratify, and split BEFORE fitting the vectorizer: vocabulary is fitted
# on training data only, or the IDF weights leak test statistics.
X_tr, X_te, y_tr, y_te = train_test_split(
texts, labels, test_size=test_size, random_state=seed, stratify=labels
)
pipe = Pipeline([
("tfidf", TfidfVectorizer(
ngram_range=(1, 2), min_df=2, max_features=50_000,
sublinear_tf=True, strip_accents="unicode",
)),
("clf", CalibratedClassifierCV(
LogisticRegression(max_iter=1000, class_weight="balanced")
)),
])
pipe.fit(X_tr, y_tr)
proba = pipe.predict_proba(X_te)
print(classification_report(y_te, pipe.predict(X_te), digits=3))
return pipe, X_te, y_te, proba
class_weight="balanced" matters when tickets arrive twenty-to-one in favour of the common class; without it the model learns to answer "general question" for everything and still reports respectable accuracy. Calibration matters because the next section turns raw probabilities into decisions, and uncalibrated scores make that turning point meaningless.
Thresholds, abstention and the reject option
Default argmax is a threshold of 0.5 applied without thought. Production systems tune it: raise the bar until precision meets the cost of a wrong action, and let the remainder fall into an abstain bucket that a slower path â a human, an LLM with retrieval, a fallback queue â handles.
def tune_threshold(proba, y_true, target_precision=0.95):
"""Per-class threshold sweep with an explicit abstain zone."""
classes = np.arange(proba.shape[1])
best = {}
for c in classes:
pos = (y_true == c).astype(int)
thresholds = np.linspace(0.05, 0.95, 91)
chosen, best_f1 = 0.5, -1.0
for t in thresholds:
pred = (proba[:, c] >= t).astype(int)
tp = int(((pred == 1) & (pos == 1)).sum())
fp = int(((pred == 1) & (pos == 0)).sum())
fn = int(((pred == 0) & (pos == 1)).sum())
precision = tp / (tp + fp) if tp + fp else 0.0
recall = tp / (tp + fn) if tp + fn else 0.0
f1 = (2 * precision * recall / (precision + recall)
if precision + recall else 0.0)
if precision >= target_precision and f1 > best_f1:
chosen, best_f1 = t, f1
best[int(c)] = chosen
return best
def decide(proba_row, thresholds):
"""Return a label, or None when every class sits below its bar."""
for c, t in thresholds.items():
if proba_row[c] >= t:
return int(c)
return None # abstain: route to review
Set the target precision from the cost of being wrong. Misclassifying a refund request as a compliment is cheap; routing a medical complaint to marketing is not. The abstain rate is a metric you publish â if it climbs from 4% to 12% over a week, something changed upstream even if accuracy on scored traffic looks stable.
Fine-tuning when the baseline leaves room
When the transformer has genuine headroom, fine-tune with the discipline that keeps results reproducible: a fixed seed, an early-stopping metric you actually care about, and a validation split drawn from the same time window as training so you are not measuring temporal drift as generalization.
from transformers import (AutoModelForSequenceClassification, AutoTokenizer,
Trainer, TrainingArguments)
from datasets import Dataset
def fine_tune(model_name, train_texts, train_labels, val_texts, val_labels,
epochs=3, batch_size=16, lr=2e-5):
tok = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForSequenceClassification.from_pretrained(
model_name, num_labels=len(set(train_labels)), id2label=None
)
def enc(texts, labels):
encodings = tok(texts, truncation=True, padding=True, max_length=256)
return Dataset.from_dict({**encodings, "labels": labels})
args = TrainingArguments(
output_dir="./clf-run",
num_train_epochs=epochs,
per_device_train_batch_size=batch_size,
learning_rate=lr,
eval_strategy="epoch",
save_strategy="epoch",
load_best_model_at_end=True,
metric_for_best_model="f1",
weight_decay=0.01,
seed=42,
)
trainer = Trainer(model=model, args=args,
train_dataset=enc(train_texts, train_labels),
eval_dataset=enc(val_texts, val_labels))
trainer.train()
return trainer.model, tok
Learning rates above 5e-5 on small datasets typically destroy the pretrained representation within one epoch; weight decay and early stopping are cheaper than a larger model. If the transformer beats the linear baseline by less than a point after a genuine tuning effort, ship the linear model and spend the saved GPU budget on better labels.
Spending the annotation budget well
Labels are usually the scarce resource, so how you pick the next batch matters more than the model that consumes it. Random sampling wastes budget on obvious cases the model already handles. The efficient loop is active learning: score the unlabeled pool, label the examples the model is most uncertain about or most disagrees with itself on, retrain, and repeat. Uncertainty sampling alone has a known failure â it over-selects mislabeled outliers â so mix in diversity sampling, which clusters embeddings and labels one representative per cluster, and a random slice that keeps the distribution honest.
Set a stopping rule before you start, not after the invoice arrives. Track the validation F1 gained per hundred new labels; when a batch of 500 examples buys you 0.003, the remaining errors are ambiguity or missing context rather than missing supervision. At that point, adding a field to the input text â the previous ticket in a thread, the device type, the page the user was on â reliably beats another thousand hand-labelled rows, because the information simply was not in the document the model was shown.
Error analysis in four buckets
Take fifty misclassified examples and sort them by hand into four piles: annotation errors (the gold label is wrong), ambiguous (two labels genuinely apply), out of scope (belongs in reject), and model misses (clear case, wrong answer). In most projects the first two piles are larger than the last, which tells you where the next week of work goes. Only the fourth pile responds to architecture.
Pattern matters as much as count. Misses clustered on one label suggest a definition problem or too few examples; misses on short messages suggest missing context rather than missing capacity; misses that appear only after a product change are drift, not error. Record the bucket for each sampled miss and review the distribution every sprint â it converts "accuracy dropped" from a rumour into a diagnosis.
Monitoring after launch
Production classifiers decay quietly. Track input drift with a simple Jensen-Shannon divergence on the TF-IDF distribution or embedding centroid against the training set, alert on a sharp rise in the abstain rate, and re-score a small hand-labelled sample weekly so you measure the number that matters instead of its proxy. Keep the baseline pipeline beside the transformer: when quality slips, re-fitting the linear model on fresh labels is a same-day fix, while a transformer retrain is a scheduled project.
Common Mistakes
Fitting the vectorizer before splitting the data
Fix: Split first, then fit; vocabulary and IDF statistics must come from training data only
Letting argmax make every decision at confidence 0.34
Fix: Tune per-class thresholds and route everything below the bar to an abstain path
Reporting accuracy on a heavily imbalanced label set
Fix: Report per-class precision and recall, and publish the abstain rate alongside them
Jumping to a transformer without a measured baseline
Fix: Ship a TF-IDF logistic baseline first and let the gap justify GPU spend
Best Practices
- Write the annotation guideline and measure inter-annotator agreement before training anything
- Reserve an explicit out-of-scope label so the model is allowed to say no
- Use stratified, time-aware splits and keep a frozen test set untouched until release
- Keep a cheap linear model deployed as the rollback path for every expensive model
- Re-label a small sample weekly and track the four error buckets, not just aggregate accuracy
Key Takeaways
- Label design sets the ceiling: measure annotator agreement before training, and reserve an explicit reject class
- A TF-IDF baseline is cheap, fast, and often nearly as good â the gap it leaves is what justifies a transformer
- Calibrate probabilities and tune thresholds per class against the real cost of a wrong action
- Abstain rate is a leading indicator: it moves before accuracy does when the data changes
- Sort misclassifications into annotation, ambiguity, scope and model buckets â only the last one is fixed by architecture