Skip to main content

Machine learning model interpretability, part 2: PDP, ICE, LIME and Shapley values

Five model-agnostic methods to explain a black-box model, with how each is computed, its pros and cons and the R and Python libraries that implement it.

The second part moves from theory to practice with models trained on employee attrition data: partial dependence plots (PDP), ICE curves, permutation feature importance, LIME and Shapley values. For each method, how it is computed, its strengths and limits and which libraries implement it, plus guidelines for choosing one.

Series «Machine learning model interpretability», part 2 of 2. Part 1 · Part 2

This second part on machine learning model interpretability moves from theory to practice: it presents five model-agnostic methods (PDP, ICE, permutation feature importance, LIME and Shapley values), with how each is computed, its pros and cons and the R and Python libraries that implement it, and closes with guidelines for choosing among them. Part 1 covered why interpretability matters for understanding and making the most of data science and machine learning models; now we turn to the practical challenge.

How do I interpret my black-box model?

We work with generalized linear models (GLM), gradient boosting machines (GBM), random forests (RF) and deep neural networks (DNN), trained on the Job Attrition data to predict the categorical variable attrition.

Below are short introductions to five of the model-agnostic interpretation methods from the table at the end of part 1 (that is, methods that work with any model) and to their R implementation, to help understand the predicted results and how reliable they are:

  • PDP, or partial dependence plot
  • ICE, or individual conditional expectation plot
  • Permutation feature importance
  • LIME
  • Shapley values

PDP, or partial dependence plot

PDPs show the average marginal effect that one or two features have on the ML model’s predicted outcome. In other words, the partial dependence for variable XS is the model’s average prediction for each value that variable takes.

The main statistical problem with PDPs arises when variables are correlated, because the marginal dependence computed for each value of XS comes from the model’s joint prediction function (what the model predicts for every value of XS across all the points of the other variables, XC).

As a result, computing the PDP for every value of XS can include points that are very unlikely in reality, or even impossible, since the data need not contain every value of XS combined with a correlated variable: for example, high salaries with a low job level.

Formula

f̂S(xS) = EXC[f̂(xS, XC)] ≈ (1/n) Σi=1n f̂(xS, xC(i))

where f̂ is the model’s joint prediction function, XS is the variable the PDP is computed for, and XC are the model’s other variables.

Pros:

  • Intuitive: the model’s average prediction if we force every data point to take a given value of the variable.
  • If there is no correlation, it perfectly represents the variable’s influence on the prediction.
  • If there is no correlation, it has a causal interpretation between the variable and the model’s predictions (which does not necessarily mean the causality holds in reality; that depends on how correct the model is).

Cons:

  • It hides heterogeneity between observations, because it is an average.
  • Two is the maximum number of XS variables, since we cannot process 4D charts.
  • It does not show the distribution of XS: complement it with a histogram or plot the data points, to avoid over-interpreting low-frequency cases.
  • It assumes XS and XC are independent.

Software:

  • iml, pdp and DALEX in R
  • sklearn.inspection.PartialDependenceDisplay in Python (it replaced plot_partial_dependence, which scikit-learn removed in version 1.2)

ICE, or individual conditional expectation plot

Individual conditional expectation (ICE) plot

ICE plots draw one line per observation, showing how the ML model’s prediction for that instance changes as the values of the feature vary.

They measure how the prediction depends on a variable for each instance separately; the average of all ICE curves is the PDP.

Formula

f̂S(i)(xS) = f̂(xS, xC(i))

where XS is the variable the ICE is computed for and XC are the model’s other variables.

Pros:

  • Even more intuitive than the PDP: each line is an individual case, so you can see how each individual’s trajectory influences the model’s predictions.
  • It can reveal heterogeneous behavior across observations.

Cons:

  • It can only show one variable meaningfully (otherwise it loses interpretability).
  • If XS is correlated with the model’s other variables, some points on the plotted lines may be invalid (fictitious).
  • The chart can get overcrowded with lines and hard to read; one fix is to compute ICE on a sample of the data or add transparency.

Software:

  • iml, ICEbox and pdp in R
  • pycebox in Python; scikit-learn also draws ICE curves with PartialDependenceDisplay (kind=’individual’)

Permutation feature importance

Permutation feature importance chart

It is the increase in the model’s prediction error after permuting the variable’s values, which breaks the relationship between the variable and the true outcome.

It can be computed on two datasets, depending on what you want to measure:

  • Training data: how much the model relies on each variable to make predictions.
  • Test data: how much each feature contributes to the predictive model’s performance.

Algorithm

  1. Compute the mean squared error (MSE) of the original model.
  2. For each variable i in {1, …, p}:
    1. Shuffle its values (Fisher, Rudin and Dominici suggest splitting the dataset in half and swapping the variable’s values between the halves instead of permuting it).
    2. Apply the ML model.
    3. Estimate the model’s MSE.
    4. Compute the importance of variable i as permuted MSE (step 2.3) / original MSE (step 1).
  3. Sort the variables by importance in descending order.

Pros:

  • Global, compact and easy to interpret: a variable’s importance is the increase in model error when that variable’s information is destroyed.
  • It also captures all interactions with the other variables, because permuting destroys those effects too; importance thus accounts for both direct and interaction effects.
  • It does not require retraining the model, unlike methods that compare results with and without the variable of interest.

Cons:

  • The calculation involves estimating marginal distributions, with some variance: results can be unstable without enough data.
  • It measures the effect on model performance, not on predicted values (it does not measure robustness).
  • You need the true outcome of the dependent variable (it cannot be used with clustering models).
  • With correlated variables, it can include unrealistic points, and adding a correlated variable can lower the importance of the associated one.

Software:

  • iml and DALEX in R
  • eli5.sklearn.PermutationImportance() in Python; scikit-learn also includes sklearn.inspection.permutation_importance

LIME, or local interpretable model-agnostic explanations

Local explanation of a prediction with LIME

The assumption behind LIME is that any complex model is linear at a local scale, so two very similar observations behave predictably even within a complex ML model.

That makes it possible to train a simple linear model around a single observation (perturbing the original data to get similar samples) that mimics how the black-box model behaves at that point.

LIME leaves many decisions to the user, so there is a lot of room to improve the explanations. The factors that affect their quality are:

  • How the perturbations are generated.
  • How the similarity score between perturbations and the original observation is computed.
  • How many variables go into the local model and how they are selected.
  • The type of interpretable linear model.

Algorithm

  1. Select the instance or sample of interest to explain locally.
  2. Perturb each selected observation x n times to create a new dataset from x’s neighborhood.
  3. Compute the distance from every perturbation to the original observation and turn it into a similarity score used to weight each sample.
  4. Select the m variables that best describe the complex model’s output on the perturbed data, to include in the interpretable model.
  5. Fit an interpretable model on the new perturbed dataset, explaining the complex model’s output with the m selected variables and observations weighted by their similarity to x.
  6. Take the variable weights of the simple model as the local interpretation of the complex model’s behavior for cases similar to x.

Pros:

  • Because the local model is separate, it works with any ML model, and you can even swap the model without changing the interpretation tool.
  • LIME explanations are comparable, easy for people to understand and easy to present visually.
  • LIME is one of the few interpretation methods that works for tabular data, text and images.
  • The fidelity measure (R squared) shows how well the local model approximates the black-box predictions in the neighborhood of the instance of interest.

Cons:

  • Defining the neighborhood correctly (the kernel parameter) is still an open problem when using LIME on tabular data. Each application requires testing different settings to find the best one.
  • LIME’s main problem is the instability of its explanations: in a 2018 paper, Alvarez-Melis and Jaakkola showed that explanations for two very close points varied widely in a simulated setting. That makes the results hard to trust, so the tool should be used with great care.

Software:

  • lime or iml in R
  • lime.lime_tabular in Python

Shapley values

Contribution of each variable to a prediction according to Shapley values

The Shapley value (φ) is a way to compute variable importance in a complex ML model that accounts for interactions between variables.

The idea is to compute the model’s prediction for every possible combination of features that excludes X, then add X and observe the changes; the weighted sum of all those effects is X’s Shapley value.

The SHAP estimator aims for a fair distribution of variable importance. To do so, it satisfies these properties:

  • Efficiency: the contributions add up to the difference between the prediction and the average prediction.
  • Symmetry: if two variables contribute equally in every coalition, their values are identical.
  • Dummy: a feature that never changes the prediction in any coalition has a value of zero.
  • Monotonicity: if a variable increases the prediction more in one model than in another in every situation, its effect is larger in the first model.

Algorithm (for variable j of instance x, over M iterations)

  1. Draw a random instance z from the data matrix X.
  2. Choose a random permutation o of the feature values.
  3. Order instance x: xo = (x(1), …, x(j), …, x(p)).
  4. Order instance z: zo = (z(1), …, z(j), …, z(p)).
  5. Build two new instances:
    • x+j = (x(1), …, x(j−1), x(j), z(j+1), …, z(p))
    • x−j = (x(1), …, x(j−1), z(j), z(j+1), …, z(p))
  6. Compute the marginal contribution: φjm = f̂(x+j) − f̂(x−j).
  7. Compute the Shapley value as the average: φj(x) = (1/M) Σm=1M φjm.

Pros:

  • Satisfying the efficiency, symmetry, dummy and monotonicity axioms gives it a sound statistical foundation.
  • The difference between the prediction and the average prediction is fairly distributed among the variables (it satisfies efficiency, which LIME does not guarantee).
  • It supports explanations at several levels: the whole dataset, a sample or a single observation (LIME is only local).

Cons:

  • Shapley explanations always use every variable in the model; if you prefer selective explanations, LIME is a better fit.
  • Shapley returns importance values but is not a predictive model: it tells you nothing about what happens when the model changes.
  • With correlated variables, Shapley values can include unrealistic data points (it uses the marginal distribution to impute missing points).
  • It is computationally expensive: the estimator samples coalitions and caps the number of iterations M, which increases its variance.

Software:

  • iml in R
  • shap in Python (for example, shap.force_plot())
Comparison of interpretation methods applied to the Job Attrition models

Which technique should I use to explain my ML model?

If you suspect the model’s variables are correlated, use more than one method to make the explanation more consistent and faithful.

The key is to consider what the explanation is for and who it is for, and then weigh these guidelines:

  • Local or global method. Do you need to understand the model’s full logic, or only the reason behind a specific decision?
  • Complexity and exhaustiveness. What is the timeline? If the user needs to decide quickly, a simple explanation (LIME, PDP) may be better; if time is not an issue, a more complex and exhaustive explanation is advisable. What is the user’s level of expertise? Experts will probably prefer a more sophisticated explanation, while other users may prefer one that is easier to understand and remember.

For more on the subject, I recommend the book I used as a guide for this article: Interpretable machine learning. A guide for making black box models explainable (2019), by Christoph Molnar.

Camila Palomeque
Consultant, Data & Analytics unit

¿Listo para dar
el próximo paso?

Inicia tu camino
Otras publicaciones

Before asking how to use AI in a utility, it is worth asking whether the data is ready to support better decisions.

Six connected stages take a public power finance function from assessment to adoption, so AI can support better, faster and more traceable decisions.

Affordability, capital investment and resilience are now moving together. Utilities need scenarios to make decisions before the future becomes clear.

Quanam, a digital transformation, data and AI consultancy headquartered in Montevideo, Uruguay, is Certified in the Claude Partner Network. Its team holds Claude certifications, part of a path guided by one conviction: AI delivers more when people work alongside it.

Leave a Reply