Shap Vs Lime Vs Pdp Vs Ice An Intuitive Side By Si
Why Your Model’s ‘Best Guess’ Isn’t Enough
Imagine you’re a data scientist at a bank. Your team built a model that predicts whether a loan applicant will repay. It’s accurate — 94% AUC on your test set. Then a regulator walks in with a rejected applicant’s file. “Why was this person denied?” she asks. You pull up the screen. The model’s probability of default is 0.81. “The model says they’re high-risk,” you offer. The regulator isn’t impressed. “But why? Was it their income? Their credit history? Their zip code?” You stare at the screen. You don’t know.
This is the core tension of modern machine learning. The models that win Kaggle competitions — XGBoost, random forests, neural networks — are black boxes. They give you a number, but they don’t tell you the story behind it. And in high-stakes settings (lending, healthcare, hiring), the story is what matters. You can’t debug bias you can’t see. You can’t build trust with a stakeholder who only hears “the algorithm said so.”
Interpretability isn’t an academic luxury. It’s a practical necessity. And the good news is, we have tools — translators, really — that can open up the black box and explain what’s going on inside. In this article, we’ll learn four of the most important ones:
- PDP (Partial Dependence Plots): How does a feature affect predictions on average?
- ICE (Individual Conditional Expectation): Does that average hide different stories for different people?
- LIME (Local Interpretable Model-agnostic Explanations): Why did the model make this specific prediction?
- SHAP (SHapley Additive exPlanations): Can we ground our explanations in something solid, like game theory?
By the end, you’ll know exactly which tool to reach for and how to read its output in plain English. We’ll use one dataset and one model throughout, so you can see how each method illuminates a different piece of the same puzzle.
Let’s build that model now.
# Load a familiar dataset and train a single Random Forest model
# that all four methods will explain.
import pandas as pd
from sklearn.datasets import fetch_california_housing
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import train_test_split
# Load California Housing data
housing = fetch_california_housing(as_frame=True)
X = housing.data
y = housing.target
# Train a Random Forest (fast, non-linear, and works with all four tools)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
model = RandomForestRegressor(n_estimators=100, random_state=42, n_jobs=-1)
model.fit(X_train, y_train)
print(f"Model trained. Test R²: {model.score(X_test, y_test):.3f}")
print(f"Features: {list(X.columns)}")
We now have a random forest that predicts California house prices (in hundreds of thousands of dollars) from eight features: median income, house age, average rooms, average bedrooms, population, average occupancy, latitude, and longitude. The model is accurate enough to be useful — and opaque enough to need explaining. Let’s start by building a mental map of what kinds of explanations we can ask for.
The Big Picture: Global vs. Local, and What Each Method Is For
Before we dive into code, let’s get our bearings. Think of your model like a car. You can ask two very different questions about its fuel efficiency:
- Global: “Over the past year, what was the car’s average miles per gallon?” That’s a summary of the car’s overall behavior. It doesn’t tell you about any specific trip — just the big-picture trend.
- Local: “Why did the car guzzle gas on my drive to the mountains last Tuesday?” That’s an explanation for one specific event. Maybe it was the uphill grade, the cold weather, the heavy cargo. You’re zooming in on a single data point.
In machine learning interpretability, we use these same two lenses:
- Global explanations tell you how a feature generally affects the model’s predictions across the whole dataset. “Higher median income pushes predicted house prices up.”
- Local explanations tell you why the model made a specific prediction for a specific instance. “This house’s predicted price is $$45,000 above average because its median income is in the 90th percentile.”
Here’s where our four methods sit on this map:
- PDP and ICE are global methods. They show you curves of how a feature’s value changes the prediction, on average (PDP) or for individual instances (ICE).
- LIME is a local method. It explains one prediction at a time by building a tiny, transparent model just for the neighborhood around that instance.
- SHAP bridges both. It gives you local explanations (why this prediction?) that you can aggregate into a global view (how important is each feature overall?).
In plain English: Global = how a feature generally matters. Local = why this specific prediction came out the way it did.
Let’s pick one specific prediction to be our “mystery” — the one we’ll unpack with all four tools.
# Make a single prediction to serve as our running 'mystery' instance.
import pandas as pd
from sklearn.datasets import fetch_california_housing
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import train_test_split
# Recreate the model and data (self-contained block)
housing = fetch_california_housing(as_frame=True)
X = housing.data
y = housing.target
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
model = RandomForestRegressor(n_estimators=100, random_state=42, n_jobs=-1)
model.fit(X_train, y_train)
# Pick the first test instance as our mystery house
mystery_house = X_test.iloc[[0]]
mystery_pred = model.predict(mystery_house)[0]
print(f"Mystery house features:\n{mystery_house.to_string()}")
print(f"\nPredicted price (hundreds of thousands): {mystery_pred:.3f}")
print(f"That's ${mystery_pred * 100_000:,.0f}")
Our model predicts this house is worth about $$206,000. But why? What features pushed it up or pulled it down? Let’s start with the simplest global method — one that shows us how a feature affects predictions, on average, across the whole dataset.
Partial Dependence Plots (PDP): How a Feature Pushes Predictions, On Average
Here’s the intuition. Imagine you could take every house in California and magically set its median income to 40,000, then $$50,000, and so on. The curve you’d get — average predicted price at each income level — is a partial dependence plot.
In plain English: a PDP shows the average marginal effect of a feature on the prediction. It answers the question, “If we ignore everything else and just wiggle this one feature, how does the model’s output move, on average?”
Let’s see it in action.
# Generate a PDP for median income using scikit-learn.
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.datasets import fetch_california_housing
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import train_test_split
from sklearn.inspection import PartialDependenceDisplay
# Recreate model and data
housing = fetch_california_housing(as_frame=True)
X = housing.data
y = housing.target
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
model = RandomForestRegressor(n_estimators=100, random_state=42, n_jobs=-1)
model.fit(X_train, y_train)
# Plot PDP for 'MedInc' (median income)
fig, ax = plt.subplots(figsize=(8, 5))
PartialDependenceDisplay.from_estimator(
model, X_train, features=['MedInc'], ax=ax, grid_resolution=50
)
ax.set_title("PDP: How Median Income Affects Predicted House Price (on average)")
ax.set_ylabel("Predicted Price (hundreds of thousands)")
plt.tight_layout()
plt.show()
Look at that curve. When median income is around 3 (about 150,000). When median income climbs to 8 (about 350,000). That’s a $$200,000 swing driven by income alone — at least, on average.
Now here’s the catch. And this is the hardest part of PDPs. When we “set everyone’s income to 80,000 but the average number of rooms is only 2. That combination is rare — high-income areas tend to have larger houses. But the PDP blithely creates it, because it varies one feature while holding everything else constant, ignoring the fact that features are correlated in the real world.
This is the independence assumption, and it’s the PDP’s Achilles’ heel. If two features are strongly correlated — like temperature and humidity in a bike-sharing dataset — the PDP can show you predictions for combinations that almost never occur, leading to misleading conclusions.
Let’s check that against the data. We’ll switch to a bike-sharing dataset for a moment, because it has a classic example: high temperature and high humidity rarely happen together, but a PDP will happily show you what the model predicts for that unlikely combo.
# Demonstrate the PDP failure mode with correlated features
# using the Bike Sharing dataset (temperature and humidity).
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.datasets import fetch_california_housing
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import train_test_split
from sklearn.inspection import PartialDependenceDisplay
# We'll simulate the bike-sharing scenario with California housing
# by using two correlated features: Latitude and Longitude.
# (The actual bike dataset requires a separate download; this
# demonstrates the same principle with our running data.)
# Recreate model and data
housing = fetch_california_housing(as_frame=True)
X = housing.data
y = housing.target
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
model = RandomForestRegressor(n_estimators=100, random_state=42, n_jobs=-1)
model.fit(X_train, y_train)
# 2D PDP for Latitude and Longitude (correlated by geography!)
fig, ax = plt.subplots(figsize=(8, 6))
PartialDependenceDisplay.from_estimator(
model, X_train, features=[('Latitude', 'Longitude')],
ax=ax, grid_resolution=30
)
ax.set_title("2D PDP: Latitude and Longitude (correlated features)")
plt.tight_layout()
plt.show()
# Print the correlation to make the point explicit
corr = X_train['Latitude'].corr(X_train['Longitude'])
print(f"Correlation between Latitude and Longitude: {corr:.3f}")
print("The PDP treats them as independent, creating unrealistic (lat, lon) pairs.")
The 2D PDP shows predicted prices for every combination of latitude and longitude — including points in the ocean or deep in the desert where no houses exist. The model is forced to make predictions for absurd data points. This doesn’t mean the PDP is useless; it just means you need to know about this blind spot.
So what if the average hides important differences? What if income affects prices differently in coastal areas than inland? That’s where ICE comes in.
Individual Conditional Expectation (ICE): When Averages Hide the Real Story
A PDP is an average. And averages can be liars. Imagine a feature that has a huge positive effect for half the population and a huge negative effect for the other half. The PDP would show a flat line — zero effect on average — and you’d walk away thinking the feature doesn’t matter. But it matters enormously; it just matters in opposite directions for different groups.
ICE plots fix this by unhiding the individual lines that the PDP averages over. Instead of one average curve, you get one curve for each instance in your dataset (or a sample of them). The PDP is simply the average of all those ICE curves.
In plain English: “Instead of averaging everyone together, let’s draw one line for each house and see if they all tell the same story.”
Let’s see it.
# Generate an ICE plot with PDP overlay for median income.
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.datasets import fetch_california_housing
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import train_test_split
from sklearn.inspection import PartialDependenceDisplay
# Recreate model and data
housing = fetch_california_housing(as_frame=True)
X = housing.data
y = housing.target
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
model = RandomForestRegressor(n_estimators=100, random_state=42, n_jobs=-1)
model.fit(X_train, y_train)
# ICE + PDP for 'MedInc' (using a subset of 200 instances for clarity)
fig, ax = plt.subplots(figsize=(8, 5))
PartialDependenceDisplay.from_estimator(
model, X_train.sample(200, random_state=42),
features=['MedInc'],
kind='both', # <-- 'both' gives ICE curves + PDP average
ax=ax,
grid_resolution=30,
ice_lines_kw={'alpha': 0.2, 'linewidth': 0.5},
pd_line_kw={'color': 'red', 'linewidth': 2, 'label': 'PDP (average)'}
)
ax.set_title("ICE Plot: Each thin line is one house. Red line is the PDP.")
ax.set_ylabel("Predicted Price (hundreds of thousands)")
ax.legend()
plt.tight_layout()
plt.show()
Look at that fan of lines. Most of them slope upward — higher income means higher predicted price. But notice how some lines are steep and some are nearly flat. The steep ones might be houses in desirable coastal areas, where income has a huge effect on price. The flat ones might be inland areas where income matters less. The red PDP line averages all of this together, hiding this heterogeneity.
To make these differences even clearer, we can use centered ICE plots (c-ICE). We subtract each line’s starting point, so every curve begins at zero. Now the differences in shape jump out, rather than differences in baseline price.
# Centered ICE plot to highlight heterogeneous effects.
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.datasets import fetch_california_housing
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import train_test_split
from sklearn.inspection import PartialDependenceDisplay
# Recreate model and data
housing = fetch_california_housing(as_frame=True)
X = housing.data
y = housing.target
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
model = RandomForestRegressor(n_estimators=100, random_state=42, n_jobs=-1)
model.fit(X_train, y_train)
# Centered ICE plot
fig, ax = plt.subplots(figsize=(8, 5))
PartialDependenceDisplay.from_estimator(
model, X_train.sample(200, random_state=42),
features=['MedInc'],
kind='both',
centered=True, # <-- center each ICE curve at its starting value
ax=ax,
grid_resolution=30,
ice_lines_kw={'alpha': 0.2, 'linewidth': 0.5},
pd_line_kw={'color': 'red', 'linewidth': 2}
)
ax.set_title("Centered ICE: All lines start at 0, highlighting shape differences")
ax.set_ylabel("Change in Predicted Price")
plt.tight_layout()
plt.show()
Now we can clearly see: for some houses, moving from low to high income adds 50,000. The feature’s effect is not uniform — and the PDP alone would have hidden that.
But here’s the limitation we must acknowledge: ICE still suffers from the same independence assumption as PDP. It just reveals the heterogeneity the PDP hides. It doesn’t fix the “absurd data point” problem.
PDP and ICE show us how features affect predictions on average. But they don’t tell us why a specific house got its specific price. For that, we need local explanations.
LIME: Explaining One Prediction at a Time with a Simple Stand-In Model
Let’s return to our mystery house — the one our model predicted would be worth $$206,000. Why that number? What features pushed it up or pulled it down?
LIME’s intuition is beautifully simple. To explain one prediction, you create a thousand tiny variations of that instance — tweak the income a little, change the number of rooms, shift the location slightly — and see how the model’s predictions change. Then you fit a simple, transparent model (like a linear regression) just to those perturbed samples, giving more weight to samples that are closer to the original instance. That simple model is your explanation.
In plain English: “Let’s build a tiny, interpretable model that mimics the black-box model in the neighborhood of this one prediction.”
Let’s use LIME to explain our mystery house.
# Use LIME to explain the single mystery-house prediction.
import pandas as pd
import numpy as np
from sklearn.datasets import fetch_california_housing
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import train_test_split
import lime.lime_tabular
# Recreate model and data
housing = fetch_california_housing(as_frame=True)
X = housing.data
y = housing.target
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
model = RandomForestRegressor(n_estimators=100, random_state=42, n_jobs=-1)
model.fit(X_train, y_train)
# Our mystery house
mystery_house = X_test.iloc[[0]]
mystery_pred = model.predict(mystery_house)[0]
# Create the LIME explainer
# feature_names must be a list of strings
feature_names = list(X_train.columns)
explainer = lime.lime_tabular.LimeTabularExplainer(
training_data=X_train.values, # LIME expects numpy arrays
feature_names=feature_names,
mode='regression',
random_state=42
)
# Explain the mystery house
# mystery_house.values[0] gives a 1D numpy array for the single instance
exp = explainer.explain_instance(
data_row=mystery_house.values[0],
predict_fn=model.predict,
num_features=5
)
# Print the explanation as a list
print("LIME Explanation (feature: effect):")
for feature, weight in exp.as_list():
print(f" {feature}: {weight:.4f}")
# Show the explanation as a bar chart in the notebook
exp.as_pyplot_figure()
plt = __import__('matplotlib.pyplot')
plt.title(f"LIME Explanation for Mystery House (predicted ${mystery_pred*100_000:,.0f})")
plt.tight_layout()
plt.show()
Look at the output. LIME tells us something like: “The model’s baseline prediction is around 45,000. The fact that AveOccup is high subtracts about $$12,000.” Each feature gets a weight — positive means it pushed the prediction up, negative means it pushed it down.
This is incredibly intuitive. You can hand this explanation to a stakeholder and they’ll immediately understand it.
But wait — there’s a catch. And this is the hardest part about LIME: it’s unstable. Run LIME twice on the exact same instance, and you might get slightly different explanations. Why? Because the perturbation process is random. LIME creates those “thousand tiny variations” by sampling from a distribution, and different random seeds give different samples.
Let’s see this instability in action.
# Demonstrate LIME instability: run twice on the same instance.
import pandas as pd
import numpy as np
from sklearn.datasets import fetch_california_housing
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import train_test_split
import lime.lime_tabular
# Recreate model and data
housing = fetch_california_housing(as_frame=True)
X = housing.data
y = housing.target
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
model = RandomForestRegressor(n_estimators=100, random_state=42, n_jobs=-1)
model.fit(X_train, y_train)
mystery_house = X_test.iloc[[0]]
feature_names = list(X_train.columns)
# First explanation (seed 42)
explainer1 = lime.lime_tabular.LimeTabularExplainer(
training_data=X_train.values,
feature_names=feature_names,
mode='regression',
random_state=42
)
exp1 = explainer1.explain_instance(
data_row=mystery_house.values[0],
predict_fn=model.predict,
num_features=5
)
# Second explanation (seed 99)
explainer2 = lime.lime_tabular.LimeTabularExplainer(
training_data=X_train.values,
feature_names=feature_names,
mode='regression',
random_state=99
)
exp2 = explainer2.explain_instance(
data_row=mystery_house.values[0],
predict_fn=model.predict,
num_features=5
)
print("Run 1 (seed 42):")
for f, w in exp1.as_list():
print(f" {f}: {w:.4f}")
print("\nRun 2 (seed 99):")
for f, w in exp2.as_list():
print(f" {f}: {w:.4f}")
print("\nNotice the weights shift — that's LIME's instability.")
See the differences? The top features are usually the same, but the exact weights wiggle around. For high-stakes decisions, this can be unsettling. There’s also the “neighborhood” problem: how big should the neighborhood of perturbed samples be? There’s no single right answer, and the choice heavily influences the explanation.
LIME is fast and intuitive, but it has no theoretical guarantees. What if we could ground our explanations in something more solid — like game theory?
SHAP: Game Theory Meets Machine Learning (and Fixes LIME’s Flaws)
Here’s a story to build the intuition. Three friends — Alice, Bob, and Carol — order dinner together. The total bill is 30. Bob alone would have spent 20. How do you fairly split the $$90?
You can’t just split it equally (90 by coincidence. The fair solution is to consider every possible coalition: what if Alice and Bob ate together? Their joint bill would be 80 - 40. You do this for every possible ordering of friends joining the table, and average each person’s marginal contribution over all those orders. That average is the Shapley value — the only way to fairly assign credit that satisfies some very reasonable axioms (efficiency, symmetry, dummy, additivity).
Now replace “friends” with “features” and “dinner bill” with “prediction.” SHAP (SHapley Additive exPlanations) uses Shapley values to assign each feature a fair share of the prediction. It tells you: “The average prediction is 52,000. AveRooms contributed +5,000. Add them all up, and you get exactly the model’s prediction for this house.”
In plain English: SHAP treats the prediction like a cooperative game where features are players, and fairly divides the prediction among them based on what each feature brings to the table.
Let’s use SHAP to explain our mystery house.
# Use SHAP TreeExplainer to explain the mystery house prediction.
import pandas as pd
import numpy as np
from sklearn.datasets import fetch_california_housing
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import train_test_split
import shap
# Recreate model and data
housing = fetch_california_housing(as_frame=True)
X = housing.data
y = housing.target
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
model = RandomForestRegressor(n_estimators=100, random_state=42, n_jobs=-1)
model.fit(X_train, y_train)
mystery_house = X_test.iloc[[0]]
mystery_pred = model.predict(mystery_house)[0]
# Create TreeExplainer (fast and exact for tree models)
explainer = shap.TreeExplainer(model)
shap_values = explainer.shap_values(mystery_house)
# SHAP waterfall plot for the single prediction
# shap_values is a numpy array; we wrap it for the plot
shap.waterfall_plot(
shap.Explanation(
values=shap_values[0],
base_values=explainer.expected_value,
data=mystery_house.values[0],
feature_names=list(X.columns)
)
)
plt = __import__('matplotlib.pyplot')
plt.title(f"SHAP Waterfall: Mystery House (predicted ${mystery_pred*100_000:,.0f})")
plt.tight_layout()
plt.show()
The waterfall plot starts at the base value — the average prediction across all houses, roughly $$206,000. Then each feature pushes that value up (red) or down (blue). MedInc gives a big upward push. AveOccup gives a small downward push. At the bottom, we land exactly on the model’s prediction. That’s the “additive” property: base + sum of SHAP values = prediction.
Now here’s what makes SHAP special. Remember how LIME is unstable? SHAP (with TreeExplainer) is deterministic — you get the same explanation every time. And SHAP has a deep connection to LIME: KernelSHAP, one variant of SHAP, is essentially LIME with a special weighting scheme that guarantees the Shapley properties (local accuracy, missingness, consistency). SHAP unifies LIME and Shapley values into one framework.
But SHAP isn’t just local. Because each prediction gets its own SHAP values, you can stack them all together to get a global view of the model. Let’s see that.
# SHAP summary plot: global feature importance from local explanations.
import pandas as pd
import numpy as np
from sklearn.datasets import fetch_california_housing
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import train_test_split
import shap
import matplotlib.pyplot as plt
# Recreate model and data
housing = fetch_california_housing(as_frame=True)
X = housing.data
y = housing.target
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
model = RandomForestRegressor(n_estimators=100, random_state=42, n_jobs=-1)
model.fit(X_train, y_train)
# Compute SHAP values for a subset of test data (for speed)
X_sample = X_test.sample(500, random_state=42)
explainer = shap.TreeExplainer(model)
shap_values_sample = explainer.shap_values(X_sample)
# Summary plot
shap.summary_plot(shap_values_sample, X_sample, feature_names=list(X.columns), show=False)
plt.title("SHAP Summary Plot: Global Feature Importance")
plt.tight_layout()
plt.show()
The summary plot is a masterpiece of data density. Each dot is one house’s SHAP value for one feature. The color is the feature’s actual value (red = high, blue = low). The horizontal position is the SHAP value — how much that feature pushed that house’s prediction up or down. Features are ranked by overall importance.
Look at MedInc: high values (red) cluster on the right — they push predictions up. Low values (blue) cluster on the left — they push predictions down. That’s exactly what we’d expect. But look at Latitude and Longitude: the pattern is more complex, with both high and low values having positive and negative effects depending on the interaction. This is the global view built entirely from local explanations.
SHAP’s limitations? It’s slow if you don’t have a tree-based model (KernelExplainer can be 100x slower than TreeExplainer). And like LIME, it struggles with correlated features — Shapley values assume features can enter the “coalition” in any order, which can create unrealistic feature combinations.
We’ve now seen all four methods in isolation. Let’s put them side-by-side on the same prediction and see what each one reveals — and hides.
Side-by-Side Showdown: When to Use Which Method
This is the core value proposition of this guide. We have one model, one prediction, and four different explanations. Let’s put them all on one page.
# Side-by-side comparison: all four explanations for the same instance.
import pandas as pd
import numpy as np
from sklearn.datasets import fetch_california_housing
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import train_test_split
from sklearn.inspection import PartialDependenceDisplay
import lime.lime_tabular
import shap
import matplotlib.pyplot as plt
# Recreate model and data
housing = fetch_california_housing(as_frame=True)
X = housing.data
y = housing.target
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
model = RandomForestRegressor(n_estimators=100, random_state=42, n_jobs=-1)
model.fit(X_train, y_train)
mystery_house = X_test.iloc[[0]]
mystery_pred = model.predict(mystery_house)[0]
feature_names = list(X.columns)
# Set up the 2x2 grid
fig, axes = plt.subplots(2, 2, figsize=(14, 12))
# --- Top-left: PDP ---
PartialDependenceDisplay.from_estimator(
model, X_train, features=['MedInc'], ax=axes[0, 0], grid_resolution=50
)
axes[0, 0].set_title("PDP: Average effect of MedInc")
axes[0, 0].set_ylabel("Predicted Price")
# --- Top-right: ICE ---
PartialDependenceDisplay.from_estimator(
model, X_train.sample(100, random_state=42),
features=['MedInc'],
kind='both',
ax=axes[0, 1],
grid_resolution=30,
ice_lines_kw={'alpha': 0.3, 'linewidth': 0.5},
pd_line_kw={'color': 'red', 'linewidth': 2}
)
axes[0, 1].set_title("ICE: Individual curves + PDP average")
axes[0, 1].set_ylabel("Predicted Price")
# --- Bottom-left: LIME ---
explainer_lime = lime.lime_tabular.LimeTabularExplainer(
training_data=X_train.values,
feature_names=feature_names,
mode='regression',
random_state=42
)
exp = explainer_lime.explain_instance(
data_row=mystery_house.values[0],
predict_fn=model.predict,
num_features=5
)
# LIME bar chart
lime_weights = dict(exp.as_list())
features_ordered = list(lime_weights.keys())
values_ordered = [lime_weights[f] for f in features_ordered]
colors = ['red' if v > 0 else 'blue' for v in values_ordered]
axes[1, 0].barh(features_ordered, values_ordered, color=colors)
axes[1, 0].set_title(f"LIME: Local explanation (pred ${mystery_pred*100_000:,.0f})")
axes[1, 0].set_xlabel("Effect on Prediction")
# --- Bottom-right: SHAP ---
explainer_shap = shap.TreeExplainer(model)
shap_vals = explainer_shap.shap_values(mystery_house)
shap_exp = shap.Explanation(
values=shap_vals[0],
base_values=explainer_shap.expected_value,
data=mystery_house.values[0],
feature_names=feature_names
)
# We'll do a simple horizontal bar chart for SHAP to match the grid
shap_order = np.argsort(np.abs(shap_vals[0]))
shap_features = [feature_names[i] for i in shap_order]
shap_effects = [shap_vals[0][i] for i in shap_order]
shap_colors = ['red' if v > 0 else 'blue' for v in shap_effects]
axes[1, 1].barh(shap_features, shap_effects, color=shap_colors)
axes[1, 1].set_title(f"SHAP: Local explanation (pred ${mystery_pred*100_000:,.0f})")
axes[1, 1].set_xlabel("SHAP Value (effect on prediction)")
plt.suptitle("Four Ways to Explain the Same Prediction", fontsize=16, fontweight='bold')
plt.tight_layout()
plt.show()
What do we see when we put them side by side?
Agreement: All four methods identify MedInc (median income) as the most important positive driver for this prediction. The PDP shows income’s strong upward slope globally. The ICE curves confirm that most individual houses follow that pattern. LIME and SHAP both assign MedInc the largest positive weight for this specific house.
Divergence: LIME’s exact numbers will shift slightly each time you run it (as we demonstrated). SHAP’s values are deterministic — you get the same answer every time. PDP and ICE show the global trend but can’t explain why this specific house’s prediction deviates from the average trend. And none of the four methods fully handles the correlation between latitude and longitude — that’s a known limitation we’ll address in the next article.
So which method should you use? Here’s a decision flowchart in plain English:
- Do you need to explain one specific prediction to a stakeholder? → LIME or SHAP. LIME is faster and more intuitive; SHAP is more rigorous and deterministic.
- Do you need to understand how a feature affects the model overall? → PDP. It’s the simplest global plot.
- Do you suspect the feature’s effect differs across subgroups? → ICE. It unhides heterogeneity the PDP averages away.
- Do you need theoretical guarantees (fairness, regulatory compliance)? → SHAP. Shapley values are uniquely fair under well-defined axioms.
- Are you in a hurry with a big model? → TreeSHAP (for tree models) or LIME. KernelSHAP is slow.
Here’s a quick-reference table of limitations:
| Method | Speed | Handles Correlated Features? | Scope | Deterministic? | Model Compatibility |
|---|---|---|---|---|---|
| PDP | Fast | No (independence assumption) | Global | Yes | Any |
| ICE | Fast | No (same as PDP) | Global | Yes | Any |
| LIME | Fast | Partially (local neighborhood) | Local | No (random sampling) | Any |
| SHAP (Tree) | Fast | No (feature ordering) | Both | Yes | Tree models only |
| SHAP (Kernel) | Slow | No (feature ordering) | Both | Yes | Any |
In plain English: PDP shows the average story. ICE reveals the subplots. LIME gives a quick, intuitive local translation. SHAP gives a rigorous, game-theory-backed translation that works both locally and globally.
Recap and What’s Next
We’ve covered a lot of ground. Here’s what to remember:
- PDP averages feature effects across the whole dataset. It’s simple and global, but it assumes features are independent — an assumption that’s often violated.
- ICE unhides the individual curves that PDP averages over. It reveals heterogeneous effects but shares PDP’s independence assumption.
- LIME builds a local surrogate model to explain one prediction at a time. It’s fast and intuitive, but unstable — run it twice and you may get different answers.
- SHAP uses Shapley values from game theory to fairly assign each feature’s contribution. It’s deterministic (with TreeExplainer), bridges local and global, but can be slow for non-tree models.
The hardest parts, revisited:
- PDP’s independence assumption means it can show you predictions for absurd data points that don’t exist in reality.
- LIME’s instability means you should be cautious using it for high-stakes, one-shot explanations.
- SHAP’s computational cost (with KernelExplainer) can be prohibitive for large models and datasets.
So where do we go from here? All four methods we’ve learned today struggle with correlated features. In the next article — “When PDP Lies: Permutation Importance and Accumulated Local Effects (ALE) Plots” — we’ll learn the tools that handle correlated features correctly. ALE plots are the natural evolution of PDP and ICE, designed specifically to avoid the “absurd data point” problem.
Now that you can explain any prediction, the next step is knowing when your explanation itself is trustworthy.
Check Your Understanding
Remember
- What is the key difference between a global and a local explanation?
- Which method uses Shapley values from cooperative game theory?
Understand 3. In your own words, why does the PDP’s independence assumption cause problems when features are correlated? 4. Why might an ICE plot show a fan of diverging curves even when the PDP is a smooth, monotonic line?
Apply 5. You’ve trained a random forest to predict customer churn. A stakeholder asks, “What’s the single biggest driver of churn across all our customers?” Which method do you reach for first, and why? 6. A specific customer calls to ask why they were flagged as high-risk for churn. Which method(s) would you use to answer their question?
Analyze 7. You run LIME twice on the same instance and get different top features. A colleague says LIME is broken. How would you explain what’s happening and whether the explanation is still useful? 8. Compare the information you get from a SHAP waterfall plot versus a PDP. What can the waterfall plot tell you that the PDP cannot?
Evaluate 9. A regulator requires that your loan-decision explanations be deterministic and theoretically justified. Which method(s) meet this bar, and which fall short? Justify your answer. 10. Your dataset has highly correlated features (e.g., temperature and humidity). A teammate suggests using PDP to understand the model. Would you endorse this choice? Why or why not?
Create 11. Design an explanation dashboard for a fraud-detection model. Which combination of methods would you include to serve both data-science auditors (who want global understanding) and fraud investigators (who want per-case explanations)? Sketch what each panel would show.
Apply What You Learned is for Supporter and Insider subscribers.
Subscribe to unlock the exercises on this post.
See plansRelated articles
- Explainability Under review
Reference: Model Explainability Techniques
A side-by-side reference applying PDP, ICE, permutation importance, LIME, and SHAP to the same model so you can see what each tells you and where they diverge.
- Explainability Under review
Machine Learning In Banking And Finance Credit Ris
Picture this: you're a data scientist at a mid-sized bank. Every morning, three different problems land on your desk.
- Explainability Under review
LIME vs. SHAP: Choosing the Right 'Translator' for Your Black-Box Models
Learn how LIME's fast local perturbations and SHAP's game-theoretic Shapley values explain black-box model predictions, and when to use each for your projects.
- Explainability Under review
Bagging Vs Boosting The Difference Ensemble Diagra
Let’s start with a single decision tree. A deep tree memorizes every detail of the training data – including the noise. That’s **high variance**: change the training set slightly, and the tree’s predictions change a lot.
Looking for something else?
Search every article by title, summary or topic.