Sub topic 12
Where Partial Dependence Misleads
This chapter assumes you can train a scikit-learn model, you have computed a partial dependence curve (grid, substitute, average), and you know what an ICE curve is. It covers the three main ways a partial dependence plot (PDP) can mislead you: extrapolation, the independence assumption, and hidden heterogeneity. It also shows how to check for each one.
The examples reuse the model, X_test, and y_test from the earlier chapters, a random forest fit on the California housing data.
What a PDP actually claims
For a feature x_S, the partial dependence function is the average prediction when x_S is forced to a value v for every row:
PD(v) = mean over rows i of f(v, x_C,i)
Here x_C,i holds the other features of row i, with their real values. The plot is only as trustworthy as these forced rows. Each forced row is a data point the model may never have seen. The average also hides any difference between rows. Each of the three pitfalls below comes from one of these two facts.
Pitfall 1: extrapolation
Extrapolation means the model is asked to predict in a region with little or no training data. A tree ensemble such as a random forest cannot predict outside the range of targets it saw. Beyond the edge of the data its prediction simply stays flat. A linear model continues its line forever. Neither behavior reflects reality, and a PDP over the full range of a feature shows both without warning.
Two habits reduce this risk.
- Restrict the grid to a central range. The hand-written function in the earlier chapter uses the 5th to 95th percentile for this reason. scikit-learn does the same through
percentiles=(0.05, 0.95), which is the default. - Show where the data lies. A rug of tick marks or a histogram under the curve tells the reader which parts of the curve rest on many rows and which rest on a few.
The code below counts how many test rows fall into each region of a feature, so you can see where the curve is thin.
import numpy as np
counts, edges = np.histogram(X_test["AveOccup"], bins=10)
for n, lo, hi in zip(counts, edges[:-1], edges[1:]):
print(f"{lo:8.2f} to {hi:8.2f}: {n} rows")In this dataset AveOccup (average household occupancy) has a long right tail with a few extreme values. Almost all rows sit in the first bin, and the later bins hold only a handful. A PDP drawn across the full range would show a curve where almost no data supports the right-hand side.
Pitfall 2: the independence assumption
When you set MedInc to a value for every row, you ignore the other features in that row. The method assumes the feature of interest is independent of the others. If it is not, many of the forced rows describe combinations that do not occur in the real world.
California housing has such pairs. Latitude and Longitude are strongly related, because houses lie along a coastline. AveRooms and AveBedrms also move together. If you force Latitude to 38 for every row, a row whose Longitude places it in the Pacific Ocean now describes a location that does not exist. The model still returns a number for it. That number enters the average with the same weight as a realistic row.
You can measure how unrealistic the forced rows are. The check below computes the correlation between two features and then compares the model's predictions on real rows with those on forced rows.
import numpy as np
print(X_test[["Latitude", "Longitude"]].corr().round(2))
forced = X_test.copy()
forced["Latitude"] = 38.0
real_pred = model.predict(X_test)
forced_pred = model.predict(forced)
print(f"mean prediction, real rows: {real_pred.mean():.3f}")
print(f"mean prediction, Latitude=38: {forced_pred.mean():.3f}")A strong correlation (the two columns are near -0.92 in this dataset) tells you that the PDP for either feature should be read with caution. The second half of the check shows what the PDP will plot: the average over every row, including the rows that make no geographic sense.
Correlation can also push the curve in a misleading direction. Suppose two features carry the same signal and the model splits its use of them. The PDP for each feature shows only part of the shared effect, and so each curve can look weaker than the real relationship.
What to do about it:
- Compute pairwise correlations before you trust a PDP, and look for pairs above roughly 0.7.
- Treat PDPs of correlated features as a description of the model's behavior on unrealistic inputs, not of the world.
- Consider a method that conditions on the other features, such as ALE (accumulated local effects), described in a later chapter.
- Where two features are strongly tied, plot them together with a two-way PDP, and mask or ignore the cells where there is no data.
Pitfall 3: hidden heterogeneity
The PDP is an average. Averages hide differences. If half the rows increase with a feature and half decrease, the average is flat, and the PDP says the feature does nothing. In fact the feature matters a great deal, but in opposite directions for two groups.
A small synthetic example makes this concrete. The target depends on x with a sign set by a binary feature group.
import numpy as np
import pandas as pd
from sklearn.ensemble import RandomForestRegressor
from sklearn.inspection import partial_dependence, permutation_importance
rng = np.random.default_rng(0)
n = 2000
x = rng.uniform(-1, 1, n)
group = rng.integers(0, 2, n)
y = np.where(group == 1, x, -x) + rng.normal(0, 0.1, n)
data = pd.DataFrame({"x": x, "group": group})
toy = RandomForestRegressor(n_estimators=100, random_state=0).fit(data, y)
pdp = partial_dependence(toy, data, ["x"], grid_resolution=5)
print("PDP of x:", np.round(pdp["average"][0], 2))
imp = permutation_importance(toy, data, y, n_repeats=5, random_state=0)
print("Importance of x:", round(imp.importances_mean[0], 2))The PDP values for x stay close to zero, because the two groups cancel out. Yet the permutation importance of x is large, since shuffling x destroys a model that depends on it. The two tools disagree, and the disagreement is the signal. A feature with high importance and a flat PDP is a candidate for an interaction.
ICE curves expose this. Each row gets its own line, and the plot shows two bundles that slope in opposite directions with a flat average running between them.
import matplotlib.pyplot as plt
from sklearn.inspection import PartialDependenceDisplay
fig, ax = plt.subplots(figsize=(6, 4))
PartialDependenceDisplay.from_estimator(
toy, data, ["x"], kind="both", subsample=200, random_state=0, ax=ax
)
plt.show()Other things that quietly distort a PDP
- Evaluating on the wrong data. A PDP computed on training data describes the model's behavior on rows it has fitted. That is usually fine for describing the model, but if the model overfits, the curve can follow noise. Use held-out data when you want the curve to reflect what the model does on new cases.
- Categorical and discrete features. A grid made of quantiles does not suit a feature with a few distinct values. Pass
categorical_featuresto scikit-learn, or list the values explicitly, so that each level is plotted as its own point. - Scale of the target. For classifiers the default response method may be a probability or a decision score. The two have different shapes, so state which one you plotted.
- Overreading small wiggles. Tree-based models produce steps and bumps that come from how the trees split. A bump of a few thousandths in the average is rarely a real effect. Fit the model with a different
random_stateand see whether the bump survives. - Causal language. A PDP describes how the model's predictions change. It does not show that changing the feature would change the real outcome.
A checklist before you report a PDP
| Question | How to check | If the answer is bad |
|---|---|---|
| Is the curve supported by data? | Histogram or rug under the grid | Narrow the percentiles |
| Are features correlated? | `X.corr()` on the feature pair | Use ALE, or a two-way plot |
| Does the average hide groups? | ICE curves with `kind="both"` | Report ICE, color by a suspect feature |
| Is importance high but the PDP flat? | Compare with permutation importance | Look for an interaction |
| Is the curve stable? | Refit with another seed | Do not report small bumps |
Exercise
A feature has a permutation importance of 0.25 on held-out data, but its partial dependence curve is almost flat. Give two possible explanations and one plot you would draw to tell them apart.
Show answer
One explanation is that the feature interacts with another feature, so its effect has opposite signs in different groups of rows, and the average cancels out. A second explanation is that the model's use of the feature is nonmonotonic in a way the 5th to 95th percentile grid mostly misses, or that the importance comes from a correlated partner whose shuffling also breaks the model. An ICE plot (kind="both") for the feature distinguishes the cases. Diverging ICE bundles point to an interaction, and a flat set of ICE lines points to the other explanations, which you would then check with a correlation table.
Exercise
You force Latitude to 38 for every row in the California housing test set. Why can the resulting average prediction mislead, and which check from this chapter warns you about it?
Show answer
Latitude and Longitude are strongly correlated, so forcing Latitude to a single value creates rows whose location does not exist, such as points in the ocean. The model still predicts for them and the predictions enter the average. The pairwise correlation check, X_test[["Latitude", "Longitude"]].corr(), warns about this. A value near -0.9 means the PDP for either feature is based on many unrealistic rows.