Global Model-Agnostic Interpretation Methods
local graph
Chapter 4 — Global Model-Agnostic Interpretation Methods
Section titled “Chapter 4 — Global Model-Agnostic Interpretation Methods”In the first part of this book, we introduced the concepts, challenges, and purpose of machine learning interpretation. This chapter kicks off the second part, which dives into a vast array of methods that are used to diagnose models and understand their underlying data. One of the biggest questions answered by interpretation methods is: What matters most to the model and how does it matter? Interpretation methods can shed light on the overall importance of features and how they—individually or combined—impact a model’s outcome. This chapter will provide a theoretical and practical foundation to approach these questions.
Initially, we will explore the notion of feature importance by examining the model’s inherent parameters. Following that, we will study how to employ permutation feature importance in a model-agnostic manner to effectively, reliably, and autonomously rank features. Finally, we will outline how SHapley Additive exPlanations (SHAP) can rectify some of the shortcomings of permutation feature importance.
This chapter will look at several ways to visualize global explanations, such as SHAP’s bar and beeswarm plots, and then dive into feature-specific visualizations like Partial Dependence Plots (PDP) and Accumulated Local Effect (ALE) plots. Lastly, feature interactions can enrich explanations because features often team up, so we will discuss 2-dimensional PDP and ALE plots.
The following are the main topics we are going to cover in this chapter:
- What is feature importance?
- Gauging feature importance with model-agnostic methods
- Using SHAP, PDP, and ALE plots to visualize:
- Global explanations
- Feature summary explanations
- Feature interactions
- Global explanations
Technical requirements
Section titled “Technical requirements”This chapter’s example uses the pandas, numpy, sklearn, catboost, seaborn, matplotlib, shap, pdpbox, and pyale libraries. Instructions on how to install all of these libraries are in the GitHub repository README.md file.
The code for this chapter is located here: https://packt.link/Ty0Ev
The mission
Section titled “The mission”The used car market in the United States is a thriving and substantial industry with significant economic impact. In recent years, approximately 40 million used light vehicles have been sold yearly, representing over two-thirds of the overall yearly sales in the automotive sector. In addition, the market has witnessed consistent growth, driven by the rising cost of new vehicles, longer-lasting cars, and an increasing consumer preference for pre-owned vehicles due to the perception of value for money. As a result, this market segment has become increasingly important for businesses and consumers.
Given the market opportunity, a tech startup is currently working on a machine-learning-driven, two-sided marketplace for used car sales. It plans to work much like the e-commerce site eBay, except it’s focused on cars. For example, sellers can list their cars at a fixed price or auction them, and buyers can either pay the higher fixed price or participate in the auction, but how do you come up with a starting point for the price? Typically, sellers define the price, but the site can generate an optimal price that maximizes the overall value for all participants, ensuring that the platform remains attractive and sustainable in the long run.
Optimal pricing is not a simple solution since it has to maintain a healthy balance between the number of buyers and sellers on the platform while being perceived as fair by both buyers and sellers. It remains competitive with other platforms while being profitable. However, it all starts with a price prediction model that can estimate the fair value, and then, from there, it can incorporate other models and constraints to adjust it. To that end, one of the startup’s data scientists has obtained a dataset of used car listings from Craigslist and merged it with other sources, such as the U.S. Census Bureau for demographic data and the Environmental Protection Agency (EPA) for emissions data. The idea is to train a model with this dataset, but we are unsure what features are helpful. And that’s where you come in!
You have been hired to explain which features are useful to the machine learning model and why. This is critical because the startup only wants to ask sellers to provide the bare minimum of details about their car before they get a price estimate. Of course, there are details like the car’s make and model and even the color that another machine learning model can automatically guess from the pictures. Still, some features like the transmission or cylinders may vary in the car model, and the seller may not know or be willing to disclose them. Limiting the questions asked produces the least friction and thus will lead to more sellers completing their listings successfully.
The approach
Section titled “The approach”You have decided to take the following steps:
- Train a couple of models.
- Evaluate them.
- Create feature importance values using several methods, both model-specific and model-agnostic.
- Plot global summaries, feature summaries, and feature interaction plots to understand how these features relate to the outcome and each other.
The plots will help you communicate findings to the tech startup executives and your data science colleagues.
The preparations
Section titled “The preparations”You will find the code for this example here: https://github.com/PacktPublishing/Interpretable-Machine-Learning-with-Python-2E/tree/main/04/UsedCars.ipynb
Loading the libraries
Section titled “Loading the libraries”To run this example, you need to install the following libraries:
mldatasetsto load the datasetpandasandnumpyto manipulate itsklearn(scikit-learn) andcatboostto load and configure the modelmatplotlib,seaborn,shap,pdpbox, andpyaleto generate and visualize the model interpretations
You should load all of them first:
import mathimport os, randomimport numpy as npimport pandas as pdimport mldatasetsfrom sklearn import metrics, ensemble, tree, inspection,model_selectionimport catboost as cbimport matplotlib.pyplot as pltimport seaborn as snsimport shapfrom pdpbox import pdp, info_plotsfrom PyALE import alefrom lime.lime_tabular import LimeTabularExplainerThe following snippet of code will load the usedcars dataset:
usedcars_df = mldatasets.load(“usedcars”, prepare=True)
You can inspect it using the usedcars_df.info() function and verify that there are indeed over 256,000 rows and 29 columns with no nulls. Some of them are object data types because they are categorical.
The data dictionary for the dataset is as follows:
- Variables related to the listing:
price: target, continuous, the price posted for the vehicleregion: categorical, the region for the listing—usually this is a city, metropolitan area, or (for more rural areas) a portion of a state or a least populated state (out of 402)posting_date: datetime, the date and time of the posting (all postings are for a single month period in 2021 so you cannot observe seasonal patterns with it)lat: continuous, the latitude in decimal formatlong: continuous, the longitude in decimal formatstate: categorical, the two-letter state code (out of 51 including [DC])city: categorical, the name of the city (out of over 6,700)zip: nominal, the zip code (out of over 13,100)
- Variables related to the vehicle:
make: categorical, the brand or manufacturer of the vehicle (out of 37)make_cat: categorical, the category for the make (out of 5). It’s [obsolete] for makes no longer produced, such as “Saturn,” [luxury sports] for brands like “Ferrari,” and [luxury] for brands like “Mercedes-Benz.” Everything else is [regular] or [premium]. The only difference is that [premium] include brands like “Cadillac” and “Acura,” which are the high-end brands of car manufacturers in the [regular] category.make_pop: continuous, the relative popularity of the make in percentiles (0–1)model: categorical, the model (out of over 17,000)model_premier: binary, whether the model is a luxury version/trim of a model (if the model itself is not already high-end such as those in the luxury, luxury sports, or premium categories)year: ordinal, the year of the model (from 1984–2022)make_yr_pop: continuous, the relative popularity of the make for the year it was made for in percentiles (0–1)model_yr_pop: continuous, the relative popularity of the model for the year it was made in percentiles (0–1)odometer: continuous, the reading in the vehicle’s odometerauto_trans: binary, whether the car has automatic transmission—otherwise, it is manualfuel: categorical, the type of fuel used (out of 5: [gas], [diesel], [hybrid], [electric] and [other])model_type: categorical (out of 13: [sedan], [SUV], and [pickup] are the three most popular, by far)drive: categorical, whether it’s four-wheel, front-wheel, or rear-wheel drive (out of 3: [4wd], [fwd] and [rwd])cylinders: nominal, the number of cylinders of the engine (from 2–16). Generally, the more cylinders, the higher the horsepowertitle_status: categorical, what the title says about the status of the vehicle (out of 7 like [clean], [rebuilt], [unknown], [salvage], and [lien])condition: categorical, what the owner reported the condition of the vehicle to be (out of 7 like [good], [unknown], [excellent] and [like new])
- Variables related to the emissions of the vehicle:
epa_co2: continuous, tailpipe CO2 in grams/mile. For models after 2013, it is based on EPA tests. For previous years, CO2 is estimated using an EPA emission factor (-1= not vvailable)epa_displ: continuous, the engine displacement (in liters 0.6–8.4)
- Variables related to the ZIP code of the listing:
zip_population: continuous, the populationzip_density: continuous, the density (residents per sq. mile)est_households_medianincome_usd: continuous, the median household income
Data preparation
Section titled “Data preparation”We should apply categorical encoding to them so that there’s one column per category, but only if the category has at least 500 records. We can do this with the make_dummies_with_limits utility function. But first, let’s back up the original dataset:
usedcars_orig_df = usedcars_df.copy()usedcars_df = mldatasets.make_dummies_with_limits(usedcars_df,'fuel',min_recs=500,defcatname='other')usedcars_df = mldatasets.make_dummies_with_limits(usedcars_df,'make_cat')usedcars_df = mldatasets.make_dummies_with_limits(usedcars_df,'model_type',min_recs=500,defcatname='other')usedcars_df = mldatasets.make_dummies_with_limits(usedcars_df,'condition',min_recs=200,defcatname='other')usedcars_df = mldatasets.make_dummies_with_limits(usedcars_df,'drive')usedcars_df = mldatasets.make_dummies_with_limits(usedcars_df,'title_status',min_recs=500,defcatname='other')The above snippet got rid of many object columns by turning them into a series of binary columns (of the uint8 type). However, there are still a few object columns left. We can find out which ones like this:
usedcars_df.dtypes[lambda x: x == object].index.tolist()
We don’t need any of these columns since we have latitude, longitude, and some of the demographic features, which provide the model with some idea of where the car was being sold. As for the make and model, we have the make and model popularity and category features. We can remove the non-numerical features by simply only selecting the numerical ones like this:
usedcars_df = usedcars_df.select_dtypes(include=(int,float,np.uint8))The final data preparation steps are to:
- Define our random seed (
rand) to ensure reproducibility. - Split data into
X(features) andy(labels). The former has all columns except for the target variable (target_col). The latter is only the target. - Lastly, divide both
Xandyinto train and test components randomly using scikit-learn’strain_test_splitfunction:
rand = 42os.environ['PYTHONHASHSEED']=str(rand)np.random.seed(rand)random.seed(rand)target_col = 'price'X = usedcars_df.drop([target_col], axis=1)y = usedcars_df[target_col]X_train, X_test, y_train, y_test = model_selection.train_test_split(X, y, test_size=0.25, random_state=rand)Now we have everything to move forward so we will go ahead with some model training!
Model training and evaluation
Section titled “Model training and evaluation”The following code snippet will train two classifiers, CatBoost and Random Forest:
cb_mdl = cb.CatBoostRegressor(depth=7, learning_rate=0.2, random_state=rand, verbose=False)cb_mdl = cb_mdl.fit(X_train, y_train)rf_mdl =ensemble.RandomForestRegressor(n_jobs=-1,random_state=rand)rf_mdl = rf_mdl.fit(X_train.to_numpy(), y_train.to_numpy())Next, we can evaluate the CatBoost model using a regression plot, and a few metrics. Run the following code, which will output Figure 4.1:
mdl = cb_mdly_train_pred, y_test_pred = mldatasets.evaluate_reg_mdl(mdl, X_train, X_test, y_train, y_test)The CatBoost model produced a high R-squared of 0.94 and a test RMSE of nearly 3,100. The regression plot in Figure 4.1 tells us that although there are quite a few cases that have an extremely high error, the vast majority of the 64,000 test samples were predicted fairly well. You can confirm this by running the following code:
thresh = 4000pct_under = np.where(np.abs(y_test - y_test_pred) < thresh, 1, 0).sum() / len(y_test) print(f”Percentage of test samples under ${thresh:,.0f} in absolute error {pct_under:.1%}”)
It says that the percentage of test samples with an absolute error in the $4,000 range is nearly 90%. Granted it’s a large margin of error for cars that cost a few thousand, but we just want to get a sense of how accurate the model is. We will likely need to improve it for production, but for now, it will do for the exercise requested by the tech startup:

Figure 4.1: CatBoost model predictive performance
So now let’s repeat the same evaluation for the Random Forest model (rf_mdl). To do this, we must run the same snippet but simply replace cb_mdl with rf_mdl in the first line.
The Random Forest performs just as well for the test samples, and its metrics are remarkably similar to CatBoost, except it overfits much more in this case. This matters because we will now compare some feature importance methods on both and don’t want differences in predictive performance to be a reason to doubt any findings.
What is feature importance?
Section titled “What is feature importance?”Feature importance refers to the extent to which each feature contributes to the final output of a model. For linear models, it’s easier to determine the importance since coefficients clearly indicate the contributions of each feature. However, this isn’t always the case for non-linear models.
To simplify the concept, let’s compare model classes to various team sports. In some sports, it’s easy to identify the players who have the greatest impact on the outcome, while in others, it isn’t. Let’s consider two sports as examples:
- Relay race: In this sport, each runner covers equal distances, and the race’s outcome largely depends on the speed at which they complete their part. Thus, it’s easy to separate and quantify each racer’s contributions. A relay race is similar to a linear model since the race’s outcome is a linear combination of independent components.
- Basketball: In this game, players have distinct roles, and comparing them using the same metrics is not possible. Moreover, the varying game conditions and player interactions can significantly affect their contributions to the outcome. So, how can we measure and rank each player’s contributions?
Models possess inherent parameters that can occasionally aid in unraveling the contributions of each feature. We’ve trained two models. How have their intrinsic parameters been used to calculate feature importance?
Let’s begin with Random Forest. If you plot one of its estimators with the following code, it will generate Figure 4.2. Because each estimator is up to six levels deep, we will plot only up to the second level (max_depth=2) because, otherwise, the text would be too small. But feel free to increase the max_depth:
tree.plot_tree(rf_mdl.estimators_[0], filled=True, max_depth=2,
feature_names=X_train.columns)
Notice the squared_error and samples in each node of the estimator in Figure 4.2. By dividing these numbers, you can calculate the Mean Squared Error (MSE). Although for classifiers, it’s the Gini coefficient, for regressors, MSE is the impurity measure. It’s expected to decrease as you go deeper in the tree, so the sum of these weighted impurity decreases is calculated for each feature throughout the tree. How much a feature decreases node impurity indicates how much it contributes to the model’s outcome. This would be a model-specific method since it can’t be used with linear models or neural networks, but this is precisely how tree-based models compute feature importance. Random Forest is no different. However, it’s an ensemble, so it has a collection of estimators, so the feature importance is the mean decrease in impurity across all estimators.

Figure 4.2: First level for the first estimator of the Random Forest model
We can obtain and print the feature importance values for the Random Forest model with the following snippet:
rf_feat_imp = rf_mdl.feature_importances_print(rf_feat_imp)Note that since they have been normalized, they add up to 1 (sum(rf_feat_imp)).
CatBoost uses a different method, by default, to compute feature importance, called PredictionValuesChange. It shows how much, on average, the model outcome changes if the feature value changes. It traverses the tree performing a weighted average of feature contributions according to the number of nodes in each branch (left or right). If it encounters a combination of features in a node, it evenly assigns contributions to each one. As a result, it can yield misleading feature importance values for features that usually interact with one another.
You can also retrieve the CatBoost feature importances with feature_importances_ like this, and unlike Random Forest, they add up to 100 and not 1:
cb_feat_imp = cb_mdl.feature_importances_print(cb_feat_imp)Now, let’s put them side by side in a pandas DataFrame. We will multiply the Random Forest feature importances (rf_feat_imp) times 100 to be on the same scale as CatBoost’s. Then we will sort by cb_feat_imp and format so that there’s a nice bar chart embedded in our DataFrame. The result of the following snippet is in Figure 4.3:
feat_imp_df = pd.DataFrame( { 'feature':X_train.columns, 'cb_feat_imp':cb_feat_imp, 'rf_feat_imp':rf_feat_imp*100 })feat_imp_df = feat_imp_df.sort_values('cb_feat_imp', ascending=False)feat_imp_df.style.format( '{:.2f}%', subset=['cb_feat_imp', 'rf_feat_imp']) .bar(subset=['cb_feat_imp', 'rf_feat_imp'], color='#4EF', width=60)Notice that both models have the same most important feature in Figure 4.3. The top ten features are mostly the same but not in the same rank. In particular, odometer appears to be much more important for CatBoost than for Random Forest. Also, all the other features don’t match up in ranking except for the least important ones, for which there’s a consensus that they are indeed last:

Figure 4.3: Compare both models’ feature importance values
How can we address these differences and employ a technique that consistently represents a feature’s importance? We will explore this using model-agnostic approaches.
Assessing feature importance with model-agnostic methods
Section titled “Assessing feature importance with model-agnostic methods”Model-agnostic methods imply that we will not depend on intrinsic model parameters to compute feature importance. Instead, we will consider the model as a black box, with only the inputs and output visible. So, how can we determine which inputs made a difference?
What if we altered the inputs randomly? Indeed, one of the most effective methods for evaluating feature importance is through simulations designed to measure a feature’s impact or lack thereof. In other words, let’s remove a random player from the game and observe the outcome! In this section, we will discuss two ways to achieve this: permutation feature importance and SHAP.
Permutation feature importance
Section titled “Permutation feature importance”Once we have a trained model, we cannot remove a feature to assess the impact of not using it. However, we can:
- Replace the feature with a static value, such as the mean or median, rendering it devoid of useful information.
- Shuffle (permute) the feature values to disrupt the relationship between the feature and the outcome.
Permutation feature importance (permutation_importance) uses the second strategy with a test dataset. Then it measures a change in the score (MSE, r2, f1, accuracy, etc.). In this case, a substantial decrease in the negative Mean Absolute Error (MAE) when the feature is shuffled would suggest that the feature has a high influence on the prediction. It would have to repeat the shuffling several times (n_repeats) to arrive at conclusive results by averaging out the decreases in accuracy. Please note the default scorer for Random Forest regressors is R-squared, while it’s RMSE for CatBoost, so we are making sure they both use the same scorer by setting the scoring parameter. The following code does all of this for both models:
cb_perm_imp = inspection.permutation_importance( cb_mdl, X_test, y_test, n_repeats=10, random_state=rand,\ scoring='neg_mean_absolute_error')rf_perm_imp = inspection.permutation_importance( rf_mdl, X_test.to_numpy(), y_test.to_numpy(), n_repeats=10,\ random_state=rand, scoring='neg_mean_absolute_error')The method outputs a mean score (importances_mean) and a standard deviation (importances_std) across all repeats for each model, which we can place in a pandas DataFrame, sort, and format, as we did before with feature importance. The following code generates the table in Figure 4.4:
perm_imp_df = pd.DataFrame( { 'feature':X_train.columns, 'cb_perm_mean':cb_perm_imp.importances_mean, 'cb_perm_std':cb_perm_imp.importances_std, 'rf_perm_mean':rf_perm_imp.importances_mean, 'rf_perm_std':rf_perm_imp.importances_std })perm_imp_df = perm_imp_df.sort_values( 'cb_perm_mean', ascending=False)perm_imp_df.style.format( '{:.4f}', subset=['cb_perm_mean', 'cb_perm_std', 'rf_perm_mean', 'rf_perm_std']).bar(subset=['cb_perm_mean', 'rf_perm_mean'],\ color='#4EF', width=60)The first four features for both models in Figure 4.4 are much more consistent than Figure 4.3—not that they have to be because they are different models! However, it makes sense considering they were derived from the same method. There are considerable differences too. Random Forest seems to rely much more heavily on fewer features, but these features might not be as necessary if they achieve a very similar predictive performance as CatBoost:

Figure 4.4: Compare both models’ permutation feature importance values
Permutation feature importance can be understood as the average increase in model error when a feature is made irrelevant, along with its interactions with other features. It is relatively fast to compute since models don’t need to be retrained, but its specific value should be taken with a grain of salt because there are some drawbacks to this shuffling technique:
- Shuffling a highly correlated feature with another unshuffled feature may not significantly affect predictive performance, as the unshuffled feature retains some information from the shuffled one. This means it cannot accurately assess the importance of multicollinear features.
- Shuffling can lead to unrealistic observations, like predicting vehicle traffic with weather and ending up with winter temperatures during the summer. This will result in a higher predictive error for a model that has never encountered such examples, overstating the importance scores beyond their actual significance.
Therefore, these importance values are only useful to rank the features and gauge their relative importance against other features in a particular model. We will now explore how Shapley values can help address these issues.
SHAP values
Section titled “SHAP values”Before delving into SHAP values, we should discuss Shapley values. SHAP is an implementation of Shapley values that takes some liberties but maintains many of the same properties.
It’s appropriate that we’ve been discussing feature importance within the context of games, as Shapley values are rooted in cooperative game theory. In this context, players form different sets called coalitions, and when they play, they get varying scores known as marginal contributions. The Shapley value is the average of these contributions across multiple simulations. In terms of feature importance, players represent features, sets of players symbolize sets of features, and marginal contribution is related to a decrease in predictive error.
This approach may seem similar to permutation feature importance, but its focus on feature combinations rather than individual features helps tackle the multicollinear issue. Moreover, the values obtained through this method satisfy several favorable mathematical properties, such as:
- Additivity: the sum of the parts adds to the total value
- Symmetry: consistent values for equal contributions
- Efficiency: equal to the difference between the prediction and expected value
- Dummy: a value of zero for features with no impact on the outcome
In practice, this method demands substantial computational resources. For instance, five features yield
possible coalitions, while 15 features result in 32,768. Therefore, most Shapley implementations use shortcuts like Monte Carlo sampling or leveraging the model’s intrinsic parameters (which makes them model-specific). The SHAP library employs various strategies to reduce computational load without sacrificing Shapley properties too much.
Comprehensive explanations with KernelExplainer
Section titled “Comprehensive explanations with KernelExplainer”Within SHAP, the most prevalent model-agnostic approach is KernelExplainer, which is based on Local Interpretable Model-agnostic Explanations (LIME). Don’t fret if you don’t understand the specifics since we will cover it in detail in Chapter 5, Local Model-Agnostic Interpretation Methods. To cut down on computation, it employs sample coalitions. In addition, it follows the same procedures as LIME, such as fitting weighted linear models, but employs Shapley sample coalitions and a different kernel that returns SHAP values as coefficients.
KernelExplainer can be initialized with a kmeans background sample of the training dataset (X_train_summary), which helps it define the kernels. It can be still slow. Therefore, it’s better not to use large datasets to compute the shap_values. Instead, in the following code, we are using only 2% of the test dataset (X_test_sample):
rf_fn = lambda x: rf_mdl.predict(x)X_train_summary = shap.kmeans(X_train.to_numpy(), 50)X_test_sample = X_test.sample(frac=0.02)rf_kernel_explainer = shap.KernelExplainer(rf_fn, X_train_summary)rf_shap_values = rf_kernel_explainer.shap_values( X_test_sample.to_numpy())It might take a while to run the whole thing. Should it take too long, feel free to reduce the sample size from 0.02 to 0.005. SHAP values will be less reliable but it’s just an example so you can get a taste of KernelExplainer.
Once it completes, please run print(rf_shap_values.shape) to get an idea of the dimensions we’ll be dealing with. Note that it’s two dimensions! There’s one SHAP value per observation x feature. For this reason, SHAP values can be used for both global and local interpretation. Put a pin in that! We will cover the local interpretation in the next chapter. For now, we will look at another SHAP explainer.
Faster explanations with TreeExplainer
Section titled “Faster explanations with TreeExplainer”TreeExplainer was designed to efficiently estimate SHAP values for tree-based models such as XGBoost, Random Forest, and CART decision trees. It can allocate non-zero values to non-influential features because it employs the conditional expectation value function rather than marginal expectation, violating the Shapley dummy property. This can have consequences when features are collinear, potentially making explanations less reliable. However, it adheres to other properties.
You can obtain the SHAP values with TreeExplainer like this:
cb_tree_explainer = shap.TreeExplainer(cb_mdl)cb_shap_values = cb_tree_explainer.shap_values(X_test)As you can tell, it’s easier and much quicker. It also outputs a two-dimensional array like KernelExplainer. You can check with print(cb_shap_values.shape).
For feature importance values, we can collapse two dimensions into one. All we need to do is average the absolute value per feature like this:
cb_shap_imp = np.mean(np.abs(cb_shap_values),0)For Random Forest, just replace the cb_ for rf_ with the same code.
We can now compare both SHAP feature importances side-by-side using a formatted and sorted pandas DataFrame. The following code will generate the table in Figure 4.5.
shap_imp_df = pd.DataFrame( { 'feature':X_train.columns, 'cb_shap_imp':cb_shap_imp, 'rf_shap_imp':rf_shap_imp })shap_imp_df = shap_imp_df.sort_values('cb_shap_imp', ascending=False)shap_imp_df.style.format( '{:.4f}', subset=['cb_shap_imp', 'rf_shap_imp']).bar( subset=['cb_shap_imp', 'rf_shap_imp'], color='#4EF', width=60)Figure 4.5 not only compares feature importance for two different models but also for two different SHAP explainers. They aren’t necessarily perfect depictions, but they are both to be trusted more than permutation feature importance:

Figure 4.5: Compare both models’ SHAP feature importance values
SHAP for both models suggest that loan_to_value_ratio and make_cat_va importances were previously deflated. This makes sense because loan_to_value_ratio is highly correlated with several of the top features and make_cat_va with all the other product-type features.
Visualize global explanations
Section titled “Visualize global explanations”Previously, we covered the concept of global explanations and SHAP values. But we didn’t demonstrate the many ways we can visualize them. As you will learn, SHAP values are very versatile and can be used to examine much more than feature importance!
But first, we must initialize a SHAP explainer. In the previous chapter, we generated the SHAP values using shap.TreeExplainer and shap.KernelExplainer. This time, we will use SHAP’s newer interface, which simplifies the process by saving SHAP values and corresponding data in a single object and much more! Instead of explicitly defining the type of explainer, you initialize it with shap.Explainer(model), which returns the callable object. Then, you load your test dataset (X_test) into the callable Explainer, and it returns an Explanation object:
cb_explainer = shap.Explainer(cb_mdl)cb_shap = cb_explainer(X_test)In case you are wondering, how did it know what kind of explainer to create? Glad you asked! There’s an optional parameter called algorithm in the initialization function, and you can explicitly define tree, linear, additive, kernel, and others. But by default, it is set to auto, which means it will guess which kind of explainer is needed for the model. In this case, CatBoost is a tree ensemble, so tree is what makes sense. We can easily check that SHAP chose the right explainer with cb_explainer.[dict]{custom-style="P - Italics"}[ or ]print(type(cb_explainer)). It will return <class 'shap.explainers._tree.Tree'>, which is correct! As for the explanation stored in cb_shap, what is it exactly? It’s an object that contains pretty much everything that is needed to plot explanations, such as the SHAP values (cb_shap.values) and corresponding dataset (cb_shap.data). They should be exactly the same dimensions because there’s one SHAP value for every data point. It’s easy to verify this by checking their dimensions with the shape property:
print("Values dimensions: %s" % (cb_shap.values.shape,))print("Data dimensions: %s" % (cb_shap.data.shape,))Now, let’s put these values to some use!
SHAP bar plot
Section titled “SHAP bar plot”Let’s start with the most straightforward global explanation visualizations we can do, which is feature importance. You can do this with a bar chart (shap.plots.bar). All it needs is the explanation object (cb_shap), but by default, it will only display 10 bars. Fortunately, we can change this with max_display:
shap.plots.bar(cb_shap, max_display=15)The preceding snippet will generate Figure 4.6:

Figure 4.6: CatBoost model’s SHAP feature importance
Figure 4.6 should look very familiar if you read the previous chapter. In fact, it should match the cb_shap_imp column in Figure 4.5.
SHAP feature importance offers considerable flexibility since it is simply the average of the absolute value of SHAP values for each feature. With the granularity of SHAP values, you can dissect them in the same way as the test dataset to obtain insights across various dimensions. This reveals more about feature importance than a single average for each feature.
For example, you can compare feature importance across different groups. Suppose we want to explore how feature importance differs between year cohorts. First, we need a threshold to define. Let’s use 2014 because it’s the median year in our dataset. Values above that can be set in the “Newer Car” cohort and pre-2014 values set to “Older Car.” Then, use np.where to create an array assigning the cohorts to each observation. To create the bar chart, repeat the previous process but use the cohorts function to split the explanation, applying the absolute value (abs) and mean operations to each cohort.
yr_cohort = np.where( X_test.year > 2014, "Newer Car", "Older Car")shap.plots.bar(cb_shap.cohorts(yr_cohort).abs.mean(0))This code snippet produces Figure 4.7:

Figure 4.7: CatBoost model’s SHAP feature importance split by property value cohorts
As you can see in Figure 4.7, all the top features matter less for “Older cars.” One of the biggest differences is with year itself. When a car is older, how much older doesn’t matter as much as when it’s in the “Newer Car” cohort.
SHAP beeswarm plot
Section titled “SHAP beeswarm plot”Bar charts can obscure some aspects of how features affect model outcomes. Not only do different feature values have varying impacts, but their distribution across all observations can also exhibit considerable variation. The beeswarm plot aims to provide more insight by using dots to represent each observation for every individual feature, even though features are ordered by global feature importance:
- Dots are color-coded based on their position in the range of low to high values for each feature.
- Dots are arranged horizontally according to their impact on the outcome, centered on the line where SHAP value = 0, with negative impacts on the left and positive impacts on the right.
- Dots accumulate vertically, creating a histogram-like visualization to display the number of observations influencing the outcome at every impact level for each feature.
To better understand this, we’ll create a beeswarm plot. Generating the plot is easy with the shap.plots.beeswarm function. It only requires the explanation object (cb_shap), and, as with the bar plot, we’ll override the default max_display to show only 15 features:
shap.plots.beeswarm(cb_shap, max_display=15)The result of the preceding code is in Figure 4.8:

Figure 4.8: The CatBoost model’s SHAP beeswarm plot
Figure 4.8 can be read as follows:
- The most important feature (of the 15) from top to bottom is
yearand the least is longitude (long). It should match the same order in the bar chart or if you take the average absolute values of the SHAP values across every feature. - Low values for
yearnegatively impact the model outcome, while high values impact it positively. There’s a nice clean gradient in between, suggesting an increasing monotonic relationship betweenyearand the predictedprice. That is, the higher theyear, the higher thepriceaccording to the CatBoost model. odometerhas a negative or negligible impact on a sizable portion of the observations. However, it has a long tail of observations for which it has a sizable impact. You can tell this by looking at the density depicted vertically.- If you scan the rest of the plot looking for other continuous features, you won’t find such a clean gradient anywhere else as you did for
yearandodometerbut you’ll find some trends like higher values ofmake_yr_popandmodel_yr_pophaving mostly a negative impact. - For binary features, it is easy to tell because you only have two colors, and they are sometimes neatly split, as with
model_premier,model_type_pickup,drive_fwd,make_cat_regular, andfuel_diesel, demonstrating how a certain kind of vehicle might be a tell-tale sign for the model whether it is high priced or not. In this case, a pick-up model increases the price, whereas a vehicle with a regular make—that is, a brand that is not luxury—decreases the price.
While the beeswarm plot offers an excellent summary of many findings, it can sometimes be challenging to interpret, and it doesn’t capture everything. The color-coding is useful for illustrating the relationship between feature values and model output, but what if you want more detail? That’s where the partial dependence plot comes in. It’s among the many feature summary explanations that provide a global interpretation method specific to features.
Feature summary explanations
Section titled “Feature summary explanations”This section will cover a number of methods used to visualize how an individual feature impacts the outcome.
Partial dependence plots
Section titled “Partial dependence plots”Partial Dependence Plots (PDPs) display a feature’s relationship with the outcome according to the model. In essence, the PDP illustrates the marginal effect of a feature on the model’s predicted output across all possible values of that feature.
The calculation involves two steps:
- Initially, conduct a simulation where the feature value for each observation is altered to a range of different values, and predict the model using those values. For example, if the
yearvaries between 1984 and 2022, create copies of each observation withyearvalues ranging between these two numbers. Then, run the model using these values. This first step can be plotted as the Individual Conditional Expectation (ICE) plot, with simulated values foryearon the X-axis and the model output on the Y-axis, and one line per simulated observation. - In the second step, simply average the ICE lines to obtain a general trend line. This line represents the PDP!
PDPs can be created using scikit-learn but these only work well with scikit-learn models. They also can be generated with the SHAP library, as well as another library called PDPBox. Each has its advantages and disadvantages, which we will cover in this section.
SHAP’s partial_dependence plot function takes the name of a feature (year), a predict function (cb_mdl.predict), and a dataset (X_test). There are some optional parameters such as whether to show the ICE lines (ice), a horizontal model expected value line (model_expected_value), and a vertical feature expected value line (feature_expected_value). It shows the ice lines by default, but there are so many observations in the test dataset it would take a long time to generate the plot, and would be “too busy” to appreciate the trends. The SHAP PDP can also incorporate SHAP values (shap_values=True) but it would take a very long time considering the size of the dataset. It’s best to sample your dataset to make it more plot-friendly:
shap.plots.partial_dependence( "year", cb_mdl.predict, X_test, ice=False, model_expected_value=True,\ feature_expected_value=True)The preceding code will produce the plot in Figure 4.9:

Figure 4.9: SHAP’s PDP for year
As you can appreciate in Figure 4.9, there’s an upward trend for year. This finding shouldn’t be surprising considering the neat gradient in Figure 4.8 for year. With the histogram, you can tell the bulk of observations have values for year over 2011, which is where it starts to have an above-verage impact on the model. This makes sense once you compare the location of the histogram to the location of the bulge in the beeswarm plot (Figure 4.8).
With PDPBox, we will make several variations of PDP plots. This library separates the potentially time-consuming process of making the simulations with the PDPIsolate function from the plotting with the plot function. We will only have to run PDPIsolate once but plot three times.
For the first plot, we use plot_pts_dist=True to display a rug. The rug is a more concise way of conveying the distribution than the histogram.
For the second one, we use plot_lines=True to plot the ICE lines, but we can only plot a fraction of them, so frac_to_plot=0.01 randomly selects 1% of them.
For the third one, instead of showing a rug, we can construct the X-axis with quantiles (to_bins=True):
pdp_single_feature = pdp.PDPIsolate( model=cb_mdl, df=X_test, model_features=X_test.columns,\ feature='year', feature_name='year', n_classes=0,\ n_jobs=-1)fig, axes = pdp_single_feature.plot(plot_pts_dist=True)fig.show() fig, axes = pdp_single_feature.plot( plot_pts_dist=True, plot_lines=True, frac_to_plot=0.01)fig.show() fig, axes = pdp_single_feature.plot( to_bins=True, plot_lines=True, frac_to_plot=0.01)fig.show()The preceding snippet will output the three plots in Figure 4.10:

Figure 4.10: Three variations of PDPBox’s PDPs for year
The ICE lines enrich the PDP plots by showing the potential for variance. The last plot in Figure 4.10 also shows how, even though rugs or histograms are useful guides, organizing the axis in quantiles better helps visualize distribution. In this case, two-thirds of year is distributed before 2017. And the two decades between 1984 and 2005 only account for 11%. It’s only fair they get a corresponding portion of the plot.
We can now create a few lists we will use to iterate across different kinds of features, whether continuous (cont_feature_l), binary (bin_feature_l), or categorical (cat_feature_l):
cont_feature_l = [ 'year', 'odometer', 'cylinders', 'epa_displ', 'make_pop',\ 'make_yr_pop', 'model_yr_pop']make_cat_feature_l = [ 'make_cat_obsolete', 'make_cat_regular', 'make_cat_premium',\ 'make_cat_luxury', 'make_cat_luxury_sports']bin_feature_l = ['model_premier', 'auto_trans']cat_feature_l = make_cat_feature_l + bin_feature_lTo quickly get a sense of what PDPs look like for each feature, we can iterate across one of the lists of features producing PDP plots for each one. We will do continuous features (cont_feature_l) because it’s easiest to visualize, but you can try one of the other lists as well:
for feature in cont_feature_l: pdp_single_feature = pdp.PDPIsolate( model=cb_mdl, df=X_test, model_features=X_test.columns,\ feature=feature, feature_name=feature, n_classes=0,\ n_jobs=-1 ) fig, axes = pdp_single_feature.plot( to_bins=True, plot_lines=True, frac_to_plot=0.01,\ show_percentile=True, engine='matplotlib' )The preceding code will output eight plots, including the one in Figure 4.11:

Figure 4.11: PDPBox’s PDP for odometer
The beeswarm plot in Figure 4.8 shows that a low value of odometer correlates with the model outputting a higher price. In Figure 4.11, it depicts how it’s mostly monotonically decreasing except in the extremes. It’s interesting that there are odometer values of zero and ten million in the extremes. While it makes sense that the model learned that odometer made no difference in prices when it’s zero, a value of ten million is an anomaly, and for this reason, you can tell that the ICE lines are going in different directions because the model is not sure what to make of such a value. We must also keep in mind that ICE plots, and thus PDPs, are generated with simulations that may create examples that wouldn’t exist in real life, such as a brand-new car with an extremely high odometer value.
If you replace cont_feature_l with make_cat_feature_l and re-run the previous snippet, you will realize that some make categories correlate positively while others negatively with the outcome. This finding shouldn’t be surprising considering some make categories, such as “luxury” are indicative of a high price and others of a lower one. That being said, make_cat is a categorical feature that was one-hot encoded, so it’s not natural to create PDP plots as if each category were an independent binary feature.
Fortunately, you can create a PDP with each one-hot encoded category side by side. All you need to do is plug in the list of product-type features in the feature attribute. PDPBox also has a “predict plot,” which can help provide context by showing prediction distribution across feature values. PredictPlot is easy to plot, having many of the same attributes as the plot.
pdp_multi_feature = pdp.PDPIsolate( model=cb_mdl, df=X_test, model_features=X_test.columns,\ feature=make_cat_feature_l, feature_name="make_cat", n_classes=0, n_jobs=-1)fig, axes = pdp_multi_feature.plot( plot_lines=True, frac_to_plot=0.01, show_percentile=True)fig.show()predict_plot = info_plots.PredictPlot( model=cb_mdl, df=X_test, feature_name="make_cat", n_classes=0, model_features=X_test.columns, feature=make_cat_feature_l)fig, _, _ = predict_plot.plot()fig.show()The preceding snippet should create the two plots in Figure 4.12:

Figure 4.12: PDPBox’s actual plot for make categories
The PDP for make_cat in Figure 4.12 shows the tendency of “luxury” and “premium” categories to lead to higher prices but only by about 3,000 dollars on average with a lot of variance depicted in the ICE lines. However, remember what was said about simulations not being necessarily representative of real-life scenarios?
If we compare the PDP to the box and whiskers in the actual predictions in Figure 4.12, we can tell that the difference in average prediction between regular and any of the “luxury” and “premium” categories is at least seven thousand dollars. Of course, the average doesn’t tell the whole story because even a premium car with too much mileage or that’s very old might cost less than a regular vehicle. The price depends on many factors besides the reputation of the make. Of course, just judging by how the boxes and whiskers align in Figure 4.12, “luxury sports” and “obsolete” categories are stronger indications of higher and lower prices, respectively.
PDPs are often straightforward to interpret and relatively quick to generate. However, the simulation strategy it employs doesn’t account for feature distribution and heavily relies on the assumption of feature independence, which can lead to counterintuitive examples. We will now explore two alternatives.
SHAP scatter plot
Section titled “SHAP scatter plot”SHAP values are available for every data point, enabling you to plot them against feature values, resulting in a PDP-like visualization with model impact (SHAP values) on the y-axis and feature values on the x-axis. Being a similar concept, the SHAP library initially called this a dependence_plot, but now it’s referred to as a scatter plot. Despite the similarities, PDP and SHAP values are calculated differently.
Creating a SHAP scatter plot is simple, requiring only the explanation object. Optionally, you can color-code the dots according to another feature to understand potential interactions. You can also clip outliers from the x-axis using percentiles with xmin and xmax attributes and make dots 20% opaque (alpha) to identify sparser areas more easily:
shap.plots.scatter( cb_shap[:,"odometer"], color=cb_shap[:,"year"], xmin="percentile(1)",\ xmax="percentile(99)", alpha=0.2)shap.plots.scatter( cb_shap[:,"long"], color=cb_shap[:,"epa_displ"],\ xmin="percentile(0.5)", xmax="percentile(99.5)", alpha=0.2, x_jitter=0.5)The above snippet creates Figure 4.13:

Figure 4.13: SHAP’s scatter plots for odometer and long, color-coded for year and epa_displ respectively
The first plot in Figure 4.13 depicts how a higher odometer reading negatively impacts the model outcome. Also, the color coding shows that the SHAP values for higher years are even lower when the odometer reading is over ninety thousand. In other words, an old car with a high odometer reading is expected, but with a new car, it’s a red flag!
The second plot in Figure 4.13 is very interesting; it shows how the west coast of the country (at about -120°) correlates with higher SHAP values and the further east it goes, the lower the SHAP values. Hawaii, Anchorage, and Alaska (at about -150°) are also higher than the east coast of the United States (at around -75°). The color coding shows how the more liters displaced of fuel mostly leads to higher SHAP values but it’s not as stark of a difference the further east you go.
The scatter plot works well for continuous features, but can you use it for discrete ones? Yes! Let’s create one for make_cat_luxury. Since there are only two possible values on the x-axis, 0 and 1, what makes sense is to jitter them so that all the dots don’t get plotted on top of each other. For instance, x_jitter=0.4 means they will be jittered horizontally up to 0.4, or 0.2 on each side of the original value. We can combine this with alpha to ensure that we can appreciate the density:
shap.plots.scatter( cb_shap[:,"make_cat_luxury"], color=cb_shap[:,"year"], x_jitter=0.4,\ alpha=0.2, hist=False)The snippet above produces Figure 4.14:

Figure 4.14: SHAP’s scatter plot for make_cat_luxury color-coded for year
Figure 4.14 shows that according to the SHAP values, make_cat_fha=1 positively impacts the model outcome, whereas make_cat_fha=1 has a mildly negative effect. The color coding suggests that lower years tempers the impact, making it smaller. This makes sense because older luxury cars have depreciated.
While SHAP scatter plots may be an improvement from PDP plots, SHAP’s tree explainers trade fidelity for speed, causing features that have no influence on the model to potentially have a SHAP value above zero. Fidelity refers to the accuracy of an explanation in representing the behavior of the model. To get higher fidelity, you need to use a method that makes fewer shortcuts in understanding what the model is doing, and even then, some adjustments to parameters like using a greater sample size will increase fidelity too because you are using more data to create the explanations. In this case, the solution is to use KernelExplainer instead because, as we previously discussed, it is more comprehensive, but it has issues with feature dependence. So there’s no free lunch! Next, we will cover ALE plots as a partial solution to these problems.
ALE plots
Section titled “ALE plots”ALE plots are advantageous over PDPs because they are unbiased and faster. ALE accounts for data distributions when calculating feature effects, resulting in an unbiased representation. The algorithm divides the feature space into equally sized windows and computes how predictions change within these windows, resulting in the local effects. Summing the effects across all windows makes them accumulated.
You can easily generate the ALE plot with the ale function. All you need is some data (X_test_no_outliers), the model (cb_mdl), and the feature(s) and feature type(s) to be plotted. Optionally, you can enter the grid_size, which will define the window size for local effects calculations. It is 20 by default, but we can increase it for higher fidelity, provided you have enough data. As mentioned previously, some adjustments to parameters can affect fidelity. For window size, it will break the data into smaller bins to compute values and thus make them more granular. Also, confidence intervals are shown by default. Incidentally, it’s best to remove outliers in this case because it’s hard to appreciate the plot when the maximum loan nearly reaches $8 million. You can try using X_test instead of X_test_no_outliers to see what I mean.
Confidence intervals are shown by default. It’s preferable to exclude outliers in this case, as it’s difficult to appreciate the plot when only very few vehicles represent years before 1994 and after 2021 and have very low and very high odometer readings. You can use X_test instead of X_test_no_outliers in the ale function to see the difference:
X_test_no_outliers = X_test[ (X_test.year.quantile(.01) <= X_test.year) &\ (X_test.year <= X_test.year.quantile(.99)) &\ (X_test.odometer.quantile(.01) <= X_test.odometer) &\ (X_test.odometer <= X_test.odometer.quantile(.99))]ale_effect = ale( X=X_test_no_outliers, model=cb_mdl, feature=['odometer'],\ feature_type='continuous', grid_size=80)plt.show()ale_effect = ale( X=X_test_no_outliers, model=cb_mdl,\ feature=['make_cat_luxury'],feature_type='discrete')plt.show()The above snippet produces the two plots in Figure 4.15:

Figure 4.15: ALE plots for odometer and make_cat_luxury
The first plot in Figure 4.15 is the ALE plot for odometer. As portrayed in Figure 4.13, the effect on the model goes from positive to negative as the odometer reading increases. However, unlike SHAP, in the ALE plot, it goes negative long before the odometer reaches 90,000. Please note the confidence interval is so thin it’s only visible somewhere under 10,000. The second ALE plot shows a significant positive impact of the “luxury” category on the outcome and that luxury vehicles are not as represented as other ones.
So far, we’ve only discussed single-feature explanations. But we also can observe the interaction between features, which we will cover next.
Feature interactions
Section titled “Feature interactions”Features may not influence predictions independently. For example, as discussed in Chapter 2, Key Concepts of Interpretability, determining obesity based solely on weight isn’t possible. A person’s height or body fat, muscle, and other percentages are needed. Models understand data through correlations, and features are often correlated because they are naturally related, even if they are not linearly related. Interactions are what the model may do with correlated features. For instance, a decision tree may put them in the same branch, or a neural network may arrange its parameters in such a way that it creates interaction effects. This also occurs in our case. Let’s explore this through several feature interaction visualizations.
SHAP bar plot with clustering
Section titled “SHAP bar plot with clustering”SHAP comes with a hierarchical clustering method (shap.utils.hclust) that allows for the grouping of training features based on the “redundancy” between any given pair of features. This refers to the degree to which they depend on each other, on a scale from complete redundancy (0) to total independence (1). We won’t use the entire dataset for this task because it would take a very long time, so we will use a 10% sample:
X_samp = X.sample(frac=0.1)y_samp = y.loc[X_samp.index]clustering = shap.utils.hclust(X_samp, y_samp)We can employ the same bar chart as in Figure 4.6, but this time, we input the clustering and clustering cutoff and voilá! We can visualize which features are most redundant. Our aim is to pinpoint relationships that are less than 0.7 independent (clustering_cutoff):
shap.plots.bar(cb_shap, clustering=clustering, clustering_cutoff=0.7)The preceding snippet generates the bar plot in Figure 4.16:

Figure 4.16: SHAP bar plot with clustering
The dendrogram on the right in Figure 4.16 reveals which features rely on each other the most and at three tiers. For instance, year is dependent on odometer, and when combined, they both depend on epa_co2, which in turn depends indirectly on a number of features, including the fuel displacement (epa_displ) and cylinders features. Also, please note that all make category features depend on each other but also on the make’s relative popularity (make_pop). This finding makes sense because some categories are overall more popular than others. These insights can serve as a guide for subsequent investigations.
2D ALE plots
Section titled “2D ALE plots”The optimal way to visually inspect the impact of two variables on predictions is through 2D ALE plots, primarily because it’s unbiased when dealing with correlated features.
Let’s scrutinize the top features, year and odometer, which also have a clear dependency. We’ll utilize the test dataset minus the outliers so that the plot focuses on the core of the data—that is, the part containing approximately 98% of the data points. This time, instead of a single feature, we’ll insert a list of two features:
features_l = ["year", "odometer"]ale_effect = ale( X=X_test_no_outliers, model=cb_mdl, feature=features_l,\ feature_type='continuous', grid_size=50, include_CI=False)plt.show()The above code produces the ALE plot in Figure 4.17:

Figure 4.17: 2D ALE plot for odometer and year
As seen in Figure 4.17, except for a slim range of extremely high odometer readings and areas where older cars and low odometer readings overlap, there’s a modest effect for most of the plot. Mostly, they seem to only have a larger negative effect in the corners.
An important point to remember is that SHAP’s clustering distance ranges from redundancy to independence. The issue with highly correlated features is that, at a certain point, they cease depending on each other and become entirely redundant. So, let’s examine how close to redundancy these two features are with the clustering array we created with shap.utils.hclust:
np.set_printoptions(suppress=True)print(clustering)The preceding snippet should output the below array:
[[ 2. 21. 0. 2. ] [ 22. 52. 0. 3. ] [ 23. 53. 0. 4. ] [ 24. 54. 0. 5. ] [ 20. 55. 0. 6. ] [ 12. 14. 0.235 2. ] [ 0. 57. 0.253 3. ] [ 1. 58. 0.262 4. ] [ 13. 59. 0.289 5. ] [ 4. 7. 0.383 2. ] [ 9. 11. 0.394 2. ] [ 43. 44. 0.429 2. ] [ 15. 17. 0.462 2. ] [ 5. 56. 0.477 7. ] [ 10. 61. 0.605 3. ] [ 46. 49. 0.647 2. ] [ 62. 66. 0.654 5. ] [ 51. 67. 0.665 3. ] [ 6. 68. 0.67 6. ] [ 31. 70. 0.673 7. ] [ 65. 71. 0.694 14. ] [ 25. 32. 0.717 2. ] [ 41. 101. 0.997 52. ]]
The array consists of rows of edges. The columns represent node number 1, node number 2, their distance, and parent node number. At the top, there are a few pairs that are completely redundant such as make_pop (feature 2) and make_cat_luxury_sports (feature 21). Not a strange outcome considering luxury sports cars, like a Ferrari, are the least popular vehicles in the dataset because they aren’t sold as often as, say, a Ford:
features_l = ["cylinders", "epa_displ"]ale_effect = ale(X=X_test, model=cb_mdl, feature=features_l,\ feature_type='discrete', grid_size=50)The preceding snippet outputs Figure 4.18:

Figure 4.18: 2D ALE plot for epa_displ and cylinders
Figure 4.18 distinctly illustrates higher interaction effects where cylinders is larger than 8 and where epa_displ is under 4. This finding is counterintuitive considering vehicles with a lot of cylinders are unlikely to have low amounts of engine displacement. On the other hand, the higher interaction effects when there are over 4 cylinders and an engine displacement of at least 6 liters make more sense. Please note that there are other factors such as year and model_type that correlate with these two features, but ALE is great at separating the effects of cylinders and epa_displ from other highly correlated features.
PDP interactions plots
Section titled “PDP interactions plots”I’m sure you’re wondering: Given the numerous limitations of PDP, when and where should we contemplate using 2D PDP?
Only when a proven relationship exists between two features, but they are not entirely redundant or independent, and ideally, when they perfectly complement each other. Even then, an ALE plot is advisable as it teases out higher-order effects.
Nonetheless, for illustrative purposes, we will generate a 2D PDP with long and lat, which are indirectly connected. The code for 2D is very similar to 1D, with the exception that we use PDPInteract instead of PDPIsolate, and then for the plot function, designate the plot_type as contour, but grid could also be used:
features_l = ["long", "lat"]pdp_interaction_feature = pdp.PDPInteract( model=cb_mdl, df=X_test, model_features=X_test.columns,\ features=features_l, feature_names=features_l, n_classes=0,\ num_grid_points=15, n_jobs=-1)fig, _ = pdp_interaction_feature.plot( plot_type='contour', plot_pdp=False)fig.show()The preceding snippet outputs Figure 4.19:

Figure 4.19: PDP interaction contour plot for long and lat
Figure 4.19 serves as proof of how the features are related to the outcome: long seems to be responsible for most of the effect, but in some areas, lat seems to make a difference, especially in Alaska in the top-left corner. We can check the reliability of this result with a 2D predict plot (InteractPredictPlot). As with Figure 4.12, the objective is to display the distribution of the data and the predicted scores for that data, but this time, it features a grid of bins that are color-coded for average scores and size-coded for the number of test observations. We can contrast this with the corresponding 2D target plot (InteractTargetPlot), which does the same but for the labels (target) and not the predicted score:
fig, axes, summary_df = info_plots.InteractPredictPlot( model=cb_mdl, X=X_test, features=features_l,\ feature_names=features_l, num_grid_points=(15,12))fig, axes, summary_df = info_plots.InteractTargetPlot( df=X_train.join(y_train), target='price', features=features_l,\ feature_names=features_l, num_grid_points=(15,12))The preceding snippet creates both plots in Figure 4.20:

Figure 4.20: PDP actual plot for long and lat
From the initial plot, it’s evident that the median predictions are greatest on the western half (on the right side) and especially toward the southwest (on the bottom right), but not by much. The second plot affirms that the labels are indeed more likely to be high-priced in these sections of the plot. Therefore, it’s no surprise that the model learned this distribution to its degree of accuracy. These plots aid in affirming a relationship between both features.
In the following chapter, we’ll delve deeper into local explanations!
Mission accomplished
Section titled “Mission accomplished”We set out to uncover what features helped predict the used car price for the two-sided marketplace. Using the intrinsic parameters of the decision trees, permutation feature importance, and SHAP, we realized that at least 15 features have a negligible impact on either model. Also, about an equal amount of features holds the lion’s share of impact. Some of the most critical features, like engine displacement (epa_displ) and cylinders, are technical and can vary for the same make and model, so the user would have to know and enter them.
We also found interesting and perfectly valid relationships between different features such as year and odometer, which help us understand how they interact in the model. We can share all of these findings with the tech startup.
Summary
Section titled “Summary”After reading this chapter, you should understand what model-specific methods to compute feature importance are and their shortcomings. Then, you should have learned how model-agnostic methods’ permutation feature importance and SHAP values are calculated and interpreted. You also learned the most common ways to visualize model explanations. You should know your way around global explanation methods like global summaries, feature summaries, and feature interaction plots and their advantages and disadvantages.
In the next chapter, we will delve into local explanations.
Further reading
Section titled “Further reading”- Shapley, Lloyd S., 1953, A value for n-person Games. In Kuhn, H. W.; Tucker, A. W. (eds.). Contributions to the Theory of Games. Annals of Mathematical Studies. 28. Princeton University Press. pp. 307–317: https://doi.org/10.1515/9781400881970-018
- Lundberg, S., and Lee, S., 2017, A Unified Approach to Interpreting Model Predictions. Advances in Neural Information Processing Systems: https://arxiv.org/abs/1705.07874 (documentation for SHAP: https://github.com/slundberg/shap)
- Lundberg, S.M., Erion, G., and Lee, S., 2018, Consistent Individualized Feature Attribution for Tree Ensembles. ICML Workshop: https://arxiv.org/abs/1802.03888
- Molnar, C., 2019, Interpretable Machine Learning. A Guide for Making Black Box Models Explainable: https://christophm.github.io/interpretable-ml-book/
- Documentation for SHAP plots: https://shap.readthedocs.io/en/latest/api.html#plots
- Original paper for PDP method: Friedman, J.H., 2001, Greedy function approximation: A gradient boosting machine. Annals of Statistics, 29, 1189-1232: https://doi.org/10.1214/aos/1013203451
- Documentation for PDPBox: https://pdpbox.readthedocs.io/en/latest/
- Original paper for ALE method: Apley, D.W., & Zhu, J., 2020, Visualizing the effects of predictor variables in black box supervised learning models. Journal of the Royal Statistical Society: Series B (Statistical Methodology), 82. https://arxiv.org/abs/1612.08468
- Repository for PyALE: https://github.com/DanaJomar/PyALE
- Original paper for LIME method: Ribeiro, M., Singh, S., and Guestrin, C., 2016, “Why Should I Trust You?”: Explaining the Predictions of Any Classifier. Proceedings of the 22nd ACM SIGKDD International Conference on Knowledge Discovery and Data Mining. https://arxiv.org/abs/1602.04938
- Documentation for LIME: https://lime-ml.readthedocs.io/en/latest/