Sub topic 10
Reading One-Way and Two-Way Partial Dependence Plots
This chapter assumes you can fit a scikit-learn regressor and evaluate it on a held-out split. It also assumes you know how partial dependence is computed: set a feature to each grid value for every row, predict, and average. The goal here is interpretation. You will learn what each part of a plot means and what you can and cannot conclude from it.
What a one-way plot shows
A one-way partial dependence plot (PDP) has the feature's grid values on the x-axis. The y-axis is the model's average prediction when every row is forced to that value. For a regressor, the y-axis is in target units. For a classifier, it is a probability or a decision-function value, depending on the response_method.
Three parts of the plot carry information:
- Direction. Does the curve rise, fall, or stay flat as the feature increases?
- Shape. Is it linear, a plateau, a step, or a hump? Tree ensembles produce staircase-like curves because their predictions are piecewise constant.
- Strength. How far does the curve move vertically compared with the spread of the target?
Strength is the part people misjudge. A curve that looks steep may span only 0.1 target units, while another feature's curve spans 1.5. Compare features on a common y-axis. scikit-learn gives the one-way panels of a single display a shared y-range for this reason.
A PDP shows how the model behaves, not how the world behaves. If the model has learned a spurious pattern, the PDP will show it faithfully.
Producing the plots
The following script is self-contained. It trains a forest, then draws two one-way plots and one two-way plot in a single display. It needs scikit-learn 1.3 or newer.
import matplotlib.pyplot as plt
from sklearn.datasets import fetch_california_housing
from sklearn.ensemble import RandomForestRegressor
from sklearn.inspection import PartialDependenceDisplay
from sklearn.model_selection import train_test_split
X, y = fetch_california_housing(as_frame=True, return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
model = RandomForestRegressor(n_estimators=100, n_jobs=-1, random_state=0)
model.fit(X_train, y_train)
X_sample = X_test.sample(500, random_state=0)
fig, ax = plt.subplots(1, 3, figsize=(14, 4), constrained_layout=True)
PartialDependenceDisplay.from_estimator(
model,
X_sample,
["MedInc", "HouseAge", ("MedInc", "AveOccup")],
kind="average",
grid_resolution=20,
method="brute",
ax=ax,
)
plt.show()Some arguments need explanation:
grid_resolution=20sets the number of grid points per feature. The two-way panel evaluates 20 × 20 = 400 grid cells, and each cell requires predictions for every row.method="brute"runs the substitute-and-average procedure literally, so the result matches the hand-written version from the previous chapter.- Using 500 rows keeps the cost to roughly 400 × 500 = 200,000 predictions for the surface. Use more rows when you need smoother averages.
- By default the grid runs from the 5th to the 95th percentile of the feature (
percentiles=(0.05, 0.95)). This trims outliers, but it also hides behavior at the extremes.
Reading the tick marks
scikit-learn draws small tick marks along the x-axis at the deciles of the feature's data. They show where the data is dense. Treat the curve as trustworthy where ticks are close together, and as an extrapolation where they are sparse or absent.
On the California housing data, MedInc (median income, in tens of thousands of dollars) is dense at low values and thin at high values. Its curve typically rises steeply through the dense region and flattens or turns noisy near the right edge. That flattening may be real saturation, or it may reflect few training samples there. The tick marks tell you which is more plausible, but only more data can confirm it.
Two-way plots
A two-way PDP varies two features together over a grid. scikit-learn draws it as a filled contour plot. Each contour band is a range of average predicted values, and the tick marks appear on both axes.
Read it in this order:
- Trace the contours along one axis, with the other axis fixed. This gives the effect of that feature at a given level of the other.
- Look at the contour spacing. Evenly spaced, parallel contours mean the effects combine without interaction.
- Look for bending or fanning. If the slope of the contours along
MedIncchanges asAveOccupchanges, the two features interact.
The distinction is between a main effect and an interaction. The plot shows the combined average effect. It does not separate the two directly, so you must check whether the surface is additive.
Checking additivity numerically
Eyeballing contours is unreliable. A direct check is to double-center the two-way surface: subtract each row mean and each column mean, then add back the grand mean. If the effects are purely additive, the result is zero everywhere. Any remaining pattern is the interaction part of the average surface.
import numpy as np
from sklearn.inspection import partial_dependence
pd2 = partial_dependence(
model,
X_sample,
[("MedInc", "AveOccup")],
kind="average",
grid_resolution=20,
method="brute",
)
surface = pd2["average"][0] # shape: (grid for MedInc, grid for AveOccup)
residual = (
surface
- surface.mean(axis=1, keepdims=True)
- surface.mean(axis=0, keepdims=True)
+ surface.mean()
)
print("Surface range: ", round(float(np.ptp(surface)), 3))
print("Interaction part:", round(float(np.ptp(residual)), 3))Compare the two ranges. If the interaction range is a small fraction of the surface range, an additive reading is reasonable. If it is a substantial fraction, the features work together and a one-way plot for either will mislead you about individual rows.
This residual measures interaction in the averaged surface only. Two opposing interactions in different parts of the data can cancel in the average and leave a residual near zero. ICE curves can still expose them.
Common misreadings
- Reading the y-axis as an absolute prediction for a typical row. The curve is the average over all rows with that feature forced to a value. No actual row may look like that.
- Reading flat as unimportant. A flat PDP can hide strong, opposite effects in different subgroups that average to zero. Check ICE curves before dropping a feature.
- Reading a curve as causal. Changing a feature in the real world may also change other features. The PDP changes only the one in the model.
- Trusting corners of a two-way plot. If two features are correlated, such as
MedIncandAveRooms, some grid combinations never occur in the data. The model's predictions there are extrapolations. - Over-reading small wiggles. A forest's curve has noise from finitely many splits and from the sample of rows. Look for patterns bigger than the jitter, and re-run with a different
random_statefor the row sample to see what is stable.
Choosing what to plot
Use a one-way PDP for features that rank high in permutation importance, since those have effects worth describing. Use a two-way PDP only for a specific pair you already suspect interacts, for example because domain knowledge says so or because ICE curves for one feature fan out. Two-way plots cost more to compute, and the number of pairs grows quickly with the number of features.
Summary of reading rules
| Question | Where to look | Warning sign |
|---|---|---|
| Which direction is the effect? | Slope of the one-way curve | Slope changes sign in a sparse region |
| How strong is the effect? | Vertical range on a shared y-axis | Comparing ranges across different y-axes |
| Is the shape trustworthy? | Tick marks along the x-axis | Large changes where ticks are sparse |
| Do two features interact? | Contour spacing and double-centered residual | Fanning or bending contours |
| Is a pair of values realistic? | Scatter plot of the two features | Contour bands over empty regions |
Exercise
A two-way PDP of MedInc and AveOccup shows parallel, evenly spaced contours, yet ICE curves for MedInc fan out strongly across rows. How can both be true, and what should you conclude?
Show answer
The two-way PDP shows only the average surface. Interactions with other features, or opposing interactions with AveOccup in different parts of the data, can cancel in the average and leave parallel contours. The fanning ICE curves show that individual rows respond differently to MedInc. Conclude that the additive reading is not safe, and find which other feature explains the spread, for example by coloring ICE curves by candidate features or plotting two-way PDPs for other pairs.
Exercise
You run the double-centering code and get a surface range of 2.4 and an interaction range of 0.05. In the one-way plot, MedInc is flat in its right-most quarter, where the tick marks are sparse. What can you say about each result?
Show answer
The interaction range is about 2% of the surface range, so the averaged surface is close to additive for this pair. The flat region of MedInc is not reliable evidence, because few rows support it. It may be true saturation or a lack of data, and the plot alone cannot tell you which.