Feature importance tells you which columns matter. It does not tell you how they matter. Do sales rise with temperature forever, or do they level off? A partial dependence plot (PDP) answers this. It shows how the model’s average prediction changes as one feature moves. In this lesson you will make PDPs with scikit-learn, build one by hand to see the trick behind it, and look at single rows with ICE curves.
In this lesson you will learn
- What partial dependence shows and how to read it
- How to use
partial_dependencefrom scikit-learn - How partial dependence is computed, step by step
- What ICE curves add for single rows
- When partial dependence can mislead you
You should know permutation feature importance and gradient boosting.
The Idea
Suppose you want to know how temperature affects a model’s sales forecast. You cannot just look at hot days, because hot days may also differ in price or rain. Partial dependence uses a cleaner experiment. It takes the whole dataset, sets temperature to 20 °C for every row, and averages the predictions. Then it does the same for 21 °C, 22 °C and so on. Only temperature changes; every other column keeps its real values. The curve of those averages is the PDP.
Partial Dependence With scikit-learn
We make ice-cream sales data where we know the truth. Sales climb by 10 per degree up to 32 °C and then stay flat. Each taka of price lowers sales by 2. Rain also lowers sales. We fit a gradient boosting model and ask it what it learned.
import numpy as np
import pandas as pd
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.inspection import partial_dependence
# Ice-cream sales. Sales rise with temperature up to about 32 C, then
# level off (people stay indoors). Price lowers sales in a straight line.
rng = np.random.default_rng(2)
n = 1500
df = pd.DataFrame({
"temp": rng.uniform(15, 40, n),
"price": rng.uniform(20, 60, n),
"rain_mm": rng.exponential(5, n),
})
sales = (100 + 10 * np.minimum(df["temp"], 32) - 2 * df["price"]
- 1.5 * df["rain_mm"] + rng.normal(0, 10, n))
model = GradientBoostingRegressor(random_state=0).fit(df, sales)
pd_temp = partial_dependence(model, df, ["temp"], grid_resolution=6, method="brute")
print("temperature average predicted sales")
for t, s in zip(pd_temp["grid_values"][0], pd_temp["average"][0]):
print(f" {t:5.1f} C {s:7.1f}")
pd_price = partial_dependence(model, df, ["price"], grid_resolution=5, method="brute")
print("\nprice average predicted sales")
for p, s in zip(pd_price["grid_values"][0], pd_price["average"][0]):
print(f" {p:5.1f} tk {s:7.1f}")
Output
temperature average predicted sales
16.4 C 176.9
20.9 C 224.5
25.4 C 265.7
29.9 C 314.8
34.4 C 333.4
38.9 C 332.1
price average predicted sales
22.3 tk 311.3
31.1 tk 294.6
40.0 tk 273.0
48.8 tk 257.5
57.6 tk 244.2
- From 16.4 °C to 29.9 °C, predicted sales rise by about 138, which is roughly 10 per degree. Above about 32 °C the curve goes flat. The model found the plateau without being told.
- For price, sales drop by about 67 across 35.3 taka, close to the true slope of −2 per taka.
- By default the grid runs from the 5th to the 95th percentile of the feature. This avoids the thin edges where the model has seen little data.
method="brute"makes the function average real predictions. For boosted trees the default"recursion"method is faster, but its values are shifted by a constant, so the shape is right but the numbers are not actual sales.
To draw the picture directly, use PartialDependenceDisplay.from_estimator(model, df, ["temp", "price"]) from sklearn.inspection. It needs matplotlib.
Partial Dependence by Hand
import numpy as np
import pandas as pd
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.inspection import partial_dependence
rng = np.random.default_rng(2)
n = 1500
df = pd.DataFrame({
"temp": rng.uniform(15, 40, n),
"price": rng.uniform(20, 60, n),
"rain_mm": rng.exponential(5, n),
})
sales = (100 + 10 * np.minimum(df["temp"], 32) - 2 * df["price"]
- 1.5 * df["rain_mm"] + rng.normal(0, 10, n))
model = GradientBoostingRegressor(random_state=0).fit(df, sales)
# Partial dependence by hand: set EVERY row's temp to one value,
# predict, and average. Repeat for each value.
for t in (20, 30, 38):
copy = df.copy()
copy["temp"] = t
preds = model.predict(copy)
print(f"temp={t}: average {preds.mean():6.1f} "
f"(first 3 rows: {preds[:3].round(1)})")
# The library gives the same averages
res = partial_dependence(model, df, ["temp"], method="brute",
custom_values={"temp": [20, 30, 38]})
print("library :", res["average"][0].round(1))
# ICE: kind="individual" keeps one curve per row instead of the average
ice = partial_dependence(model, df.head(3), ["temp"], kind="individual",
custom_values={"temp": [20, 30, 38]})
print("ICE shape :", ice["individual"].shape, "-> (outputs, rows, grid points)")
Output
temp=20: average 213.2 (first 3 rows: [219.4 242.9 197.4])
temp=30: average 314.8 (first 3 rows: [319.4 348.1 297.4])
temp=38: average 333.0 (first 3 rows: [336. 364.4 317.7])
library : [213.2 314.8 333. ]
ICE shape : (1, 3, 3) -> (outputs, rows, grid points)
- For each temperature we copy the data, overwrite the
tempcolumn, predict, and average. That is the whole method. - Our averages (213.2, 314.8, 333.0) match the library’s exactly.
- The first three rows each have their own predictions. Each row’s line of predictions across temperatures is an ICE curve (Individual Conditional Expectation). The PDP is the average of all ICE curves.
kind="individual"returns the ICE values.kind="both"returns ICE curves and their average together.
When to Look at ICE Curves
An average can hide differences. Suppose hot weather raises sales in a park but lowers them in a shopping mall. The two effects cancel out, and the PDP looks flat. The ICE curves would show two groups of lines going in opposite directions. If your ICE curves are roughly parallel, the PDP is a fair summary. If they cross or fan out, the feature works together with other features.
| Tool | Question it answers |
|---|---|
| Permutation importance | How much does the model rely on this feature? |
| Partial dependence | On average, how does the prediction change as this feature changes? |
| ICE curves | Does the effect differ from row to row? |
| Two-way PDP | How do two features act together? |
A warning about linked features
Partial dependence creates rows that may never happen in real life, such as a 40 °C day with 50 mm of rain. If two features are strongly linked, the model is guessing on those odd rows, and the PDP can be misleading. Check how your features are related before you trust the curve.
Common Mistakes
- Reading a PDP as cause and effect. It shows what the model does, not what the world does. A model can learn a link that is not causal.
- Trusting the ends of the curve. Few rows sit at the extremes, so the model has little to go on there.
- Ignoring linked features. See the warning above.
- Comparing “recursion” values with real targets. Use
method="brute"if you need actual prediction levels.
Practice Exercises
Exercise 1. Get the partial dependence of rain_mm at 0, 5, 10 and 20 mm. What slope do you expect?
Show answer
res = partial_dependence(model, df, ["rain_mm"], method="brute",
custom_values={"rain_mm": [0, 5, 10, 20]})
print(res["average"][0].round(1))
The data was made with −1.5 sales per mm, so you might expect a fall of about 30 from 0 to 20 mm. The model gives about 22 (280.7 down to 258.3). Days with that much rain are rare, so the model has learned the far end less well.
Exercise 2. How would you get a two-way partial dependence for temperature and price together?
Show answer
Pass both names in one list: partial_dependence(model, df, ["temp", "price"]). The result is a grid of averages with one value for each pair of grid points. With the display class, write the pair as a tuple: PartialDependenceDisplay.from_estimator(model, df, [("temp", "price")]). It is drawn as a contour map.
Frequently Asked Questions
Does partial dependence work with any model?
Yes. The brute method only needs a model that can predict, so it works for forests, boosting, SVMs, neural networks and pipelines. For classifiers it averages predicted probabilities.
How are partial dependence plots different from SHAP values?
A PDP shows one average curve per feature across the whole dataset. SHAP, from the separate shap package, splits each single prediction into a share for every feature. SHAP explains individual rows; PDPs show overall trends.
Summary
- A PDP shows how the average prediction changes as one feature changes.
- It is built by overwriting one column, predicting and averaging.
- ICE curves show the same thing for each single row.
- Linked features and sparse ends can make PDPs misleading.
