Traditional models · lesson 15 of 16
Parts in this lesson
Across_validate(model, X, y, scoring=['recall', 'average_precision'])several metrics at once
BLogisticRegression(class_weight='balanced')make the rare class count
CLogisticRegression(l1_ratio=1, solver='liblinear')3.8: lasso’s penalty, for classification

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:

Model guideevery model from Stages 2 to 4

15 models fit. Compare them with cross-validation (lesson 4.14).

ModelGood atWatch out forScale features?Readable?scikit-learn
Linear regression (ridge, lasso)lesson 3.1–3.8a first model for any number; each weight says how muchcurves and interactions need features built by handyeshighLinearRegression, Ridge, Lasso
Logistic regressionlesson 3.9–3.11a first model for any classes; good probabilities; many features, few rowsstraight boundaries only, unless you add featuresyeshighLogisticRegression
k-nearest neighbourslesson 2.4small data with a few meaningful features; explains itself by exampleslow to predict on big data; useless with many noisy featuresyessomeKNeighborsClassifier, KNeighborsRegressor
Naive Bayeslesson 4.3text, word counts; very little data; very fastprobabilities overconfident; features assumed independentnosomeMultinomialNB, GaussianNB
Decision treelesson 4.4rules people can read and check; mixed feature typesoverfits when deep; unstable: a small change in data, a different treenohighDecisionTreeClassifier, DecisionTreeRegressor
Random forestlesson 4.5strong with no tuning; hard to overfit by adding trees; out-of-bag score for freelarge models, slower predictions; impurity importances misleadnolowRandomForestClassifier, RandomForestRegressor
Gradient boostinglesson 4.6tables of thousands of rows or more: usually the most accurate; handles missing valuesneeds tuning; overfits with too many trees at a high learning ratenolowHistGradientBoostingClassifier, HistGradientBoostingRegressor
Support vector machinelesson 4.7small to medium data with curved boundaries (RBF kernel)slow past tens of thousands of rows; C and γ need tuningyeslowSVC, SVR (LinearSVC for big data)
k-meanslesson 4.8round, similar-sized groups; fast on big datayou choose k; long or curved clusters split wronglyyessomeKMeans, MiniBatchKMeans
DBSCANlesson 4.9any shape of cluster; finds the number itself; marks noiseone eps for all clusters: struggles when densities differyessomeDBSCAN, HDBSCAN
Hierarchical clusteringlesson 4.9a dendrogram showing groups within groupsmemory grows with the square of the rowsyeshighAgglomerativeClustering
Gaussian mixturelesson 4.9soft, stretched (elliptical) clusters; a probability for eachyou choose the number; can settle on a poor answer, so restartyessomeGaussianMixture
PCAlesson 4.10fewer features keeping most variation; speed, plots, less noiseonly straight directions; centre (and usually scale) firstyessomePCA
t-SNE, UMAPlesson 4.11a 2-D map to look at, to see clustersdistances between clusters and their sizes mean little; not for model inputyeslowTSNE (UMAP: the umap-learn package)
Isolation forestlesson 4.12unusual rows in tables; fast; no labels neededfit it on normal data; you choose how many to flagnolowIsolationForest

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:

  1. What's the task? A class, a number, groups, fewer features, or odd rows (lesson 2.2)?
  2. What's the data? A table, or text, images, sound? How many rows? How many features, and how many of them useful?
  3. What does a mistake cost, and which kind costs more? That picks the metric (lessons 2.8 and 2.11).
  4. 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.

field-guide.ipynb

"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 k from 2 to 5 and look at the groups.

field-guide.ipynb

The silhouette is highest at k=3 (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. k-means with k=3 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).

field-guide.ipynb

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%. k-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:

field-guide.ipynb

The tree: 92.8%. Boosting: 96.7%. Then read the tree:

field-guide.ipynb

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.

field-guide.ipynb

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.

1. Predict tomorrow’s electricity demand in Metro Manila, in megawatts, from weather forecasts and the day of the week. 5 years of hourly data.
2. Sort 2,000 support emails into 6 topics. 300 are labelled.
3. A bank must explain every loan refusal to the customer, by law. 50,000 past loans.
4. A clinic has 150 patients and 12 measurements, and wants to predict a yes-or-no outcome.
5. Spot unusual logins to a company’s systems. No logins are labelled as attacks.
6. A researcher has 10,000 single cells with 2,000 gene readings each, and wants to see whether they fall into types.
7. Predict which of 10,000 customers will cancel next month. 3% do. Staff can call 200 a month.
8. Is a parcel over the 5 kg limit? Each parcel is weighed.
9. Recognise 30 kinds of plant disease from phone photos of leaves. 20,000 labelled photos.
10. Estimate a car’s fuel use from 8 engineering measurements. 400 cars.
11. A shop wants 4 groups of products that tend to be bought together, from sales records.
12. Detect whether a voice recording says “yes” or “no”. 50,000 one-second clips.
13. Forecast daily sales for 500 shops, with 3 years of history. A colleague shuffles the rows before cross-validating. What’s wrong?
14. You have 200,000 rows and 30 mixed features, and need the most accurate classifier you can get. Readability doesn’t matter.
15. Two models score 0.861 ± 0.02 and 0.858 ± 0.02 in cross-validation. One is a random forest, the other a lasso regression with 6 non-zero weights. Which do you choose?

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.

All sources for Simple Machine Learning