Which ML algorithm
No algorithm wins everywhere. The data type, the number of rows, the need to explain each prediction and the time budget narrow the choice to two or three candidates. Then cross-validation decides. This guide profiles the supervised, unsupervised, time-series, text and deep learning models of the course.
flowchart TD
A{"Labeled target?"} -->|no| U{"Goal?"}
U -->|groups| U1["KMeans / GMM / HDBSCAN"]
U -->|"fewer dimensions"| U2["PCA;<br/>t-SNE / UMAP to plot"]
U -->|"unusual rows"| U3["IsolationForest / LOF"]
A -->|yes| B{"Data type?"}
B -->|"images, audio"| NN["CNN in PyTorch,<br/>or a pretrained model"]
B -->|text| TX["TF-IDF + linear model;<br/>embeddings"]
B -->|"time series"| TS["seasonal naive, then<br/>SARIMA or boosting on lags"]
B -->|tabular| C{"Must explain each<br/>weight or rule?"}
C -->|yes| L["regularized linear model,<br/>shallow tree"]
C -->|no| D{"How many rows?"}
D -->|"under ~10,000"| D1["linear, SVM, random forest,<br/>HistGradientBoosting"]
D -->|"10,000 or more"| D2["HistGradientBoosting,<br/>LightGBM, XGBoost"]
Always fit a baseline first (DummyRegressor, DummyClassifier, a seasonal naive forecast). A model is only useful if it beats the baseline by a margin that matters.
Quick lookup
Section titled “Quick lookup”| I want to… | Use… | Notes |
|---|---|---|
| a baseline for regression | DummyRegressor(strategy="median") |
the score any model must beat |
| a baseline for classification | DummyClassifier(strategy="prior") |
AP equals the positive share |
| a fast, explainable regression | RidgeCV(alphas=np.logspace(-3, 3, 13)) |
scale first |
| select features automatically | LassoCV() or ElasticNetCV() |
zeros some coefficients |
| an explainable classifier with odds ratios | LogisticRegression(C=1.0) |
scale first; np.exp(coef_) |
| the best accuracy on a table | HistGradientBoostingClassifier / Regressor |
native NaN and categories |
| very large tables (millions of rows) | lightgbm.LGBMClassifier(verbose=-1) |
num_leaves, early stopping |
| a GPU-capable boosting model | xgboost.XGBClassifier(device="cuda") |
enable_categorical=True |
| a strong default with little tuning | RandomForestClassifier(n_estimators=300) |
oob_score=True for a free check |
| readable if-then rules | DecisionTreeClassifier(max_depth=3) |
export_text(tree) |
| a model for a few hundred clean rows | SVC(C=..., gamma=...) in a pipeline with a scaler |
CalibratedClassifierCV for probabilities |
| predictions from similar cases | KNeighborsClassifier(n_neighbors=15) |
scale first; slow on large data |
| a model in milliseconds | GaussianNB(), MultinomialNB() (text) |
poor probabilities |
| combine different good models | VotingClassifier(voting="soft"), StackingClassifier |
gains are usually small |
| groups of similar rows | KMeans(n_clusters=k, n_init=10) |
scale first; choose k with silhouette |
| clusters of any shape plus noise | HDBSCAN(min_cluster_size=...) |
label −1 = noise |
| soft cluster memberships | GaussianMixture(n_components=k) |
choose k with BIC |
| compress correlated features | PCA(n_components=0.9) |
keeps 90% of the variance |
| a 2-D picture of high-dimensional data | TSNE(perplexity=30), umap.UMAP(n_jobs=1) |
for viewing only |
| flag anomalies | IsolationForest(contamination=0.01) |
no scaling needed |
| forecast a series | seasonal naive → SARIMAX → boosting on lag features |
backtest with TimeSeriesSplit |
| classify text | TfidfVectorizer + LogisticRegression(C=10) |
LinearSVC is often a bit more accurate |
| find topics in text | NMF on TF-IDF, LatentDirichletAllocation on counts |
read the top words |
| images, audio, raw signals | a CNN in PyTorch, or fine-tune a pretrained model | needs much data or transfer learning |
| explain any model | permutation_importance, SHAP, partial dependence |
on held-out data |
Supervised models for tables
Section titled “Supervised models for tables”“Scale?” means the model needs standardized inputs (StandardScaler in a pipeline). “NaN” means fit accepts missing values without an imputer. “Interpretability”: high = read the weights or rules directly; low = needs SHAP or permutation importance.
| Model | Class | Strengths | Weaknesses | Scale? | Missing / categorical | Key hyperparameters | Typical size | Interpretability |
|---|---|---|---|---|---|---|---|---|
| Linear regression, Ridge, Lasso, ElasticNet | LinearRegression, RidgeCV, LassoCV, ElasticNetCV |
fast, stable, extrapolates a trend, small data | linear only unless you add features; OLS is pulled by outliers | yes for penalized models | impute; one-hot (drop one level for plain OLS) | alpha, l1_ratio |
any; good when rows are few or features many | high: coefficients |
| Logistic regression | LogisticRegression |
well-calibrated probabilities, odds ratios, fast | linear log-odds | yes | impute; one-hot | C (smaller = stronger penalty), l1_ratio, class_weight |
any | high: odds ratios |
| k-nearest neighbors | KNeighborsClassifier, KNeighborsRegressor |
no training, local patterns | slow predictions, weak in many dimensions, stores all data | yes, essential | impute (KNNImputer); one-hot |
n_neighbors, weights, metric |
up to ~100k rows, few features | medium: “similar cases” |
| Naive Bayes | GaussianNB, MultinomialNB, ComplementNB |
milliseconds, tiny data, text | assumes independent features; overconfident probabilities | no | impute; counts for MultinomialNB |
var_smoothing, alpha |
tiny to huge | medium: per-feature likelihoods |
| Support vector machine | SVC, SVR, LinearSVC |
strong on small, clean data; kernels for curves | kernel SVMs are slow above ~20k rows; no native probabilities | yes, essential | impute; one-hot | C, kernel, gamma |
kernel: under ~20k rows; LinearSVC: large sparse data |
low (kernel), medium (linear) |
| Decision tree | DecisionTreeClassifier, DecisionTreeRegressor |
readable rules, curves and interactions | unstable, overfits, step-shaped predictions | no | NaN: yes; ordinal or one-hot encoding | max_depth, min_samples_leaf, ccp_alpha |
any | high when shallow |
| Random forest, extra trees | RandomForestClassifier, ExtraTreesRegressor, … |
strong default, little tuning, free OOB score | large models, slower predictions, no extrapolation | no | NaN: yes; ordinal encoding is fine | n_estimators, max_features, min_samples_leaf |
1k to ~1M rows | low: permutation importance, SHAP |
| Histogram gradient boosting | HistGradientBoostingClassifier, …Regressor |
top accuracy on tables, fast | needs tuning for the last few points | no | NaN: yes; categories: native (category dtype) |
learning_rate, max_iter, max_leaf_nodes, l2_regularization, early_stopping |
best from ~10k rows; fine below | low: SHAP, partial dependence |
| XGBoost | xgboost.XGBClassifier, XGBRegressor |
top accuracy, GPU, many options | many parameters | no | NaN: yes; enable_categorical=True |
n_estimators, learning_rate, max_depth, subsample, colsample_bytree, early_stopping_rounds |
10k to 100M rows | low: SHAP |
| LightGBM | lightgbm.LGBMClassifier, LGBMRegressor |
fastest on large data | leaf-wise trees overfit small data | no | NaN: yes; pandas category columns natively |
num_leaves, learning_rate, n_estimators, min_child_samples |
100k+ rows | low: SHAP |
| Neural network | MLPClassifier, PyTorch nn.Module |
images, text, audio; any function | needs much data, compute and tuning; rarely beats boosting on tables | yes | impute; one-hot or embeddings | layers, width, learning rate, weight_decay, dropout, epochs, batch size |
10k+ rows; far more for images | low |
| Voting, stacking | VotingClassifier, StackingRegressor |
small extra accuracy from different models | slower; harder to maintain and explain | as its members | as its members | estimators, voting, final_estimator, cv |
any | low |
Which models accept missing values
Section titled “Which models accept missing values”import lightgbm as lgbimport numpy as npimport xgboost as xgbfrom sklearn.datasets import make_classificationfrom sklearn.ensemble import ( GradientBoostingClassifier, HistGradientBoostingClassifier, RandomForestClassifier,)from sklearn.linear_model import LogisticRegressionfrom sklearn.neighbors import KNeighborsClassifierfrom sklearn.svm import SVCfrom sklearn.tree import DecisionTreeClassifier
X_nan, y_nan = make_classification(n_samples=200, n_features=4, random_state=42)X_nan[::10, 0] = np.nan # 10% missing in one columnmodels = [ LogisticRegression(), KNeighborsClassifier(), SVC(), GradientBoostingClassifier(n_estimators=10), DecisionTreeClassifier(random_state=42), RandomForestClassifier(n_estimators=10, random_state=42), HistGradientBoostingClassifier(max_iter=10), xgb.XGBClassifier(n_estimators=10), lgb.LGBMClassifier(n_estimators=10, verbose=-1),]for model in models: try: model.fit(X_nan, y_nan) result = "accepts NaN" except ValueError: result = "ValueError: impute first" print(f"{type(model).__name__:<31} {result}")LogisticRegression ValueError: impute firstKNeighborsClassifier ValueError: impute firstSVC ValueError: impute firstGradientBoostingClassifier ValueError: impute firstDecisionTreeClassifier accepts NaNRandomForestClassifier accepts NaNHistGradientBoostingClassifier accepts NaNXGBClassifier accepts NaNLGBMClassifier accepts NaNThe models that accept NaN learn which branch the missing values follow. That treats “missing” as information, which helps when missingness itself predicts the target. Put a SimpleImputer in the pipeline for the others; add add_indicator=True to keep the “was missing” signal.
Which models need scaling
Section titled “Which models need scaling”Distance-based and penalized models compare features on one scale. Trees split one feature at a time and do not care. The wine data has features from 0.1 to 1,680:
from sklearn.datasets import load_winefrom sklearn.model_selection import StratifiedKFold, cross_val_scorefrom sklearn.pipeline import make_pipelinefrom sklearn.preprocessing import StandardScaler
X_wine, y_wine = load_wine(return_X_y=True)cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)candidates = { "KNN": KNeighborsClassifier(), "SVC (RBF)": SVC(), "logistic": LogisticRegression(max_iter=10_000), "forest": RandomForestClassifier(random_state=42),}for name, model in candidates.items(): raw = cross_val_score(model, X_wine, y_wine, cv=cv).mean() scaled = cross_val_score( make_pipeline(StandardScaler(), model), X_wine, y_wine, cv=cv ).mean() print(f"{name:<10} raw {raw:.3f} scaled {scaled:.3f}")KNN raw 0.680 scaled 0.972SVC (RBF) raw 0.674 scaled 0.983logistic raw 0.966 scaled 0.983forest raw 0.977 scaled 0.977| Scaler | Use when |
|---|---|
StandardScaler |
the default for linear models, SVM, KNN, PCA, neural networks |
RobustScaler |
outliers would dominate the mean and SD |
MinMaxScaler |
a bounded range is required (some neural network inputs, images) |
QuantileTransformer, PowerTransformer |
very skewed features for linear or distance models |
| none | trees, forests, boosting, naive Bayes |
Compare a shortlist
Section titled “Compare a shortlist”from sklearn.datasets import load_breast_cancerfrom sklearn.dummy import DummyClassifier
X_bc, y_bc = load_breast_cancer(return_X_y=True)shortlist = { "baseline": DummyClassifier(strategy="prior"), "logistic": make_pipeline(StandardScaler(), LogisticRegression()), "forest": RandomForestClassifier(n_estimators=200, random_state=42), "boosting": HistGradientBoostingClassifier(random_state=42),}for name, model in shortlist.items(): scores = cross_val_score(model, X_bc, y_bc, cv=cv, scoring="roc_auc") print(f"{name:<9} ROC-AUC {scores.mean():.3f} +/- {scores.std():.3f}")baseline ROC-AUC 0.500 +/- 0.000logistic ROC-AUC 0.995 +/- 0.005forest ROC-AUC 0.990 +/- 0.008boosting ROC-AUC 0.992 +/- 0.006On 569 rows with a near-linear signal, the scaled logistic regression is as good as the ensembles. It is faster and easier to explain, so it wins. On large tables with interactions, boosting usually leads.
Unsupervised models
Section titled “Unsupervised models”| Model | Class | Strengths | Weaknesses | Scale? | Missing / categorical | Key hyperparameters | Typical size | Interpretability |
|---|---|---|---|---|---|---|---|---|
| k-means | KMeans, MiniBatchKMeans |
fast, simple, predict for new rows |
you choose k; round clusters of similar size; outliers pull centroids | yes | impute; numeric only | n_clusters, n_init=10 |
up to millions (mini-batch) | high: centroids |
| Hierarchical (Ward) | AgglomerativeClustering, scipy...linkage |
a dendrogram; choose k after fitting | memory grows with n²; no predict |
yes | impute; numeric | n_clusters or distance_threshold, linkage |
under ~20k rows | high: the tree |
| DBSCAN, HDBSCAN | DBSCAN, HDBSCAN |
any cluster shape; marks noise (−1); no k | eps is hard to choose (DBSCAN); no predict |
yes | impute; numeric | eps, min_samples; min_cluster_size |
under ~100k rows | medium |
| Gaussian mixture | GaussianMixture |
soft probabilities, elliptical clusters, BIC for k | assumes Gaussian blobs; local optima | yes | impute; numeric | n_components, covariance_type |
under ~100k rows | medium: means and covariances |
| PCA | PCA, IncrementalPCA |
fast, decorrelates, compresses, denoises | linear; each component mixes features | yes | impute; numeric | n_components (int or variance share) |
any | medium: loadings |
| t-SNE | TSNE |
clear 2-D maps of local neighbors | no transform; gaps and sizes mean nothing; slow |
yes | impute; numeric | perplexity |
under ~50k rows | low: for viewing only |
| UMAP | umap.UMAP |
faster than t-SNE; transform for new rows |
same reading caveats as t-SNE | yes | impute; numeric | n_neighbors, min_dist |
up to millions | low |
| Isolation forest | IsolationForest |
many features, no scaling, fast | contamination is a quota, not a discovery |
no | NaN: accepted in scikit-learn 1.9; numeric | contamination, n_estimators |
any | low: anomaly score |
| Local outlier factor | LocalOutlierFactor |
local, density-based anomalies | slow on large data; novelty=True to score new rows |
yes | impute; numeric | n_neighbors, contamination, novelty |
under ~100k rows | low |
Categorical columns are a poor fit for distance-based clustering: one-hot columns dominate the distances. Cluster on numeric behavior, then profile the clusters with the categorical columns.
Time-series models
Section titled “Time-series models”| Model | How | Strengths | Weaknesses | Scale? | Missing values | Key hyperparameters | Typical size | Interpretability |
|---|---|---|---|---|---|---|---|---|
| naive, seasonal naive | last value, or the value one season ago | the baseline; hard to beat at short horizons | no trend, no inputs | no | needs a regular index | season length m |
any | high |
| ETS (exponential smoothing) | statsmodels.tsa.holtwinters.ExponentialSmoothing |
trend and one seasonality, fast | no external inputs | no | fill gaps first | trend, seasonal, damped_trend |
two or more seasons | high: smoothing weights |
| SARIMA / SARIMAX | statsmodels...SARIMAX |
prediction intervals, known future inputs (exog) |
one seasonality; slow for long seasons (s=365); convergence issues |
no | fill gaps first | order=(p, d, q), seasonal_order=(P, D, Q, s) |
50 to a few thousand points | medium: coefficients |
| Boosting on lag features | LGBMRegressor on shift/rolling features |
many series, many inputs, nonlinear | cannot extrapolate a trend; recursive multi-step forecasts; leakage risk | no | NaN: yes | lags, window sizes, plus boosting parameters | 1k+ rows | low |
Text models
Section titled “Text models”| Model | Input | Strengths | Weaknesses | Key hyperparameters | Typical size | Interpretability |
|---|---|---|---|---|---|---|
LogisticRegression |
TF-IDF | probabilities, readable word weights | bag of words: word order lost beyond n-grams | C (try 10), ngram_range, min_df |
1k to millions of documents | high: top words |
LinearSVC |
TF-IDF | often the most accurate linear model | no predict_proba |
C |
same | high |
MultinomialNB, ComplementNB |
counts | very fast, strong on small data | overconfident probabilities | alpha |
small to huge | medium |
SGDClassifier |
TF-IDF | streams and huge corpora (partial_fit) |
needs tuning | alpha, loss |
millions | high |
NMF, LatentDirichletAllocation |
TF-IDF, counts | topics without labels | you choose the number of topics | n_components |
1k+ documents | medium: top words |
| embeddings (LSA, pretrained transformers) + a linear model | dense vectors | meaning, synonyms | compute cost; black box | model choice, dimensions | any | low |
Trees and KNN are rarely good on sparse text: thousands of sparse columns make splits and distances weak.
Worked scenarios
Section titled “Worked scenarios”| Situation | Shortlist | Why |
|---|---|---|
| predict churn for 5,000 customers, managers want reasons | logistic regression; then boosting if it gains enough | odds ratios explain; boosting sets the accuracy ceiling |
| house prices, 3,000 rows, skewed target | Ridge on log price; HistGradientBoosting | log fixes the skew; boosting captures neighborhood × size |
| fraud in 10M transactions, 0.1% positive | LightGBM with early stopping, then a tuned threshold | speed at scale; rare class needs AP and a cost threshold |
| 300 lab samples, 20 clean numeric features | logistic regression, SVM, random forest with repeated CV | small data: simple models, stable estimates |
| segment customers for marketing | scaled k-means, k from silhouette and business sense | centroids are easy to name and act on |
| detect faulty sensor readings, no labels | IsolationForest per machine, rolling features | no scaling; one model per machine avoids flagging a whole machine |
| forecast daily web visits 28 days ahead | seasonal naive, SARIMA, boosting on lags; backtest all | the baseline often wins at short horizons |
| classify 3,000 product reviews | TF-IDF + logistic regression | strong, fast, readable |
| classify photos | fine-tune a pretrained CNN | transfer learning needs far fewer images |
Gotchas
Section titled “Gotchas”| Trap | Symptom | Fix |
|---|---|---|
| KNN, SVM or a penalized model without scaling | poor scores; one feature dominates | make_pipeline(StandardScaler(), model) |
| scaling fitted on all rows | optimistic CV scores | the scaler inside the pipeline |
KMeans() with default n_init |
a worse local minimum | n_init=10 |
| a deep tree’s training score | R² = 1.0 or 100% accuracy | limit max_depth; judge on CV |
| trees or boosting asked to extrapolate | flat predictions beyond the training range | linear model, or a target with no trend (differences, ratios) |
RandomForestRegressor() defaults |
plain bagging: max_features=1.0 |
try max_features 0.3–0.6 |
HistGradientBoosting early stopping |
off below 10,000 rows ("auto") |
early_stopping=True with a validation share |
| LightGBM on a few hundred rows | overfits; terminal logs | larger min_child_samples, verbose=-1 |
SVC on 100k rows |
training takes hours | LinearSVC, SGDClassifier, or boosting |
SVC.predict_proba |
slow, and inconsistent with predict |
CalibratedClassifierCV, or a model with native probabilities |
GaussianNB probabilities |
often near 0 or 1 | use for ranking only, or calibrate |
| one-hot encoding of a high-cardinality column | thousands of columns; slow models | TargetEncoder in the pipeline, or native categories in boosting |
| clusters found on a t-SNE map | artifacts of the map | cluster on the original (scaled) features |
| a neural network on a small table | worse than boosting, after hours | try boosting first |
| an ensemble of models that agree | no gain, more cost | check the correlation of their predictions |
| choosing by the test-set score | an optimistic, unrepeatable result | choose with CV; look at the test set once |
Learn more
Section titled “Learn more”- Module 34: scikit-learn workflow and its cheat sheet
- Module 35: regression and module 36: classification, with their regression and classification cheat sheets
- Module 38: ensembles and its cheat sheet
- Module 39: unsupervised learning and its cheat sheet
- Module 40: time series, module 41: NLP and module 42: deep learning
- Decision guides: which metric and which CV strategy