Sub topic 8
Partial dependence: the average effect of a feature
This chapter assumes you can train a scikit-learn model and score it on a held-out split. You should also be comfortable with pandas DataFrames and with the idea of a feature, a prediction, and a model's predict method. Permutation importance, covered earlier, tells you which features matter. Partial dependence answers a different question: how does the prediction change, on average, as one feature changes?
The question partial dependence answers
A fitted model is a function. It takes a row of feature values and returns a prediction. For a house-price model, one row might hold median income, house age, average occupancy, and so on, and the output is a price.
You often want to know what the model does with one feature, such as median income. Reading the raw predictions doesn't help, because every row differs in all the other features too. Some rows are expensive because of income and others because of location. The effect of income is mixed in with everything else.
Partial dependence (PD) separates it out with a controlled experiment on the model:
- Pick the feature you want to study.
- Choose a value for it, for example an income of 3.0.
- Overwrite that feature with 3.0 in every row of your dataset. Leave all other columns alone.
- Predict for all rows and average the predictions.
- Repeat for other values and plot average prediction against feature value.
The result is a curve. It shows the model's average response to the feature, with the other features left at the values they have in your data.
The definition
Call the feature of interest S and all remaining features C (for complement). The partial dependence function at a value v is:
PD(v) = (1 / n) * sum over i = 1..n of f(S = v, C = C_i)Here f is the model's prediction function, n is the number of rows, and C_i is the values of all other features in row i. Row i's own value of the studied feature is discarded and replaced by v.
This is a Monte Carlo estimate of an expectation. The true quantity integrates the model over the distribution of the other features. The empirical version replaces that integral with an average over the rows you have.
The diagram shows the data flow for one grid value.
A worked example you can run
A tiny model and a three-row dataset let you check the arithmetic by eye. The model is f(x1, x2) = 3*x1 + x1*x2. It has a main effect of x1 and an interaction between x1 and x2.
import pandas as pd
def f(df):
return 3 * df["x1"] + df["x1"] * df["x2"]
data = pd.DataFrame({"x1": [1.0, 2.0, 0.5], "x2": [0.0, 2.0, 4.0]})
for a in [0, 1, 2]:
modified = data.copy()
modified["x1"] = a
preds = f(modified)
print(f"x1={a}: predictions {preds.tolist()} -> mean {preds.mean():.1f}")The output is:
x1=0: predictions [0.0, 0.0, 0.0] -> mean 0.0
x1=1: predictions [3.0, 5.0, 7.0] -> mean 5.0
x1=2: predictions [6.0, 10.0, 14.0] -> mean 10.0Follow the steps for x1=1. Every row now has x1 = 1, so only x2 differs between rows. The three predictions are 3, 5, and 7, and their mean is 5. The mean of x2 in the data is 2, so the PD curve is 3a + 2a = 5a. That is a straight line with slope 5.
Notice that the original x1 values (1.0, 2.0, 0.5) never appear in the calculation. They are overwritten. Only the other columns, here x2, carry information from your data into the curve.
What the curve means and what it does not
The curve is the average of the model's behavior across your data. In this example, the three rows have slopes of 3, 5, and 7 with respect to x1, depending on x2. The PD curve reports 5, which none of the individual rows has exactly.
That single sentence is the main thing to remember about partial dependence. It is a summary of the model, and a summary hides variation. The tool that restores the hidden detail is the ICE curve, covered later in this tutorial.
Interactions can cancel out
The averaging can erase an effect entirely. Suppose the model is f(x1, x2) = x1 * (x2 - 2) and x2 has a mean of 2 in your data. Rows with x2 above 2 respond positively to x1. Rows with x2 below 2 respond negatively. The average is zero for every value of x1:
import pandas as pd
def g(df):
return df["x1"] * (df["x2"] - 2)
data = pd.DataFrame({"x1": [1.0, 2.0, 0.5], "x2": [0.0, 2.0, 4.0]})
for a in [0, 1, 2]:
modified = data.copy()
modified["x1"] = a
print(f"x1={a}: mean prediction {g(modified).mean():.1f}")Every line prints a mean of 0.0. The PD curve is flat, yet x1 strongly drives the model's output for each individual row. A flat curve means "no average effect." It does not mean "the feature is unused."
Where PD sits among the other tools
Partial dependence and permutation importance both treat the model as a black box, and both work by changing feature values and re-querying the model. They differ in what they report.
| Aspect | Permutation importance | Partial dependence |
|---|---|---|
| Question | How much does the model rely on this feature? | How does the prediction change as this feature changes? |
| Output | One number per feature, with a spread | A curve (or surface) per feature |
| Changes the feature by | Shuffling it among rows | Setting it to a fixed value in all rows |
| Needs true labels | Yes, to compute a score | No, it only uses predictions |
| Tells you direction | No | Yes |
The last two rows matter in practice. PD uses only the model's predictions, so you can compute it on data without labels. It also shows direction and shape (rising, falling, saturating, stepped), which importance scores cannot.
Assumptions behind the average
The averaging step is only a faithful description of the model's behavior when two conditions roughly hold.
- The studied feature is not strongly correlated with the others. When you set income to 3.0 in every row, you also keep each row's other features unchanged. If income and, say, house value of neighbors move together, some of the combinations you create are unrealistic. The model gets asked about inputs it has rarely or never seen, and its answers there are extrapolation, not knowledge.
- The average is a meaningful summary. If rows respond very differently to the feature, as in the cancellation example, one curve misrepresents them.
Later chapters return to both problems in detail. For now, keep in mind that the PD curve describes the model, not the real world. It tells you what the model does when you ask it these questions. It does not establish that changing the feature would change the real outcome.
Choosing the values to evaluate
The formula holds for any v, but you can only compute it at a finite set of values, called the grid. Two common choices:
- An evenly spaced grid between two percentiles of the feature, such as the 5th and 95th. Percentile limits keep you away from rare extreme values where the model has seen little data.
- The unique values of the feature, which suits categorical features and features with few distinct values.
Each grid point costs one predict call on a full copy of the dataset, so cost grows with grid size times dataset size. Large datasets are often subsampled for this reason. The next chapter builds this computation by hand and then uses scikit-learn's built-in version.
Summary of the idea
Partial dependence fixes one feature to a value for every row, predicts, and averages. Repeating this across a grid produces a curve of the model's average response. The curve gives direction and shape, needs no labels, and can hide heterogeneous effects through averaging. It is trustworthy to the degree that the artificial rows it creates resemble real data.
Exercise
A model is f(x1, x2) = 2x1 + x1x2, and the dataset has three rows with x2 values 0, 1, and 2 (the x1 values can be anything). What are the partial dependence values for x1 at 0, 1, and 2? Then say how the slope of each individual row's response to x1 relates to the PD slope.
Show answer
Set x1 = a in every row. The predictions are 2a + a*x2 for x2 = 0, 1, 2, which is 2a, 3a, and 4a. Their mean is 3a. So PD(0) = 0, PD(1) = 3, and PD(2) = 6. The individual rows have slopes 2, 3, and 4 with respect to x1. The PD slope of 3 is the average of those three slopes, and it matches the middle row only because x2 averages to 1.
Exercise
Why can you compute partial dependence on a dataset that has no true labels, while permutation importance cannot be computed on one?
Show answer
Partial dependence only compares the model's predictions across modified copies of the data, so it never needs the true target. Permutation importance measures the drop in a score such as R^2 or accuracy after shuffling a feature, and computing that score requires the true labels.