Sub topic 9
Computing Partial Dependence by Hand and with scikit-learn
This chapter assumes you can train and score a scikit-learn model on a train/test split, and that you know basic NumPy and pandas. It also assumes you have met the idea of partial dependence: the average predicted response as one feature varies. Here you compute it yourself, then check your result against scikit-learn.
The three steps: grid, substitution, averaging
Partial dependence for one feature answers a narrow question. If every row in the data had feature value v, what would the model predict on average? You answer it for a series of values v, and the resulting curve is the partial dependence.
The computation has three parts:
- Grid. Choose the values of the feature to evaluate.
- Substitution. For each grid value, copy the data and overwrite the feature column with that single value in every row. All other columns keep their real values.
- Averaging. Predict on the modified copy and average the predictions.
In symbols, for feature set S and the remaining features C, the estimate at value v is:
PD(v) = (1/n) * sum over rows i of f(v, x_i,C)
where f is the model and x_i,C holds row i's other features. Each grid value costs one full pass of predict over the dataset.
Setting up the model
The examples use the California housing data and a random forest. Run this block first. Every later block reuses model, X_test, and y_test.
from sklearn.datasets import fetch_california_housing
from sklearn.ensemble import RandomForestRegressor
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)The target is median house value in units of $100,000. MedInc is median income in a block group, in units of $10,000. AveOccup is average household size.
Computing it by hand
This function follows the three steps directly.
import numpy as np
def partial_dependence_1d(model, X, feature, grid_size=20):
grid = np.linspace(X[feature].quantile(0.05), X[feature].quantile(0.95), grid_size)
averages = []
for value in grid:
X_mod = X.copy()
X_mod[feature] = value
averages.append(model.predict(X_mod).mean())
return grid, np.array(averages)
grid, pd_values = partial_dependence_1d(model, X_test, "MedInc")
for g, p in zip(grid[::4], pd_values[::4]):
print(f"MedInc={g:5.2f} average prediction={p:.3f}")The code makes several choices worth understanding.
The grid
The grid runs from the 5th to the 95th percentile of the feature, in evenly spaced steps. Trimming the tails matters for two reasons. Extreme values are rare, so the curve there rests on little real data. Substituting an extreme value into every row also forces the model to predict in regions where it has seen few examples. The evenly spaced grid is simple but can waste points where the data is sparse. Using quantiles of the feature as grid points would place more points where data is dense. scikit-learn exposes this through grid_resolution and percentiles.
The data you average over
The function takes the test set, but you could pass the training set. Partial dependence describes the model's behavior, not its accuracy, so it does not require held-out data the way permutation importance does. Using the test set is still a reasonable default. It keeps the averaging population consistent with the rest of your analysis. For large datasets, a random subsample of a few thousand rows gives nearly the same curve at a fraction of the cost.
The cost
For a grid of G values and n rows, the model predicts G * n times. With 5,000 test rows and 20 grid values that is 100,000 predictions. A forest of 100 trees handles this in seconds. A slow model, a large grid, or a two-way plot (where cost multiplies across both grids) can make it expensive. Subsampling rows is the usual remedy.
Reading the output
The numbers rise as income rises, which matches intuition. The values are average predictions, so the y-axis is in the same units as the target. A curve that moves from 1.6 to 3.4 says that, across the population, moving everyone from a low to a high income raises the average predicted value by about $180,000. It does not say any single house would change by that amount. The next chapters on ICE curves cover that distinction.
Computing it with scikit-learn
scikit-learn provides the same computation in sklearn.inspection. The function partial_dependence returns the numbers, and PartialDependenceDisplay draws them.
from sklearn.inspection import partial_dependence
result = partial_dependence(
model, X_test, ["MedInc"], kind="average", grid_resolution=20
)
print(result["grid_values"][0][:3])
print(result["average"][0][:3])The result is a dictionary-like object. For kind="average", the key "grid_values" holds one array per requested feature, and "average" holds the matching curves. Older scikit-learn versions named the grid key "values", so check your version if the key is missing.
You can confirm that your hand-written function agrees with the library:
lib_grid = result["grid_values"][0]
lib_avg = result["average"][0]
print(np.allclose(np.interp(grid, lib_grid, lib_avg), pd_values, atol=0.05))The two are close but not identical, because the grids differ slightly. The library uses 20 points between the 5th and 95th percentiles by default, but it builds them from the unique values of the feature when there are few of them, and the interpolation here adds a small error. If you pass your own grid positions to the library's internals, the two match closely. The point of the check is to see that the idea behind the library is the one you wrote.
Plotting one feature
import matplotlib.pyplot as plt
from sklearn.inspection import PartialDependenceDisplay
fig, ax = plt.subplots(figsize=(6, 4))
PartialDependenceDisplay.from_estimator(model, X_test, ["MedInc"], ax=ax)
plt.show()The plot shows the curve, and along the bottom edge a small tick mark for each decile of the feature. Those ticks are the quickest check on where the curve is trustworthy. Where ticks are sparse, the curve is built from few real observations.
Plotting two features
A two-way plot varies two features together. The grid becomes a 2D lattice, and every lattice point gets its own substitution and average.
fig, ax = plt.subplots(figsize=(6, 5))
PartialDependenceDisplay.from_estimator(
model, X_test, [("MedInc", "AveOccup")], ax=ax
)
plt.show()Pass a tuple inside the list to request a pair. The result is a contour plot. If the effects of the two features simply added, the contours would look like parallel stripes. Contours that bend or cluster show an interaction: the effect of one feature depends on the level of the other.
Choosing a method for the computation
scikit-learn has two internal strategies. The "brute" method does exactly what the hand-written function does. The "recursion" method is faster, but it works only for some tree models and uses a weighted traversal of the trees instead of repeated prediction. For random forests, method="auto" chooses brute force for RandomForestRegressor, so the default matches your code. Gradient boosting models can use recursion, and for those the results may differ slightly from brute force because recursion weights by training sample counts instead of averaging over the data you supply.
| Setting | What it does | When to use it |
|---|---|---|
| `kind="average"` | Returns the averaged curve | Default, one line per feature |
| `kind="individual"` | Returns one curve per row | Checking heterogeneity |
| `kind="both"` | Returns both | Overlaying the average on individual curves |
| `grid_resolution` | Number of grid points | Raise for wiggly curves, lower for speed |
| `percentiles` | Range of the grid, default (0.05, 0.95) | Widen to see tails, with caution |
| `method` | `"brute"`, `"recursion"`, or `"auto"` | Use `"brute"` when you need results to match your own code |
Common errors
- Modifying the original data. Writing
X[feature] = valuewithout copying changes your test set for every later step. The hand-written function copies inside the loop for this reason. - Passing a NumPy array without feature names. With arrays, features are selected by integer position. With a DataFrame, you can use column names.
- Reading the curve outside the data. A feature range wider than the 5th to 95th percentile produces predictions for combinations the model never saw. Treat steep changes at the edges with suspicion.
- Confusing the curve with causation. The curve shows what the model does, not what happens in the world.
- Mixing up units. The curve is in target units. Rescaling the target rescales the plot.
Exercise
You run partial_dependence_1d on a training set of 20,000 rows with a 50-point grid and a random forest whose predict takes about 0.4 seconds per 20,000 rows. Roughly how long does the computation take, and what is the simplest way to cut it by a factor of ten without changing the grid?
Show answer
It makes 50 calls to predict, each taking about 0.4 seconds, so roughly 20 seconds. The simplest fix is to average over a random subsample of about 2,000 rows instead of all 20,000. Cost scales with grid size times row count, so one tenth of the rows gives one tenth of the time, and the curve changes very little.
Exercise
You plot a two-way partial dependence for features A and B and see contour lines that are parallel diagonal stripes. What does this tell you about how the model uses A and B?
Show answer
Parallel contours mean the effects of A and B add up. The effect of changing A is the same at every level of B, so the model shows little or no interaction between them in its averaged behavior. Bent or clustered contours would indicate an interaction.