Hello! Welcome to the final lesson in our module on Tree-Based Models.
In our last lesson, we compared Random Forests and Gradient Boosting, establishing a framework for choosing between them based on trade-offs between performance, speed, and simplicity. We concluded that while these models are powerful, they are often perceived as "black boxes." Today, we will open those boxes.
This lesson directly addresses your goal of being able to explain why a model works. The learning outcome is to interpret feature importance scores generated by tree-based models. By the end of this lesson, you will understand several methods for measuring which features most influence your model's predictions, empowering you to justify your results and gain deeper insights from your data.
We will cover three main techniques, progressing from the simplest to the most sophisticated:
- Impurity-Based (Gini) Importance: The fast, default method in libraries like scikit-learn.
- Permutation Importance: A more robust, model-agnostic approach.
- SHAP Values: A state-of-the-art method based on game theory that provides both global and local explanations.
1. Why is Feature Importance Important?
Before diving into the methods, let's understand the benefits.
Understanding Feature Importance in Machine Learning
The article 'Understanding Feature Importance in Machine Learning' on Built In gives a concise overview of why this concept is so critical. It aligns perfectly with our goal of moving beyond just building models to understanding them.
Please read the sections 'What Is Feature Importance?' and 'Why Is Feature Importance Useful?'. Focus on the three key benefits it discusses.
As the article highlights, calculating feature importance helps with:
- Data Comprehension: Understanding the relationship between your input features and the target variable.
- Model Improvement: You can use importance scores for feature selection, potentially simplifying your model and improving its performance by removing irrelevant features (a form of dimensionality reduction).
- Model Interpretability: Explaining to stakeholders (or in an interview!) which factors are driving the model's decisions.
2. Method 1: Impurity-Based Feature Importance
This is the most common and fastest method for tree-based models. It's what scikit-learn's Random Forest and Gradient Boosting models provide by default through the .feature_importances_ attribute.
The Intuition:
In a decision tree, every split is chosen to maximize the decrease in node impurity (e.g., Gini impurity or entropy). A feature that consistently leads to large impurity reductions across many trees in the forest is considered important. The final score for a feature is the total reduction in impurity it provides, averaged over all trees in the ensemble.
Understanding Feature Importance in Machine Learning
Let's return to the 'Understanding Feature Importance' article, which explains how Gini Importance is calculated and provides a straightforward Python example.
Please read the subsection 'Gini Importance' and then follow the code in 'How to Calculate Feature Importance in Python'. You don't need to run the code yourself, but focus on how rf.feature_importances_ is used to get the scores and generate a plot.
Limitations of Impurity-Based Importance:
While fast and convenient, this method has significant drawbacks that you must be aware of.
Best Practice to Calculate and Interpret Model Feature Importance
The article 'Best Practice to Calculate and Interpret Model Feature Importance' from Towards Data Science provides a great critique of this default method.
Read the section 'The trouble with Default Feature Importance'. Pay close attention to the two main problems it identifies using the Titanic dataset example.
As the article demonstrates, impurity-based importance:
- Is biased towards high-cardinality features: It tends to inflate the importance of continuous variables or categorical variables with many unique values.
- Is unreliable on overfitting models: It is calculated on the training data, so if a model has overfit, the importance scores will reflect the noise the model has learned, not the true underlying signal.
Because of these issues, it's a good tool for a quick first look, but you should not rely on it for definitive conclusions.
3. Method 2: Permutation Feature Importance
Permutation importance is a more reliable and intuitive method that overcomes the limitations of impurity-based scores.
The Intuition:
The importance of a feature is measured by how much the model's performance drops when that feature's information is "destroyed." We do this by:
- Training a model and calculating a baseline score (e.g., accuracy) on a validation or test set.
- Taking one feature column and randomly shuffling its values. This breaks the relationship between that feature and the target variable, while keeping the feature's distribution the same.
- Calculating a new score using the model with the shuffled data.
- The feature's importance is the difference between the baseline score and the new score. A big drop means the feature was important.
This process is model-agnostic, meaning it can be used for any fitted model, not just tree-based ones.
The following video from Sebastian Raschka provides an excellent, code-first walkthrough of this technique.
13.4.3 Feature Permutation Importance Code Examples (L13: Feature Selection)
Let's watch a video by Sebastian Raschka that walks through computing and interpreting permutation importance. We'll focus on the core concepts and the comparison with impurity-based methods.
Please watch from the beginning up to 13:35. Pay close attention to: The setup and review of impurity-based importance (0:00 - 5:02). The explanation of how to compute permutation importance using scikit-learn (starts around 5:02, with the scikit-learn specific part at 12:03). The side-by-side comparison of the results (9:28). How the permutation importance values are interpreted as a direct drop in performance.
Here's a visual example of what the output of permutation importance looks like.

Key Advantages:
- More reliable: It is calculated on a hold-out set, so it reflects the model's true generalization performance.
- Interpretable score: The score is directly related to a performance metric (e.g., "shuffling feature X caused the accuracy to drop by 5%").
- Model-agnostic: Works for any type of model.
Test your understanding!
You have just used permutation importance and found that one feature has an importance score of approximately 0.0. Another feature has a negative importance score (e.g., -0.01). How would you interpret these two results?
Show answer
- Score of 0.0: The feature has no impact on the model's performance on the test set. Shuffling it didn't change the outcome. This feature is likely not useful and could be removed.
- Negative Score: Shuffling the feature actually improved the model's performance slightly. This suggests the model was learning some spurious, noisy patterns from this feature in the training data that were hurting its ability to generalize to the test set. This feature is a strong candidate for removal.
A Note on Correlated Features
A major challenge for all feature importance methods is multicollinearity. If two features are highly correlated and contain similar information, their importance will be "split" between them.
13.4.3 Feature Permutation Importance Code Examples (L13: Feature Selection)
Let's continue with Sebastian Raschka's video, where he provides a perfect illustration of how correlated features affect permutation importance.
Please watch from 17:09 to 25:30. He creates a synthetic dataset with two perfectly correlated features and shows how they share the importance score. This is a critical concept for correct interpretation.
How to handle this:
- Be aware: Before interpreting importance, always check for correlations between your top features (e.g., using a correlation heatmap).
- Group features: If features are highly correlated (e.g.,
house_size_sqftandnum_bedrooms), you can mentally group them and consider their combined importance. - Remove a feature: If two features are redundant, you could remove one and retrain the model to get a clearer importance score for the remaining one.
4. Method 3: SHAP (SHapley Additive exPlanations)
SHAP is a powerful, modern approach to model explainability based on a concept from cooperative game theory called Shapley values.
The Intuition:
Imagine a team of players (features) collaborating in a game to achieve a result (the model's prediction). Shapley values provide a way to fairly distribute the "payout" (the prediction) among the players based on their individual contributions to every possible sub-team (subset of features).
SHAP's key advantage is that it can provide both global importance (like the other methods) and local importance—explaining why an individual prediction was made.
Explainable AI explained! | #4 SHAP
The video 'Explainable AI explained! | #4 SHAP' from DeepFindr gives an excellent, non-mathematical introduction to the core idea behind SHAP.
Please watch the following segments: 0:04 - 3:52: This explains the game theory analogy and connects it to machine learning features. 7:28 - 14:57: This section shows how to use the shap library in Python. Focus on the types of plots it generates, especially the force plot (for local, single predictions) and the summary plot (for global feature importance).
For tree-based models like Random Forest and XGBoost, a highly optimized version called TreeSHAP exists, making these powerful explanations computationally feasible. SHAP values are considered the gold standard for model explainability today.
Conclusion
You've now learned how to go beyond just training a model to actually understanding what it has learned. This is a crucial skill that separates a good data scientist from a great one.
Key Takeaways:
- Impurity-Based (Gini) Importance: Fast and easy, but biased and unreliable for overfit models. Use it for a quick first look only.
- Permutation Importance: A robust, model-agnostic standard. Its scores are directly interpretable as a drop in model performance. This should be your go-to method for global feature importance.
- SHAP Values: The state-of-the-art method that provides both robust global importance and invaluable local explanations for individual predictions.
- Always be cautious with correlated features, as they can split their importance scores, potentially masking their true influence.
Preview of the Next Module:
This lesson concludes our module on Tree-Based Models and supervised learning for now. We will now shift gears into a different domain of machine learning: Unsupervised Learning. In the next module, we'll start by exploring how to find inherent structure in data without a target label, beginning with a powerful technique for dimensionality reduction called Principal Component Analysis (PCA).