TExcelTAD

Choosing an Algorithm

You have now built every major classical algorithm. Faced with a new problem, which one do you try first? There is no universally best model; the no free lunch theorem says that averaged over all possible problems, every learner is equally good. Real problems are not "all possible problems", though: they have structure, and the structure (how much data, what kind of features, what the model will be used for) narrows the choice quickly. This lesson collects the trade-offs from the course into a guide and shows how the amount of data changes the answer.

Questions to ask first

  1. What is the task? Regression, classification, clustering, dimensionality reduction or anomaly detection.
  2. How much data, how many features? Tens of rows, thousands, millions? Tens of features or tens of thousands (text)?
  3. What kind of features? Numeric, categorical with many levels, text, images, missing values.
  4. What does the model have to do besides predict? Be explained to a regulator, give calibrated probabilities, run in 1 ms, update online, extrapolate.
  5. How will you know it works? A metric and a validation scheme, decided before you compare models.

A decision guide

labels available? yesno 1. linear baseline 2. what kind of data? tabular: random forest, then gradient boosting (LightGBM, ...) text: linear model, naive Bayes small, few features: SVM (RBF), kNN must explain: linear, shallow tree images, audio: deep learning what do you need? compact groups: k-means, GMM odd shapes + noise: DBSCAN a hierarchy: agglomerative fewer dimensions: PCA nonlinear codes: autoencoder anomalies: isolation forest always: compare against a baseline with the same cross-validation splits

The algorithms side by side

Algorithm Data size Scaling needed Categorical / missing Interpretable Main hyperparameters
linear / logistic any yes (with penalty) encode / impute yes (coefficients) C or alpha
decision tree any no encode; missing values handled since scikit-learn 1.3 yes (rules) max_depth, min_samples_leaf
random forest up to millions no encode; missing values handled since 1.4 partly (importances) n_estimators, max_features
gradient boosting up to millions no native in LightGBM, CatBoost, XGBoost partly learning rate, trees, depth or leaves
kNN small to medium yes encode / impute by example k, metric
SVM up to about 10510^5 yes encode / impute no (kernel) C, gamma
naive Bayes any, great when tiny no variants per type yes (per-feature evidence) smoothing
k-means up to millions yes encode centroids k
DBSCAN up to about 10510^5 yes encode no eps, min_samples
Gaussian mixture small to medium usually encode components k, covariance type
PCA any usually encode loadings number of components
isolation forest any no encode no max_samples, threshold

How the amount of data changes the answer

A nonlinear problem (each class spread over three clusters in 10 dimensions), four models, cross-validated accuracy for growing training sets:

python · try it yourself
import numpy as np
from sklearn.datasets import make_classification
from sklearn.model_selection import learning_curve, StratifiedKFold
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.neighbors import KNeighborsClassifier
from sklearn.ensemble import RandomForestClassifier, HistGradientBoostingClassifier

# a nonlinear problem: each class is spread over 3 clusters
X, y = make_classification(n_samples=3000, n_features=10, n_informative=6, n_clusters_per_class=3,
                           flip_y=0.02, random_state=0)
models = {
    "logistic":       make_pipeline(StandardScaler(), LogisticRegression()),
    "kNN (k=7)":      make_pipeline(StandardScaler(), KNeighborsClassifier(7)),
    "random forest":  RandomForestClassifier(n_estimators=40, random_state=0, n_jobs=1),
    "hist. boosting": HistGradientBoostingClassifier(max_iter=50, random_state=0),
}
sizes = [50, 200, 600, 2000]
cv = StratifiedKFold(3, shuffle=True, random_state=0)
print("training rows      " + "".join(f"{s:>7d}" for s in sizes))
for name, model in models.items():
    _, _, test = learning_curve(model, X, y, train_sizes=sizes, cv=cv, shuffle=True, random_state=0)
    print(f"{name:18s} " + "".join(f"{m:7.3f}" for m in test.mean(axis=1)))
training rows           50    200    600   2000
logistic             0.733  0.767  0.767  0.772
kNN (k=7)            0.706  0.807  0.841  0.877
random forest        0.722  0.801  0.839  0.880
hist. boosting       0.703  0.803  0.842  0.880

With 50 rows the simple linear model is as good as anything (0.733): flexible models have too little data to use their flexibility. From 200 rows on, the linear model is stuck near 0.77 (its bias), while kNN, the forest and boosting keep improving to about 0.88 at 2000 rows. The lesson generalises: with little data prefer simple, strongly regularised models; with more data, flexible models pay off. A learning curve like this, on your own data, tells you whether collecting more data or choosing a more flexible model is the better investment.

A sensible default workflow

  1. Baseline: DummyClassifier/DummyRegressor, then a regularised linear model with scaling. Every later model must beat these.
  2. Strong default for tabular data: a random forest (little tuning), then gradient boosting (HistGradientBoosting, LightGBM, XGBoost or CatBoost) with early stopping.
  3. Tune only the few hyperparameters that matter, by cross-validation on the training data.
  4. Compare on the same splits, with the spread across folds, and prefer the simpler model when the difference is within the noise (Comparison Bench).
  5. Look at the errors, not just the score: which cases fail, and is the failure acceptable?
  6. Test once, at the end, on held-out data.

For text, start with tf-idf plus a linear model or naive Bayes; for images, audio and long sequences, the deep-learning courses of this track. For preprocessing that most of these models need (imputation, encoding, scaling inside pipelines), see Data Preparation.

Pitfalls

  • Choosing by reputation. "Boosting always wins" is often true on large tabular data and often false on small data, text, or problems with a simple structure.
  • Tuning one model for days and the baseline for minutes. The comparison is then unfair.
  • Ignoring non-accuracy requirements. A model that cannot be explained, monitored or served in time is not the best model, whatever its score.

Practice

  1. You have 120 labelled patients, 15 numeric measurements, and doctors must understand the model. What do you try first?
Answer

Regularised logistic regression (scaled, C chosen by cross-validation), perhaps compared with a shallow decision tree. Both are readable, and with 120 rows flexible models have little room to shine; use repeated cross-validation, since a single split of 120 rows is very noisy.

  1. A learning curve shows validation accuracy still rising steeply at the largest training size. What does that suggest?
Answer

The model is variance-limited: more data would help. Collect more labelled data if possible, or regularise more strongly; a more flexible model would likely make things worse at the current size.

Test yourself

What should every model comparison include?

  1. Only gradient boosting
  2. A simple baseline evaluated on the same splits
  3. The test set at every step
  4. At least 10 models

With 50 training rows, the logistic regression matched the flexible models; with 2000 it fell far behind. Why?

  1. Logistic regression overfits large data
  2. With little data flexible models cannot exploit their flexibility; with more, the linear model's bias dominates
  3. The data changed
  4. Logistic regression needs scaling

Which is the most reasonable first strong model for a tabular problem with 50 000 rows of mixed numeric and categorical features?

  1. kNN with k=1k = 1
  2. A kernel SVM
  3. A random forest or gradient-boosted trees
  4. Gaussian naive Bayes