🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Text Classification with Naive Bayes and SVM

Text ClassificationClassification MethodsđŸŸĸ Free Lesson

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.

ModelTraining costProbabilitiesInterpretabilityTypical sweet spot
Multinomial Naive BayesOne passPoorly calibratedHigh, via log countsTiny data, topic tagging
Logistic regressionIterative, fastNaturally calibratedHigh, per-feature weightsGeneral purpose baseline
Linear SVMIterative, fastNeeds Platt scalingMedium, via support vectorsNoisy labels, many features
SGD classifierSingle pass, streamingApproximateHighCorpora too large to fit in memory
Gradient boosting on featuresModerateGoodMediumStructured side features mixed in
Fine-tuned transformerVery slow, GPUReasonable after calibrationLowLarge 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.

python
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.

python
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.

python
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

StepWhat to doWhy it matters
SplitHold out a test set once, never touched during tuningPrevents selection bias on the final number
StratifyPreserve class ratios across splitsKeeps rare classes present in every fold
Vectorize inside the pipelineFit on train folds onlyStops vocabulary and IDF leakage
Select metric firstMacro F1 for imbalance, accuracy only for balanceStops metric shopping after seeing results
Compare against baselinesMajority class and a simple keyword ruleProves the model adds value
Report the confusion matrixShow which classes collideReveals systematic label overlap
Error-sample manuallyRead twenty false positivesCatches annotation bugs no metric sees

💡The cheapest sanity check in the field

Always score the majority-class baseline beside your model. If the model beats a trivial predictor by three points, the problem may be the labels rather than the algorithm, and no hyperparameter search will fix a dataset whose classes genuinely overlap.

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
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-13

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert NLP Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement