The classifier is the easy part
A text classification project is roughly ten percent modelling and ninety percent deciding what a label means, where the negatives come from, and how the evaluation is constructed. The algorithms below are all decades old, all linear, and all capable of strong results; choosing between them is rarely the decision that determines whether the system works. What determines it is whether the training set resembles the traffic the model will see, whether positives were sampled without accidentally leaking the answer, and whether the metric reported is the one the business actually cares about.
With that framing, the three classical candidates are still worth knowing precisely, because they fail in different, predictable ways. Naive Bayes is a generative baseline that trains in one pass and is hard to beat on tiny data. Logistic regression gives calibrated probabilities and interpretable coefficients. Support vector machines maximise the margin, which in very high dimensions tends to generalise better when labels are noisy. All three operate on the same sparse TF-IDF matrix, so swapping them is a one-line change and comparing them honestly costs minutes.
Why text favours linear models
Raw text produces tens of thousands of features from a few hundred documents, and the ratio is inverted compared to tabular problems: features far outnumber samples. Deep networks thrive when samples dominate features, and they overfit badly in the opposite regime. Linear models have the opposite profile â their capacity is controlled by a single regularisation parameter, they train on sparse input without densifying it, and their weights can be read directly as evidence for and against a class.
| Model | Training cost | Probabilities | Interpretability | Typical sweet spot |
|---|---|---|---|---|
| Multinomial Naive Bayes | One pass | Poorly calibrated | High, via log counts | Tiny data, topic tagging |
| Logistic regression | Iterative, fast | Naturally calibrated | High, per-feature weights | General purpose baseline |
| Linear SVM | Iterative, fast | Needs Platt scaling | Medium, via support vectors | Noisy labels, many features |
| SGD classifier | Single pass, streaming | Approximate | High | Corpora too large to fit in memory |
| Gradient boosting on features | Moderate | Good | Medium | Structured side features mixed in |
| Fine-tuned transformer | Very slow, GPU | Reasonable after calibration | Low | Large label sets, nuance required |
Naive Bayes as the fast baseline
Multinomial Naive Bayes models each document as a draw from a per-class word distribution. The independence assumption is obviously false â New and York are not independent â and the classifier works anyway, because it only needs the argmax over classes to be right, not the probabilities to be true.
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.pipeline import Pipeline
from sklearn.model_selection import cross_val_predict
from sklearn.metrics import classification_report, confusion_matrix
docs = [
"win a free iphone click here now", "claim your cash prize today",
"limited time offer act fast", "cheap meds without prescription",
"agenda for monday standup", "quarterly report attached for review",
"budget approved for next quarter", "meeting notes from tuesday",
"project deadline moved to friday", "server migration window tonight",
]
labels = [1, 1, 1, 1, 0, 0, 0, 0, 0, 0] # 1 = spam
nb = Pipeline([
("vec", CountVectorizer(ngram_range=(1, 2), min_df=1)),
("clf", MultinomialNB(alpha=0.5)),
])
proba = cross_val_predict(nb, docs, labels, cv=3, method="predict_proba")
preds = proba[:, 1] >= 0.5
print(classification_report(labels, preds, digits=2))
print(confusion_matrix(labels, preds))
The alpha parameter is Laplace smoothing on the class-conditional counts. Raising it shrinks the effect of any single rare word, which helps when the training set is small and hurts when a rare token is genuinely the strongest signal â a domain-specific drug name, for instance.
SVM versus logistic regression
Both optimise a linear decision boundary over the same features, and the practical difference is the loss: hinge loss for the SVM cares only about points near or inside the margin, while logistic loss keeps pushing on every point proportional to its confidence. With clean labels the two converge; with noisy or mislabelled examples the SVM's indifference to far-away points usually generalises better.
from sklearn.svm import LinearSVC
from sklearn.linear_model import LogisticRegression
from sklearn.calibration import CalibratedClassifierCV
from sklearn.model_selection import GridSearchCV
def build(name):
if name == "svm":
clf = LinearSVC(class_weight="balanced", max_iter=5000)
else:
clf = LogisticRegression(class_weight="balanced", max_iter=2000)
return Pipeline([("vec", TfidfVectorizer(sublinear_tf=True, min_df=2)),
("clf", clf)])
param_grid = {"vec__ngram_range": [(1, 1), (1, 2)],
"clf__C": [0.5, 1.0, 4.0]}
for name in ("svm", "lr"):
search = GridSearchCV(build(name), param_grid, cv=3, scoring="f1_macro")
search.fit(docs, labels)
print(name, "best f1:", round(search.best_score_, 3), search.best_params_)
calibrated = CalibratedClassifierCV(build("svm"), cv=3)
calibrated.fit(docs, labels)
print("calibrated P:", [round(p, 2) for p in calibrated.predict_proba([docs[0]])[0]])
When you need probabilities from an SVM â for a threshold you plan to tune, or for a downstream stacking model â wrap it in CalibratedClassifierCV. Reading the raw decision_function as though it were a probability is one of the most common mistakes in production scoring code.
Handling multiclass and imbalance
Text problems are usually multiclass, and most linear models handle that natively through one-versus-rest. Imbalance is a separate issue that no class mode fixes: if complaints are 3 percent of tickets, the model must be told, via class_weight="balanced", or via resampling, that a false negative costs more than a false positive.
from sklearn.datasets import fetch_20newsgroups
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import SGDClassifier
from sklearn.metrics import f1_score
import numpy as np
cats = ["sci.space", "rec.sport.baseball", "comp.graphics", "talk.politics.guns"]
train = fetch_20newsgroups(subset="train", categories=cats)
test = fetch_20newsgroups(subset="test", categories=cats)
vec = TfidfVectorizer(stop_words="english", sublinear_tf=True, max_features=30000)
Xtr, Xte = vec.fit_transform(train.data), vec.transform(test.data)
clf = SGDClassifier(loss="log_loss", class_weight="balanced", random_state=0)
clf.fit(Xtr, train.target)
pred = clf.predict(Xte)
print("macro f1:", round(f1_score(test.target, pred, average="macro"), 3))
# per-class thresholds tuned on a validation split
proba = clf.predict_proba(Xte)
thresholds = {}
for c in range(len(clf.classes_)):
best, best_t = 0.0, 0.5
for t in np.arange(0.2, 0.8, 0.05):
p = np.where(proba[:, c] >= t, c, -1)
f = f1_score(test.target, np.where(p == -1, pred, p), average="macro")
if f > best:
best, best_t = f, t
thresholds[c] = round(best_t, 2)
print("per-class thresholds:", thresholds)
Note the ordering hazard: the vectorizer is fitted on training data and only transform is called on test data. Fitting on the concatenation of both leaks vocabulary and IDF statistics, and inflates scores by one to three points on typical benchmarks â enough to make a weak model look respectable.
What actually moves the score
Once the leakage bugs are gone, the remaining levers are ordered in a way that surprises people who start with hyperparameters. The largest single gain usually comes from deciding what counts as a positive example â a label set assembled from inconsistent sources will cap every downstream model regardless of architecture. Second comes the feature span: adding bigrams to short texts is routinely worth several points of macro F1, because phrases like not working or no signal carry the class signal and their unigrams actively mislead. Third comes class weighting and threshold tuning, which do not improve the model at all but realign its decision rule with the cost you actually incur. Only after those does the choice between SVM, logistic regression, and a gradient-boosted variant contribute a fraction of a point, and only after all of them does architecture matter. A useful discipline is to record each change with its measured delta in a short notebook: when the numbers are written down, it becomes obvious which lever you are pulling and which ones you have merely assumed are effective.
An evaluation protocol that survives review
| Step | What to do | Why it matters |
|---|---|---|
| Split | Hold out a test set once, never touched during tuning | Prevents selection bias on the final number |
| Stratify | Preserve class ratios across splits | Keeps rare classes present in every fold |
| Vectorize inside the pipeline | Fit on train folds only | Stops vocabulary and IDF leakage |
| Select metric first | Macro F1 for imbalance, accuracy only for balance | Stops metric shopping after seeing results |
| Compare against baselines | Majority class and a simple keyword rule | Proves the model adds value |
| Report the confusion matrix | Show which classes collide | Reveals systematic label overlap |
| Error-sample manually | Read twenty false positives | Catches annotation bugs no metric sees |
đĄThe cheapest sanity check in the field
Common Mistakes
Fitting the vectorizer on the full dataset before splitting
Fix: Put it in a Pipeline so fit only ever sees training folds.
Reading an SVM decision function as a probability
Fix: Wrap with CalibratedClassifierCV, or apply Platt scaling on a held-out split.
Optimising accuracy on a 3 percent positive class
Fix: Choose macro F1 or recall at a fixed precision before the first training run.
Tuning and evaluating on the same cross-validation folds repeatedly
Fix: Reserve an untouched test set for the final number and treat CV as development only.
Best Practices
- Establish the majority-class and keyword baselines before training anything
- Keep vectorizer and classifier in one pipeline so preprocessing is versioned with the model
- Use class_weight=balanced as the first response to imbalance, resampling only if that fails
- Publish macro F1, the confusion matrix, and the class distribution together on every evaluation
Interview Questions
Q1: Why do linear models often beat deep networks on small text datasets?
Text yields far more features than samples, and deep networks have enough capacity to memorise that regime, while a regularised linear model's single capacity parameter generalises far better.
Q2: How do you get probabilities from a linear SVM?
The raw decision function is unbounded and not a probability, so you calibrate with CalibratedClassifierCV, which fits a logistic or isotonic regression of the score against true labels on a held-out split.
Q3: What is the most common source of inflated reported accuracy in text classification?
Fitting the vectorizer before the train-test split, which leaks test vocabulary and IDF statistics into training and typically inflates scores by one to three points.
Key Takeaways
- Naive Bayes, logistic regression, and linear SVM are all strong, fast baselines on sparse text
- High feature-to-sample ratios favour linear models with regularisation over high-capacity networks
- Calibration is a separate step for SVMs; their decision scores are not probabilities
- Imbalance is addressed by class weighting and by choosing macro F1, not by changing the classifier
- Leakage from pre-split vectorizer fitting is the leading cause of overstated text classification results