Intermediate: machine learning · k-NN, decision trees and ensembles · topic 37 of 62 · 30 min
Choosing and explaining a model
Explanation
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
| Model | Explainability | Needs scaling | Typical strength |
|---|---|---|---|
| Linear / logistic regression | High (weights) | Yes, for regularisation | Fast baseline; good when relationships are roughly linear |
| k-NN | Medium ("similar cases") | Yes | Small data with odd-shaped boundaries |
| Decision tree | High (flowchart) | No | Simple rules people can follow |
| Random forest | Medium | No | Strong default with little tuning |
| Gradient boosting | Medium (with tools) | No | Often the most accurate on tabular data |
| Neural network | Low | Yes | Images, audio, text and very large data |
How to choose
- Start with a baseline and a simple model (logistic or linear regression).
- Try a tree ensemble (random forest or gradient boosting).
- Compare with cross-validation on the metric that matters.
- If scores are close, prefer the simpler, faster, more explainable model.
- 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".
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))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 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)
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.
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
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Random forests and baggingk-NN, decision trees and ensembles · same module
- Decision treesk-NN, decision trees and ensembles · same module
- Backtracking: subsets and permutationsData Structures and Algorithms (DSA) for interviews · Recursion and backtracking
- Conditional probability and Bayes' theoremProbability and inference
- Regression metrics: MAE, MSE, RMSE and R²Evaluating models
- Bag of words, TF-IDF and text classificationNLP, embeddings and large language models
Questions people ask about this
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%.
How many permutations do 5 distinct items have?Related
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.
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.
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
- This is the last topic of “k-NN, decision trees and ensembles”. The module exam comes next.
- Module 7 exam: k-NN, decision trees and ensembles · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
- Then the next module, Clustering, dimensionality reduction and feature engineering. 62 topics left in the course before the final exam.