Which model for which task: a field guide
Last updated
This lesson gathers everything from Stages 2 to 4 into one guide you can come back to. A table of every model, filtered by your task and your data. Eight worked cases, from a spam filter to a regulator's loan model, each reasoned through and then checked in a notebook. And a test of fifteen scenarios, so you can see whether you can make the choice yourself.
By the end of this lesson you can
- Go from a task and a data set to a short list of models, and defend the choice
- Choose a metric that matches the cost of mistakes, including for rare classes
- Recognise when a simple, readable model is the right answer
- Say where neural networks change the choice, and where they don’t
The model guide
Every model from Stages 2 to 4, in one table. Choose the task, and tick what's true of your problem:
15 models fit. Compare them with cross-validation (lesson 4.14).
| Model | Good at | Watch out for | Scale features? | Readable? | scikit-learn |
|---|---|---|---|---|---|
| Linear regression (ridge, lasso)lesson 3.1–3.8 | a first model for any number; each weight says how much | curves and interactions need features built by hand | yes | high | LinearRegression, Ridge, Lasso |
| Logistic regressionlesson 3.9–3.11 | a first model for any classes; good probabilities; many features, few rows | straight boundaries only, unless you add features | yes | high | LogisticRegression |
| k-nearest neighbourslesson 2.4 | small data with a few meaningful features; explains itself by example | slow to predict on big data; useless with many noisy features | yes | some | KNeighborsClassifier, KNeighborsRegressor |
| Naive Bayeslesson 4.3 | text, word counts; very little data; very fast | probabilities overconfident; features assumed independent | no | some | MultinomialNB, GaussianNB |
| Decision treelesson 4.4 | rules people can read and check; mixed feature types | overfits when deep; unstable: a small change in data, a different tree | no | high | DecisionTreeClassifier, DecisionTreeRegressor |
| Random forestlesson 4.5 | strong with no tuning; hard to overfit by adding trees; out-of-bag score for free | large models, slower predictions; impurity importances mislead | no | low | RandomForestClassifier, RandomForestRegressor |
| Gradient boostinglesson 4.6 | tables of thousands of rows or more: usually the most accurate; handles missing values | needs tuning; overfits with too many trees at a high learning rate | no | low | HistGradientBoostingClassifier, HistGradientBoostingRegressor |
| Support vector machinelesson 4.7 | small to medium data with curved boundaries (RBF kernel) | slow past tens of thousands of rows; C and γ need tuning | yes | low | SVC, SVR (LinearSVC for big data) |
| k-meanslesson 4.8 | round, similar-sized groups; fast on big data | you choose k; long or curved clusters split wrongly | yes | some | KMeans, MiniBatchKMeans |
| DBSCANlesson 4.9 | any shape of cluster; finds the number itself; marks noise | one eps for all clusters: struggles when densities differ | yes | some | DBSCAN, HDBSCAN |
| Hierarchical clusteringlesson 4.9 | a dendrogram showing groups within groups | memory grows with the square of the rows | yes | high | AgglomerativeClustering |
| Gaussian mixturelesson 4.9 | soft, stretched (elliptical) clusters; a probability for each | you choose the number; can settle on a poor answer, so restart | yes | some | GaussianMixture |
| PCAlesson 4.10 | fewer features keeping most variation; speed, plots, less noise | only straight directions; centre (and usually scale) first | yes | some | PCA |
| t-SNE, UMAPlesson 4.11 | a 2-D map to look at, to see clusters | distances between clusters and their sizes mean little; not for model input | yes | low | TSNE (UMAP: the umap-learn package) |
| Isolation forestlesson 4.12 | unusual rows in tables; fast; no labels needed | fit it on normal data; you choose how many to flag | no | low | IsolationForest |
Read it as lesson 4.14 says: it makes a short list, and cross-validation on the same folds, against a baseline, makes the choice. Four questions get you most of the way:
- What's the task? A class, a number, groups, fewer features, or odd rows (lesson 2.2)?
- What's the data? A table, or text, images, sound? How many rows? How many features, and how many of them useful?
- What does a mistake cost, and which kind costs more? That picks the metric (lessons 2.8 and 2.11).
- Who must understand the model? That can rule out everything but the simplest.
The eight cases that follow each answer these four, then check the answer in a notebook.
Case 1: a spam filter
The problem. A small company wants to filter spam from its customer messages. It has 400 messages, labelled spam or not by a staff member in an afternoon.
The reasoning. A class (spam or not), from text, with few labels. Text becomes word counts or TF-IDF (lesson 4.2): thousands of sparse features. Naive Bayes is built for counts, needs very little data, and trains instantly; logistic regression on TF-IDF usually overtakes it as the labels grow. Missing a spam costs little; hiding a real customer's message costs more, so precision for the spam class matters most (lesson 2.8).
The short list. MultinomialNB and LogisticRegression, each after a TfidfVectorizer in a pipeline, compared on precision at a recall the company can live with. Lesson 4.3 builds the first. Retrain as new kinds of spam appear: spammers change their words to get past filters, the fastest drift there is (lesson 4.14).
Case 2: house prices
The problem. Estimate the price of houses from their size, age, location and neighbourhood, from 20,000 past sales.
The reasoning. A number: regression. A table of tens of thousands of rows, with mixed features and location effects that jump from district to district. That's where boosted trees win (lesson 4.14). Prices are skewed, so a log of the price may help (lesson 4.1); RMSE punishes the big misses that lose a sale (lesson 2.11). Features like the distance to the city centre will matter more than the choice of model (lesson 4.2).
The short list. HistGradientBoostingRegressor, RandomForestRegressor, and Ridge with good features as the baseline. Lesson 4.P is this case, on California's 1990 census: ridge 0.663, the forest 0.591 and boosting 0.556 (in $100,000s, RMSE).
Case 3: rare fraud
The problem. Flag fraudulent card payments. 2% of past payments were fraud. Every flagged payment is checked by a person; a missed fraud costs the bank the money.
The reasoning. A class, from a table, but rare. Accuracy is useless: always saying "fine" scores 98% (lesson 2.8). The metrics that matter are recall (how much fraud is caught) and average precision, the area under the precision–recall curve, which scores the whole ranking of payments from most to least suspicious. class_weight="balanced" makes the rare class count as much as the common one in training.
"Always fine" is 98% accurate and catches nothing. Logistic regression, balanced, catches 87% of fraud but its average precision is only 0.32: it flags many honest payments along the way. Boosting is 99% accurate, catches 58% at the default threshold, and has by far the best average precision, 0.77: its ranking puts fraud at the top. Move its threshold down (lesson 2.8) and it catches more, at a cost in checks the bank can choose.
The choice. Gradient boosting, judged by average precision, with the threshold set by how many payments the bank's staff can check each day.
Case 4: groups of customers
The problem. A shop wants to know what kinds of customer it has, to plan its offers. It has visits a month and money spent per visit for 330 customers, and no labels.
The reasoning. No labels: clustering. Two numbers in different units, so scale them (lesson 4.1). The groups should be few enough to plan for, so try from 2 to 5 and look at the groups.
The silhouette is highest at (0.668), just ahead of 2. The three groups make sense to a shopkeeper: about 12 visits a month spending ₱305 (regulars buying a little often), 2 visits spending ₱2,531 (big monthly shops), and 6 visits spending ₱1,360 (in between). That they make sense is the real test.
The choice. -means with on scaled features. If the groups were long or oddly shaped, a Gaussian mixture or DBSCAN (lesson 4.9).
Case 5: a machine about to fail
The problem. A factory's pump has a dozen sensors read every minute. Failures are rare, and each one is different. Engineers want an early warning.
The reasoning. Too few failures to learn them as a class: anomaly detection. There are months of readings from when the pump was known to be healthy, so this is novelty detection: fit on healthy data (lesson 4.12), score new readings as they arrive. Several sensors at once, so not z-scores on each alone. Features matter: the change over the last hour, or the gap between two sensors that usually agree (lesson 4.2).
The choice. IsolationForest fitted on healthy readings, the alert threshold set by how many alarms the engineers can check, and the alarms judged by precision and recall against the failures that do happen.
Case 6: 1,000 features, 200 rows
The problem. A lab has measured 1,000 genes in 200 patients, and wants to predict which patients respond to a drug. Probably only a handful of genes matter.
The reasoning. Far more features than rows. Almost any model can fit 200 rows perfectly with 1,000 features, so overfitting is the whole problem. Distance-based models drown in the 990 useless features (lesson 4.2). A strong penalty is needed, and since only a few genes matter, an L1 penalty, which sets most weights to exactly 0, fits the problem (lesson 3.8).
On simulated data like this, logistic regression with an L1 penalty scores 93.5%. With an L2 penalty, which keeps every gene a little, 67%. A random forest, choosing features as it splits, 90.5%. -NN, comparing patients across all 1,000 genes, 57%, barely better than a coin.
The choice. L1-penalised logistic regression, its strength C chosen by nested cross-validation, because with 200 rows a lucky search is easy (lesson 4.13). And its non-zero weights name the genes, which the lab wants anyway.
Case 7: a model a regulator must read
The problem. A hospital wants a model to flag tumours as possibly malignant for a second look. The health regulator requires that doctors can see and check its reasoning.
The reasoning. A class, from a table of measurements, and readability is required, not a bonus. So the question becomes: how much accuracy does a readable model cost? Compare a two-level tree with gradient boosting:
The tree: 92.8%. Boosting: 96.7%. Then read the tree:
Three questions, about the size of the largest cells, the concave points on their outline and their texture, which a doctor can hold in their head and check against what they know about tumours. The 4-point gap is real and matters in medicine. But the readable model's mistakes can be found and argued with; the boosted model's can't.
The choice. A small tree or a sparse logistic regression, tuned for recall on malignant tumours (a missed cancer costs more than a second look), with the gap to the best black-box model reported honestly so the hospital can decide. Lesson 4.14 explains why this is often the right call where decisions are serious.
Case 8: pictures
The problem. Sort handwritten digits.
The reasoning. Images. Pixels are features, but each one alone means little; what matters is shapes made of many pixels together. Lesson 4.2 showed hand-made features losing to raw pixels, and the models of this stage only see pixels one by one.
On all 1,797 digits, logistic regression gets 92.8%, a random forest 93.7%, an RBF SVM 96.3%. Good, for 8 × 8 pictures. But on real photos, at hundreds of pixels a side, these models fall far behind convolutional networks (Stage 8), which learn their own features: edges, then shapes, then parts.
The choice. For tiny images, an SVM is a fine start. For real images, sound or text, neural networks, from Stage 6 on. That's the big change deep learning brings to this guide: on images, sound and language, learned features win. On tables, the trees of this stage still usually do (lesson 4.14, step 6). Later stages add rows for each kind of network to the guide.
Wrong way: the most powerful model by default
The tempting rule is "always use the strongest model": gradient boosting for tables, a neural network for everything else. The cases above show where it fails:
- Case 6: on 200 rows and 1,000 features, a simple penalised linear model beat everything.
- Case 7: the strongest model wasn't allowed.
- Lesson 4.14's race: on small, clean tables, boosting came fifth of six on two of the three.
- Lesson 2.12's leap years: no model at all was the right answer.
Powerful models cost something: more data to train well, more settings to tune, slower predictions, models nobody can read, and more ways to overfit. Start simple, with a baseline and a linear model, and move to a stronger model only when cross-validation shows it earns its place.
Test: fifteen scenarios
For each, pick the best first choice. Use the guide in step 1 if you like.
Sources
Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.
- scikit-learn: Choosing the right estimator: scikit-learn’s map from task and data size to model
- Grinsztajn, Oyallon and Varoquaux, Why do tree-based models still outperform deep learning on tabular data?, NeurIPS Datasets and Benchmarks, 2022: trees on tables, networks on images and text
- Saito and Rehmsmeier, The precision-recall plot is more informative than the ROC plot when evaluating binary classifiers on imbalanced datasets, PLOS ONE 10(3), 2015: why average precision suits rare classes
- scikit-learn: Metrics and scoring: every scoring name, from accuracy to average_precision