Classical ML Algorithms
The workhorse algorithms beyond linear models — k-nearest neighbours, Naive Bayes, decision trees, random forests, gradient boosting (XGBoost, LightGBM), support vector machines, k-means clustering, PCA, and how to choose among them.
Deep learning gets the headlines, but for tabular data — rows and columns, as in most business problems — classical algorithms, especially gradient-boosted trees, usually win: they're accurate, fast to train, need less data and are easier to interpret.
k-nearest neighbours (kNN)
To classify a point, find the k closest training examples and take a majority vote (or average, for regression).
- No training phase ("lazy learning") — but prediction compares against all stored data: O(n·d) per query without an index (Approximate nearest neighbour search solves this at scale).
- Needs feature scaling and a meaningful distance metric.
- Small k → noisy, overfits; large k → over-smoothed.
- Suffers from the curse of dimensionality: in high dimensions, all points become roughly equidistant.
Naive Bayes
Applies Bayes' theorem with the "naive" assumption that features are independent given the class:
The assumption is usually false, yet it works surprisingly well for text classification (spam filtering, sentiment) with word counts. Extremely fast to train and predict; a strong baseline.
Decision trees
A tree of if/else questions on features, learned from data:
The algorithm (CART) greedily picks, at each node, the feature and threshold that best separates the classes, measured by Gini impurity or entropy (information gain) — or variance reduction for regression — then recurses.
| Pros | Cons |
|---|---|
| Interpretable — you can read the rules | A single deep tree overfits badly |
| No feature scaling needed; handles mixed types | Unstable: small data changes → a different tree |
| Captures non-linear relationships and interactions | Axis-aligned splits approximate diagonal boundaries poorly |
Control overfitting with max_depth, min_samples_leaf and pruning — or, much better, combine many trees.
Ensembles: random forests and boosting
Ensembles combine many weak models into a strong one.
Random forest (bagging)
Train hundreds of deep trees, each on a bootstrap sample of the rows (sampling with replacement) and considering a random subset of features at each split. Average their predictions (or vote). Averaging many decorrelated, high-variance trees dramatically reduces variance.
- Robust, hard to badly misconfigure, parallelisable.
- Out-of-bag error gives a free validation estimate.
- Provides feature importances.
Gradient boosting
Train trees sequentially: each new shallow tree fits the errors (residuals / negative gradients) of the ensemble so far, and its predictions are added with a small learning rate. Boosting reduces bias step by step.
import lightgbm as lgb
from sklearn.model_selection import train_test_split
X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2, stratify=y, random_state=0)
model = lgb.LGBMClassifier(n_estimators=2000, learning_rate=0.03, num_leaves=31,
subsample=0.8, colsample_bytree=0.8)
model.fit(X_train, y_train, eval_set=[(X_val, y_val)],
callbacks=[lgb.early_stopping(100)]) # stop when validation stops improvingXGBoost, LightGBM and CatBoost are highly optimised implementations; they dominate tabular-data competitions and power many production systems (fraud, ranking, pricing, churn). Key hyperparameters: number of trees + learning rate (with early stopping), tree depth/leaves, row and column subsampling, regularisation.
| Random forest | Gradient boosting | |
|---|---|---|
| Trees built | Independently, in parallel | Sequentially, each correcting the last |
| Tree depth | Deep | Shallow |
| Reduces | Variance | Bias (and variance with regularisation) |
| Tuning | Little | More sensitive, usually more accurate |
Support vector machines (SVM)
Find the decision boundary with the maximum margin — the widest gap between classes. Only the points nearest the boundary (support vectors) define it.
The kernel trick lets SVMs learn non-linear boundaries by implicitly mapping data into a higher-dimensional space (RBF, polynomial kernels) without computing that mapping. Strong on small-to-medium, high-dimensional datasets (text, bioinformatics); scales poorly beyond ~100k examples (training is roughly O(n²)–O(n³)).
Unsupervised: k-means clustering
Group unlabelled points into k clusters:
- Pick k initial centroids (k-means++ chooses spread-out starting points).
- Assign each point to its nearest centroid.
- Update each centroid to the mean of its assigned points.
- Repeat 2–3 until assignments stop changing.
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
X_scaled = StandardScaler().fit_transform(customers[["annual_spend", "visits", "basket_size"]])
km = KMeans(n_clusters=4, n_init="auto", random_state=0).fit(X_scaled)
customers["segment"] = km.labels_Choose k with the elbow method (inertia vs k) or silhouette score. k-means assumes roughly spherical, similar-sized clusters; DBSCAN finds arbitrarily shaped clusters and marks outliers; hierarchical clustering builds a tree of clusters; Gaussian mixture models give soft assignments.
Dimensionality reduction: PCA
Principal Component Analysis finds the orthogonal directions (principal components) along which the data varies most — the eigenvectors of the covariance matrix — and projects data onto the top few.
- Compress hundreds of correlated features into a few components retaining most of the variance.
- Visualise high-dimensional data in 2-D; denoise; speed up downstream models.
- Linear only; for visualising complex structure use t-SNE or UMAP.
Choosing an algorithm
| Situation | Start with |
|---|---|
| Tabular data, best accuracy | Gradient boosting (LightGBM, XGBoost, CatBoost) |
| Need interpretability / a baseline | Logistic or linear regression; a shallow decision tree |
| Robust model with little tuning | Random forest |
| Text classification baseline | TF-IDF + logistic regression or Naive Bayes |
| Small, high-dimensional data | SVM |
| Images, audio, raw text, huge datasets | Deep learning (Neural networks) |
| Find groups | k-means, DBSCAN |
| Reduce or visualise dimensions | PCA, UMAP |
| Anomaly detection | Isolation forest, one-class SVM, autoencoders |
No free lunch: no algorithm is best on every problem. Try a simple baseline, then a strong model, and compare with proper cross-validation (Model evaluation). Better features and data usually beat a fancier algorithm.
- kNN predicts from nearest neighbours; Naive Bayes applies Bayes' rule with an independence assumption — strong for text.
- Decision trees learn interpretable if/else splits but overfit alone.
- Random forests average many decorrelated trees (less variance); gradient boosting adds shallow trees that fix residuals (less bias) — the best default for tabular data.
- SVMs maximise the margin and use kernels for non-linear boundaries.
- k-means clusters by iterating assign/update; PCA projects onto directions of maximum variance.
- Choose by data type, size and interpretability needs; validate properly.