Skip to content

Intermediate: machine learning · k-NN, decision trees and ensembles · topic 37 of 62 · 30 min

Choosing and explaining a model

Explanation

No single model is best for every problem. Choose by the data size, the need for explanations, speed and accuracy, and always compare with a baseline. Naive Bayes and SVMs are other classic options. Permutation importance and SHAP help explain which features drive a model's predictions.

There is no free lunch

The "no free lunch" idea says no algorithm wins on every problem. A model that is perfect for one dataset can be poor on another. So data scientists try a few sensible candidates, evaluate them fairly with cross-validation, and choose using both the score and practical needs.

Two more classic models

  • Naive Bayes: applies Bayes' theorem (module 3) and assumes features are independent given the class. The assumption is "naive", but it is fast and works well for text, such as spam filtering.
  • Support vector machines (SVM): find the boundary between classes with the widest margin (gap) to the nearest points. With kernels, they can draw curved boundaries. Strong on small and medium datasets; they need scaled features and get slow on very large ones.

A practical comparison

ModelExplainabilityNeeds scalingTypical strength
Linear / logistic regressionHigh (weights)Yes, for regularisationFast baseline; good when relationships are roughly linear
k-NNMedium ("similar cases")YesSmall data with odd-shaped boundaries
Decision treeHigh (flowchart)NoSimple rules people can follow
Random forestMediumNoStrong default with little tuning
Gradient boostingMedium (with tools)NoOften the most accurate on tabular data
Neural networkLowYesImages, audio, text and very large data

How to choose

  1. Start with a baseline and a simple model (logistic or linear regression).
  2. Try a tree ensemble (random forest or gradient boosting).
  3. Compare with cross-validation on the metric that matters.
  4. If scores are close, prefer the simpler, faster, more explainable model.
  5. Check practical limits: prediction speed, memory, how often it must be retrained, and whether regulators or users need explanations.

Explaining predictions

Permutation importance measures how much the model's score drops when one feature's values are shuffled, which breaks its link with the target. A big drop means the model relies on that feature. It works for any model and is computed on validation data. SHAP values go further and split each individual prediction into contributions from each feature, so you can say "this loan was declined mainly because of two missed EMIs and high existing debt".

python
from sklearn.inspection import permutation_importance

result = permutation_importance(model, X_val, y_val, n_repeats=10, random_state=0)
for i in result.importances_mean.argsort()[::-1][:5]:
    print(X_val.columns[i], round(result.importances_mean[i], 4))
Shown only. The SHAP library (pip install shap) gives per-prediction explanations.
Careful: Importance tells you what the model uses, not what causes the outcome in the real world. A model may rely on pin code because it is linked to income, which can also bring in unfair bias (module 12).

Common mistakes

  • Picking the fanciest model by default. Fix: let fair comparison decide.
  • Ignoring a 0.2-point gain that costs 10× more compute and no explainability.
  • Computing importance on training data, where overfit features look important. Fix: use validation data.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

Choosing and explaining a model · 1/7

No free lunch

No model is best for every problem. That is the no free lunch idea.

Prefer a video by a teacher? Find free videos on “how to choose machine learning model permutation importance shap explained” on YouTube ↗

In real life: Choosing a model for an insurance claim check

An insurer compares logistic regression, a random forest and gradient boosting for flagging claims that need manual review. Boosting is best by 1.5 points of recall at the same precision. Because claim decisions must be explained, the team ships boosting with SHAP explanations for every flagged claim, plus a monthly check that importance has not shifted to sensitive or proxy features.

Practice (0/2 done)

Task 1 · Code · Python

Write importance_ranking(base_score, shuffled_scores) where shuffled_scores is a dict mapping each feature to the model's score after that feature was shuffled. Return a list of (feature, drop) tuples, where drop = base_score − shuffled score rounded to 4 decimal places, sorted by drop from largest to smallest; ties by feature name A→Z.

Task 2 · Practice

A cooperative bank with 8,000 past loans wants to predict defaults. Loan officers must explain every rejection to members. Recommend which models to compare, how to compare them, and which one you would expect to choose if the scores are close. Give reasons.

Quick quiz

Question 1

1.What does the "no free lunch" idea say?

Question 2

2.Which model is classic and fast for spam filtering of text?

Question 3

3.Two models score 0.861 and 0.864 AUC; the first is a readable logistic regression, the second a large ensemble. Explanations are legally required. Which is usually better to ship?

Question 4

4.How is permutation importance computed?

Question 5

5.A model relies heavily on "pin code". What should you consider?

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

What does the "no free lunch" idea say?

Answer: No algorithm is best for every problem

You must compare candidates on your own data.

Which model is classic and fast for spam filtering of text?

Answer: Naive Bayes

Naive Bayes works well with word counts.

Two models score 0.861 and 0.864 AUC; the first is a readable logistic regression, the second a large ensemble. Explanations are legally required. Which is usually better to ship?

Answer: The logistic regression

A tiny gain rarely justifies losing explainability when it is required.

How is permutation importance computed?

Answer: Shuffling one feature and measuring how much the model's score drops

Breaking a feature's link with the target shows how much the model relies on it.

A model relies heavily on "pin code". What should you consider?

Answer: Whether pin code is a proxy for sensitive traits such as income or community, which may cause unfair results

Proxy features can bring bias into decisions (module 12).

97% of transactions are not fraud. A model has 97% accuracy. What should you conclude?Related

Answer: It may be no better than always predicting "not fraud"

The majority-class baseline already scores 97%.

From The ML workflow end to end

How many permutations do 5 distinct items have?Related

Answer: 120

5! = 5 × 4 × 3 × 2 × 1 = 120.

From Backtracking: subsets and permutations

A model scores 99.8% on the test set for a hard real-world task. What should you do first?Related

Answer: Look for leakage

Scores that are too good usually mean the answer leaked into the features.

From Train, validation and test sets

In Bayes' theorem, what is the prior?Related

Answer: How common the condition is before you see the evidence

The prior is the starting belief, the base rate, before the new evidence is used.

From Conditional probability and Bayes' theorem

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. This is the last topic of “k-NN, decision trees and ensembles”. The module exam comes next.
  2. Module 7 exam: k-NN, decision trees and ensembles · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
  3. Then the next module, Clustering, dimensionality reduction and feature engineering. 62 topics left in the course before the final exam.

← Previous: Gradient boosting