Skip to main content

Classification Models

Docs: Linear models · Ensembles · SVM · Nearest neighbours · Naive Bayes · Classification metrics · Probability calibration

Overview​

Use classification when the target is a category: fails or runs, fraud or legit, which product a customer buys. The right model depends on how complex the boundary between classes is, so start with logistic regression and move on only when it falls short. The failure people hit on real, imbalanced data is reporting accuracy: on the machine-failure problem, predicting "nothing fails" scores 97% accuracy and catches zero breakdowns.

Key concepts​

Cheatsheet​

ModelReach for it whenAvoid whenScaling?Key knobs#1 failure mode
Logistic RegressionDefault first model; need calibrated probabilitiesBoundary is clearly non-linearYesC, class_weightTrusting the 0.5 threshold
Decision TreeHumans must audit the rulesAccuracy is the goalNomax_depthUnconstrained depth → memorisation
Random ForestStrong baseline, mixed features, no tuning budgetNeed calibrated probabilities out of the boxNon_estimators, class_weightTrusting biased feature_importances_
Gradient BoostingBest tabular accuracyTiny data, no tuning timeNolearning_rate, max_depth, scale_pos_weightNo early stopping
SVMHigh-dim sparse features (text)More than ~50k rowsYes (critical)C, kernel, gammaUnscaled features
KNNSmall data, "similar → same class" holdsHigh dimensions, large data, latency mattersYeskIrrelevant features poisoning distances
Naive BayesText, small data, need it nowYou need calibrated probabilitiesNoalphaTrusting the raw probability output
MLPLarge data, boosting has plateauedSmall data, need interpretabilityYeslayers, early_stoppingUnscaled inputs → won't converge

Running example: machine failure​

Every model is applied to one problem: predict which machines will have an unplanned breakdown in the next 30 days from vibration, temperature, load cycles, service history and work orders. 10,000 machines, ~300 failures per window: a 3% positive class. The metric is PR-AUC, never accuracy. Numbers show the typical pattern, not one specific run.

ModelROC-AUCPR-AUCNotes
Predict "no failure" always0.500.03❌ 97% accuracy. Useless
Logistic Regression0.790.31Two minutes; coefficients explain why machines fail
Decision Tree (depth 4)0.750.26Weakest, but the maintenance crew can read it
Random Forest0.840.40Big jump: failure drivers interact
XGBoost (tuned)0.870.46Best; needed scale_pos_weight and early stopping
SVM (RBF)0.800.33Slowest to train; its home is text
KNN (k = 15)0.770.2850 ms per prediction at serving time
Naive Bayes0.720.22Sensors aren't independent; its home is also text
MLP (2 layers)0.850.42Close to XGBoost, needed the most babysitting

Linear gets you most of the way instantly; tuned boosting wins. SVM and Naive Bayes underperform because sensor data isn't their turf.

Evaluation metrics​

MetricIn plain wordsUse when
PrecisionOf the machines flagged, the share that really failedFalse alarms are expensive
RecallOf the machines that failed, the share flaggedMisses are expensive
F1One number balancing precision and recallYou must report a single number
ROC-AUCHow well the model ranks positives above negatives, over all thresholdsComparing models on balanced data
PR-AUCPrecision across all recall levelsRare positive class. ROC-AUC flatters bad models here

The threshold is a business decision. The tuned XGBoost on a 2,000-machine test set with 60 real breakdowns:

ThresholdFlaggedCaught (TP)False alarms (FP)Missed (FN)PrecisionRecall
0.50 (default)403010300.750.50
0.2515048102120.320.80

An inspection costs $500; an unplanned breakdown costs $50,000. Lowering the threshold adds 110 inspections ($55k) and prevents 18 more breakdowns ($900k). The model produces scores; the cost ratio picks the operating point.

Handling class imbalance​

A model that ignores imbalance is confidently wrong on the class that matters.

TechniqueUse whenResult
class_weight="balanced" / scale_pos_weight (≈ 32 here)First thing to try; built into most models✅ Cheap, no new data
Threshold tuningAlways, after training✅ Matches the operating point to the cost ratio
PR-AUC as the metricAlways, when positives are rare✅ Honest ranking of models
SMOTE (synthetic oversampling)Minority class is tiny⚠️ Inside the CV fold only, or it leaks
Undersampling the majorityMajority class is huge⚠️ Faster training, throws data away
Accuracy as the metric—❌ 97% for a model that catches nothing

Linear vs non-linear​

Linear classifiersNon-linear classifiers
ExamplesLogistic Regression, Linear SVM, Naive Bayes (approx.)Trees, Random Forest, Gradient Boosting, KNN, MLP
BoundaryStraight hyperplaneArbitrary shape
InterpretabilityCoefficients readableBlack box (shallow trees excepted)
Scaling requiredYesNot for trees
ProbabilitiesCalibrated (logistic regression)Need a calibration wrapper

Go non-linear when the linear model plateaus and the boundary depends on interactions. Here, rising vibration predicts failure only when temperature is also climbing.

Choosing a model​

Figure M2-1: Classification model selection. Amber is the starting point for every classification problem.

Logistic regression​

A linear model pushed through a sigmoid. The only model here whose probabilities are calibrated out of the box.

0.501Linear score (w·X + b)P(y = 1)Class 0Class 1threshold

Figure M2-2: The sigmoid turns a linear score into a probability. Green is the curve, amber marks the default 0.5 threshold, which is almost never the right one.

Use whenAlways first. Also when you need honest probabilities for threshold maths
Get it rightScale features: L2 penalises all weights equally. Add class_weight="balanced" before anything more complex. Tune the threshold on validation, using predict_proba scores
On the plant dataROC-AUC 0.79 in two minutes. Rising vibration trend is the strongest failure signal, a recent service the strongest protective one. That's the answer when a planner asks "why was this machine flagged?"

Decision tree classifier​

The model is the documentation, and it should almost never be the final model.

Figure M2-3: The depth-3 tree that became the crew's walk-down checklist. Amber is the leaf that sends a technician.

Use whenA compliance team, regulator or domain expert must verify the logic
Get it rightmax_depth 3–5. No scaling. Use it to understand the data, then move to an ensemble
On the plant dataAUC 0.75, the weakest. But the printed rules became the walk-down checklist, worth more to the business than the 0.12 AUC that tuned XGBoost added

Random forest classifier​

Hundreds of overfit trees and a majority vote. → See bagging vs boosting.

Use whenYou need a strong non-linear baseline fast
Get it rightStart at 100–300 trees with oob_score=True for a free validation estimate. Set class_weight="balanced" first. Built-in feature_importances_ favour high-cardinality features: use permutation importance. Probabilities cluster mid-range: wrap in CalibratedClassifierCV for threshold maths
On the plant dataAUC 0.79 → 0.84 with no tuning: failure drivers interact

Gradient boosting classifiers​

Each tree trains on the previous ensemble's mistakes. Early stopping is non-negotiable. → See bagging vs boosting.

LibraryReach for it when
XGBoostGeneral purpose, strong regularisation
LightGBM100k+ rows, need speed (is_unbalance=True for imbalance)
CatBoostMany categorical features, minimal preprocessing

The settings for the failure model live in hyperparameter search. On the plant data: AUC 0.87, PR-AUC 0.46, with early stopping picking ~700 rounds. Without scale_pos_weight the first run barely beat the forest. The PR-AUC gap over logistic regression is ~18 more breakdowns caught per 2,000 machines at the same precision, about $900k.

Support vector machine (SVM)​

Only the support vectors, the points at the margin, define the boundary. The kernel trick draws non-linear boundaries without you building the features.

marginsupportvectors

Figure M2-4: The maximum-margin boundary. Blue and orange are the two classes, the green line is the boundary, dashed lines are the margin, and circled points are the support vectors.

Use whenHigh-dimensional sparse features. TF-IDF text is the canonical case; LinearSVC is fast there
Get it rightStandardise features. Training cost grows with the square of the rows or worse: impractical above ~50k. Tune C over 0.01–100, and gamma for RBF
On the plant dataAUC 0.80, slowest to train. Where it wins: classifying failure modes from technicians' work-order text, 30,000 sparse dimensions where trees choke

K-nearest neighbours (KNN)​

There is no model. The training set is the model, and all cost is paid at prediction time.

?▲ query · 3 nearest: 2 orange, 1 blue → orange

Figure M2-5: KNN with k = 3. The amber triangle is the machine to classify; the dashed circle holds its three nearest neighbours, and the majority (orange) wins.

Use whenSmall data where "similar input → same class" is true, or where "find similar cases" is itself the product
Get it rightScale features: one unscaled column dominates every distance. Drop irrelevant features. Odd k for binary problems, tuned with CV. Prediction compares against every training row
On the plant dataAUC 0.77. Machine age in days dominated every distance until scaling. Its real niche: pulling comparable historical breakdowns for a technician

Naive Bayes​

Assumes every feature is independent given the class. Almost always false. Works on text anyway.

VariantAssumesBest for
GaussianNBContinuous, bell-shaped featuresNumeric features
MultinomialNBCountsWord counts, TF-IDF
BernoulliNBBinary featuresWord presence

Keep alpha above 0 (default 1.0) so unseen words don't zero a probability. Raw probabilities are not calibrated. On the plant data it scores AUC 0.72, the worst real model, because vibration, temperature and load are strongly correlated. On work-order text it trains in milliseconds and flags bearing problems at 90%+.

Neural network (MLP) classifier​

A universal approximator that boosting still usually beats on tabular data. Earn it, don't start with it.

Use when50k+ rows and boosting has plateaued, or you'll extend to deep learning later
Get it rightScale all features. One hidden layer of 64–128 ReLU units with Adam to start. early_stopping=True. Move to PyTorch for GPUs or custom architectures, not just for more layers
On the plant dataAUC 0.85, between the forest and XGBoost, after two convergence failures. It wins with scale or unstructured inputs: 500k machines, or raw vibration waveforms

Gotchas​

  • Reporting accuracy on imbalanced data. A do-nothing model scores 97%. Report PR-AUC and the confusion matrix.
  • Keeping the 0.5 threshold. It ignores what a miss and a false alarm cost. Pick the threshold from the cost ratio.
  • Unscaled features for logistic regression, SVM, KNN or MLP. The largest units dominate. Scale inside the pipeline.
  • Oversampling before the split. Synthetic rows leak into validation. Resample inside each training fold only.
  • Trusting tree or Naive Bayes probabilities. They're not calibrated. Wrap with CalibratedClassifierCV before threshold maths.

Scenario questions​

Q1 ★ Your failure model is 97% accurate. Is that good?

Model answer
  • Clarify: what's the base rate of failures?
  • Observe: 3%. Predicting "no failure" for every machine also scores 97%.
  • Hypothesise: accuracy is dominated by the majority class and says nothing about catching failures.
  • Fix: report PR-AUC (0.46 for tuned XGBoost against 0.03 for the do-nothing model) and precision and recall at the chosen threshold.
  • Prevent: agree the metric before modelling. The trade-off is a less familiar number for stakeholders.

Q2 ★★ How do you choose the decision threshold?

Model answer
  • Clarify: what does an inspection cost, and what does a missed breakdown cost?
  • Observe: $500 vs $50,000. At 0.5 the model catches 30 of 60 breakdowns; at 0.25 it catches 48, with 110 more inspections.
  • Hypothesise: with a 100:1 cost ratio, recall is worth a lot of false alarms.
  • Fix: pick 0.25: $55k of extra inspections prevents ~$900k of downtime. Check the inspection budget can absorb 150 flags.
  • Prevent: the threshold is reviewed with the business whenever costs or capacity change. The trade-off is many inspections that find nothing.

Q3 ★★ Logistic regression scores 0.79 AUC, Random Forest 0.84. What does the gap tell you?

Model answer
  • Clarify: same features, same split?
  • Observe: the forest's gain comes mostly from vibration and temperature together.
  • Hypothesise: failure drivers interact. Rising vibration matters only when temperature also climbs, which a linear model can't express without an explicit interaction term.
  • Fix: move to tree ensembles, or add the interaction term if the linear model's explainability matters.
  • Prevent: compare linear and forest baselines on every new problem. The trade-off is less readable coefficients.

Q4 ★★★ The plant wants to classify failure modes from technicians' free-text notes. Which model?

Model answer
  • Clarify: how many labelled notes, how many classes, and how fast is it needed?
  • Observe: a few thousand notes; TF-IDF gives ~30,000 sparse dimensions.
  • Hypothesise: tree ensembles struggle on sparse text. Linear SVM and Naive Bayes are built for it.
  • Fix: Naive Bayes as a same-day baseline, then LinearSVC on TF-IDF. A transformer only if they plateau and there's enough data.
  • Prevent: match the model family to the data shape before tuning. The trade-off is uncalibrated scores that need calibration before threshold maths.

Summary​

  • Accuracy lies on imbalanced data. Report PR-AUC and the confusion matrix.
  • The threshold is a business decision. The cost ratio of misses to false alarms picks it, not 0.5.
  • Start with logistic regression. Calibrated probabilities and readable coefficients in two minutes.
  • Tuned boosting wins on tabular data. scale_pos_weight and early stopping, or it barely beats the forest.
  • Match the model to the data shape. SVM and Naive Bayes lose on sensors and win on text.

Next → Model Landscape