Sub topic 9
Computing Partial Dependence by Hand and with scikit-learn
This chapter assumes you can fit a scikit-learn regressor, split data into train and test sets, and use NumPy and pandas. It builds on the idea that partial dependence shows a feature's average effect on predictions. Here you compute it two ways and check that they agree.
The recipe
Partial dependence for one feature has three steps:
- Choose a grid of values for the feature.
- For each grid value, set that feature to the value in every row of the data, leaving the other columns unchanged. Then predict.
- Average the predictions. Each grid value gives one point on the curve.
The other features keep their observed values. That is why the curve describes an average over the data, not a single case.
Setup
This code builds the model used in every example below.
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)Computing it by hand
The function below follows the recipe directly. The grid runs from the 5th to the 95th percentile of the feature, so the extreme values do not stretch the axis.
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")The cost is one full predict call per grid value, so 20 grid points on 5,000 rows means 20 passes over 5,000 rows. Use a subsample of rows if prediction is slow.
Checking against scikit-learn
The library function sklearn.inspection.partial_dependence returns the same numbers. Setting grid_resolution=20 and the default 5% to 95% percentile range gives the same grid as the hand version.
from sklearn.inspection import partial_dependence
sk = partial_dependence(
model, X_test, ["MedInc"], kind="average", grid_resolution=20
)
print(np.allclose(sk["average"][0], pd_values))This should print True. If it prints False, check that you passed the same data and the same grid size.
Plotting with scikit-learn
PartialDependenceDisplay computes and draws the curve in one call. With kind="both", it overlays individual ICE curves on the average. Chapter 11 covers how to read ICE curves.
import matplotlib.pyplot as plt
from sklearn.inspection import PartialDependenceDisplay
fig, ax = plt.subplots(figsize=(7, 4))
PartialDependenceDisplay.from_estimator(
model, X_test, ["MedInc"], kind="both", subsample=200, random_state=0, ax=ax
)
plt.show()For a two-way plot, pass a tuple of two feature names. The library then evaluates a two-dimensional grid and draws a contour surface.
fig, ax = plt.subplots(figsize=(6, 5))
PartialDependenceDisplay.from_estimator(
model, X_test, [("MedInc", "AveOccup")], ax=ax
)
plt.show()A two-way grid of 20 by 20 needs 400 prediction passes. This is much slower than a one-way curve, so reduce grid_resolution or subsample rows for large models.
Common errors
- Using training data. Computing on
X_trainis allowed, but the curve then reflects the model's behavior on data it has seen. Prefer held-out rows for consistency with permutation importance. - Mutating the original frame. The hand version copies
Xfor each grid value. WithoutX.copy(), you overwrite your data. - Passing a feature name that does not exist. With a DataFrame, names must match the column labels exactly.
Exercise
Why does the hand-written function call X.copy() inside the loop, and what would go wrong without it?
Show answer
Assigning X[feature] = value modifies the DataFrame in place. Without a copy, the original test data would be overwritten with the last grid value, and every later computation, including the next grid value's other columns and any later use of X_test, would use corrupted data.