Velamuvi AIAcademy

Lesson 9 of 12 · In Practice

Choosing an Algorithm

Choose between linear models, trees, k-NN and Naive Bayes: questions to ask, a side-by-side table, fair cross-validated comparisons and tuning the winner.

  • 12 min read
  • Intermediate
  • Reviewed
In this lesson you will learn
  • Explain why no algorithm is the best for every problem
  • Narrow the options with questions about the data, explanations, speed and probabilities
  • Compare several algorithms fairly with cross-validation on the same folds
  • Weigh accuracy against model size, speed and how easy a model is to explain
  • Tune the chosen model's hyperparameters with GridSearchCV

The idea in plain words

You have now met four families of supervised models: linear models, tree-based models, instance-based models and probabilistic models. Which one should you use?

There is a famous result in machine learning called the no free lunch theorem: averaged over every possible problem, no learning algorithm beats any other. Each family makes assumptions about the world (straight lines, boxes, similar examples have similar labels, independent clues), and it does well exactly when its assumptions fit the data. So the practical approach has two steps: use what you know about the problem to pick a few sensible candidates, then let cross-validation decide between them.

Questions to ask first

QuestionIf the answer is yes
Is the data a table of rows and columns?Start with tree ensembles and a regularised linear model
Is it text?Linear models or Naive Bayes on word counts are fast, strong choices
Is it images, sound or video?Deep learning, which learns its own features (see Introduction to Deep Learning)
Must you explain each prediction to a person?Linear models or a small decision tree
Will you act on the probabilities themselves?Logistic regression, or any model after checking calibration
Is there little data, say a few hundred rows?Simpler, regularised models; avoid very flexible ones
Must predictions be very fast, or the model very small?Linear models; avoid k-NN
Are many features probably irrelevant?Lasso or tree ensembles; avoid k-NN

The four families side by side

Linear modelsTree ensemblesk-nearest neighboursNaive Bayes
Learns curved patternsOnly with extra featuresYesYesA little
Needs scaled featuresYes, when regularisedNoYesNo
TrainingFastMediumInstant: just stores the dataVery fast: just counts
PredictingVery fastMediumSlow on big dataVery fast
Easy to explainYes: one weight per featureSmall trees yes, ensembles less soBy example: "similar cases"Partly: word probabilities
ProbabilitiesUsually well calibratedCheck calibrationRough: shares of the voteOften too extreme
Typical homeText, many features, first modelsTables of dataSmall data with few features; similarity searchText, very small datasets

Let the data decide

Here are six models from the four families, compared with 5-fold cross-validation on the breast tumour data. cross_val_score with cv=5 uses the same five folds for every model, so they all face exactly the same test examples:

Try it yourselfPython
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import GradientBoostingClassifier, RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.naive_bayes import GaussianNB
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.tree import DecisionTreeClassifier

models = {
    "logistic regression": make_pipeline(StandardScaler(), LogisticRegression()),
    "k-nearest neighbours": make_pipeline(StandardScaler(), KNeighborsClassifier()),
    "Gaussian Naive Bayes": GaussianNB(),
    "decision tree": DecisionTreeClassifier(max_depth=5, random_state=0),
    "random forest": RandomForestClassifier(n_estimators=100, random_state=0),
    "gradient boosting": GradientBoostingClassifier(n_estimators=50, random_state=0),
}

X, y = load_breast_cancer(return_X_y=True)        # 569 tumours, 30 measurements
for name, model in models.items():
    scores = cross_val_score(model, X, y, cv=5)    # the same 5 folds for every model
    print(f"{name:<21} {scores.mean():.3f} +/- {scores.std():.3f}")
Output
logistic regression   0.981 +/- 0.007
k-nearest neighbours  0.965 +/- 0.010
Gaussian Naive Bayes  0.939 +/- 0.015
decision tree         0.916 +/- 0.016
random forest         0.963 +/- 0.022
gradient boosting     0.958 +/- 0.017

On this data the simplest model wins: logistic regression scores 0.981 with the smallest spread. The two classes are separated well by a weighted sum of the measurements, so a straight boundary is all that's needed, and the extra flexibility of the other models only adds noise.

Now the same six models on a different problem: two curved classes that interlock like crescent moons, with just two features:

Try it yourselfPython
from sklearn.datasets import make_moons
from sklearn.ensemble import GradientBoostingClassifier, RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.naive_bayes import GaussianNB
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.tree import DecisionTreeClassifier

models = {
    "logistic regression": make_pipeline(StandardScaler(), LogisticRegression()),
    "k-nearest neighbours": make_pipeline(StandardScaler(), KNeighborsClassifier()),
    "Gaussian Naive Bayes": GaussianNB(),
    "decision tree": DecisionTreeClassifier(max_depth=5, random_state=0),
    "random forest": RandomForestClassifier(n_estimators=100, random_state=0),
    "gradient boosting": GradientBoostingClassifier(n_estimators=50, random_state=0),
}

X, y = make_moons(n_samples=500, noise=0.3, random_state=0)   # two curved, interleaved classes
for name, model in models.items():
    scores = cross_val_score(model, X, y, cv=5)
    print(f"{name:<21} {scores.mean():.3f} +/- {scores.std():.3f}")
Output
logistic regression   0.844 +/- 0.022
k-nearest neighbours  0.886 +/- 0.027
Gaussian Naive Bayes  0.840 +/- 0.033
decision tree         0.874 +/- 0.046
random forest         0.876 +/- 0.031
gradient boosting     0.880 +/- 0.026

The ranking flips. Logistic regression (0.844) and Naive Bayes (0.840) can't follow the curves, while k-NN (0.886) and the tree models (0.874 to 0.880) can. The top four differ by about 0.01, less than their spreads of 0.03 to 0.05, so they are effectively tied. Same code, same models, opposite conclusions: that is the no free lunch theorem in action, and why you compare on your own data.

Accuracy isn't everything

A model also has to be stored, run and explained. One simple measure of cost is how much a fitted model has to keep in order to predict:

Try it yourselfPython
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.naive_bayes import GaussianNB
from sklearn.neighbors import KNeighborsClassifier
from sklearn.tree import DecisionTreeClassifier

X, y = load_breast_cancer(return_X_y=True)

logreg = LogisticRegression(max_iter=5000).fit(X, y)
knn = KNeighborsClassifier().fit(X, y)
nb = GaussianNB().fit(X, y)
tree = DecisionTreeClassifier(max_depth=5, random_state=0).fit(X, y)
forest = RandomForestClassifier(n_estimators=100, random_state=0).fit(X, y)

print("What each fitted model has to keep in order to predict:")
print(f"   logistic regression: {logreg.coef_.size + logreg.intercept_.size} weights")
print(f"   Gaussian Naive Bayes: {nb.theta_.size + nb.var_.size + nb.class_prior_.size} averages, spreads and shares")
print(f"   decision tree:       {tree.tree_.node_count} nodes")
print(f"   random forest:       {sum(t.tree_.node_count for t in forest.estimators_)} nodes in 100 trees")
print(f"   k-nearest neighbours: all {X.size} numbers of the training data")
Output
What each fitted model has to keep in order to predict:
   logistic regression: 31 weights
   Gaussian Naive Bayes: 122 averages, spreads and shares
   decision tree:       35 nodes
   random forest:       4294 nodes in 100 trees
   k-nearest neighbours: all 17070 numbers of the training data

Logistic regression needs 31 numbers; the forest needs 4,294 tree nodes; k-NN keeps every one of the 17,070 numbers in the training data, and it grows with every new example. On the tumour data, logistic regression is the most accurate, the smallest, the fastest and the easiest to explain, so the choice is easy. When a big model is only slightly more accurate than a small one, the small one is often the better choice in practice.

Tuning the winner

Once you have a candidate, tune its hyperparameters. GridSearchCV tries every combination of the settings you list, scores each one with cross-validation, and keeps the best:

Try it yourselfPython
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import GridSearchCV
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

X, y = load_breast_cancer(return_X_y=True)
pipeline = make_pipeline(StandardScaler(), KNeighborsClassifier())

grid = {
    "kneighborsclassifier__n_neighbors": [3, 5, 11, 21],
    "kneighborsclassifier__weights": ["uniform", "distance"],
}
search = GridSearchCV(pipeline, grid, cv=5).fit(X, y)     # 8 settings x 5 folds
print("best settings:", search.best_params_)
print(f"best cross-validated accuracy: {search.best_score_:.3f}")
Output
best settings: {'kneighborsclassifier__n_neighbors': 11, 'kneighborsclassifier__weights': 'uniform'}
best cross-validated accuracy: 0.965

Four values of k times two weighting schemes make 8 settings, each scored on 5 folds: 40 fits. The best is k = 11 with plain voting. Two details:

  • The long names. The model sits inside a pipeline, so each setting is named after its step, then two underscores, then the parameter. make_pipeline names each step after its class in lower case.
  • The best score is a little optimistic, because it is the best of 8 tries on the same folds. After tuning, check the final model once on a test set you kept aside. When there are many settings to try, RandomizedSearchCV tests a random sample of combinations instead of all of them.

A practical recipe that works for most tabular problems:

  1. Agree on the metric, and measure a baseline (the next lesson).
  2. Try a regularised linear model.
  3. Try a tree ensemble: a random forest, then gradient boosting.
  4. Add candidates that suit the data: Naive Bayes for text, k-NN for small data with few features.
  5. Compare with cross-validation on the same folds, and look at the spread.
  6. Choose the simplest model within the noise of the best, thinking about speed, size and explanations.
  7. Tune it with GridSearchCV, then measure it once on the test set.

Common mistakes

Practice

Practice exercise

Summarise cross-validation results the way you would report them: the mean and spread of each model, best first.

Your solutionPython
import statistics

# 5-fold cross-validation accuracy of three models, on the same folds
results = {
    "logistic regression": [0.96, 0.98, 0.97, 0.99, 0.97],
    "k-nearest neighbours": [0.93, 0.96, 0.98, 0.96, 0.95],
    "random forest": [0.98, 0.94, 0.98, 0.96, 0.96],
}

# Print one line per model, best mean first, with the mean and the spread
# (statistics.pstdev) to three decimals, for example:
# some model            0.912 +/- 0.034
for name, scores in results.items():
    print(f"{name:<21} {0:.3f} +/- {0:.3f}")
Knowledge check

You have 20,000 rows of customer data in a table, you want the highest accuracy, and nobody needs an explanation of individual predictions. Which is usually the strongest candidate to try?

Summary

  • No algorithm is best for every problem: each family's assumptions suit some data and not others.
  • Narrow the field with questions about the kind of data, the need for explanations and probabilities, and limits on speed and size.
  • Compare candidates with cross-validation on the same folds, and treat differences smaller than the spread as ties.
  • Prefer the simplest model that is about as good as the best; it's cheaper to run and easier to explain.
  • Tune the winner with GridSearchCV (step name, two underscores, parameter), then check it once on the test set.

Next: Baselines, the simple yardsticks every model has to beat.

Finished reading? Tick it off to track your progress.