# Partial Dependence and ICE Plots in Python with scikit-learn

> Plot partial dependence (PDP) and individual conditional expectation (ICE) curves in scikit-learn with PartialDependenceDisplay.from_estimator, including centered ICE, two-way plots and the method="brute" vs "recursion" difference.

Source: https://www.pythoncharts.com/machine-learning/partial-dependence-ice-plot-python/ | Published: 2026-11-25 | Author: Alex Scott | Category: Machine Learning | Tags: machine learning, scikit-learn, partial dependence, ice plot, model interpretation, gradient boosting, matplotlib

A partial dependence plot (PDP) shows how a model's average prediction changes as one feature varies, with everything else left as it is in the data. In scikit-learn, use `PartialDependenceDisplay.from_estimator(model, X, ["feature"])`. Add `kind="both"` to overlay an ICE line for each individual row, which reveals when the average hides different groups. The code targets scikit-learn 1.9.

## Quick Example

This fits a gradient boosting model on simulated used-car prices and plots the partial dependence of price on three features. It runs without downloads.

```python
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn.ensemble import HistGradientBoostingRegressor
from sklearn.inspection import PartialDependenceDisplay
from sklearn.model_selection import train_test_split

rng = np.random.default_rng(41)
n = 3000
age = rng.uniform(0, 15, n)
mileage = (age * 11_000 + rng.normal(0, 12_000, n)).clip(1_000)
engine = rng.choice([1.2, 1.6, 2.0, 3.0], n, p=[0.25, 0.35, 0.3, 0.1])
premium = rng.integers(0, 2, n)
price = (12_000 + 5_000 * engine + premium * 14_000
         - (900 + 1_100 * premium) * age - 0.04 * mileage + rng.normal(0, 1_200, n))

X = pd.DataFrame({"age": age, "mileage": mileage, "engine_size": engine, "premium": premium})
X_train, X_test, y_train, y_test = train_test_split(X, price, test_size=0.25, random_state=0)
model = HistGradientBoostingRegressor(random_state=0).fit(X_train, y_train)

fig, ax = plt.subplots(1, 3, figsize=(11, 3.6), sharey=True)
PartialDependenceDisplay.from_estimator(
    model, X_train, ["age", "mileage", "engine_size"],
    kind="average", method="brute", grid_resolution=40, ax=ax,
    line_kw={"color": "#2f6690", "lw": 2},
)
plt.show()
```

![Three partial dependence plots of predicted car price: falling steeply with age from about 23,000 to 3,000, falling gently with mileage, and rising with engine size](https://www.pythoncharts.com/machine-learning/partial-dependence-ice-plot-python/images/pdp-quick-example.png)

The model reaches a test R² of 0.981. Predicted price falls from about 23,000 for a new car to about 3,000 at 14 years, drops more slowly with mileage, and rises with engine size. The small tick marks on the x-axis are deciles of the feature, and they show where the data is dense. Be skeptical of the curve where ticks are sparse, since the model is extrapolating there.

## Why Use `method="brute"`?

For `HistGradientBoostingRegressor` and other supported tree models, `kind="average"` uses `method="recursion"` by default. That is fast, but for gradient boosting it leaves out the model's initial constant prediction, so the curve is shifted. In this example the recursion curve starts near 10,500 instead of 23,400, about 12,900 too low. The shape is correct and the level is not. Passing `method="brute"` predicts on real rows and gives values on the true price scale. `kind="individual"` and `kind="both"` always use brute force.

## What Do ICE Lines Add?

A PDP is an average. Individual conditional expectation (ICE) lines draw one curve per row, so you can see whether the average describes anyone. In this data, premium brands lose value faster with age (about 2,000 per year, against 900 for standard brands). The average mixes them.

```python
from sklearn.inspection import partial_dependence

sub = X_train.sample(300, random_state=1)
res = partial_dependence(model, sub, ["age"], kind="both", grid_resolution=40)
grid, ice, avg = res["grid_values"][0], res["individual"][0], res["average"][0]

fig, ax = plt.subplots(figsize=(7, 4.4))
for line, p in zip(ice, sub["premium"]):
    ax.plot(grid, line, color="#d1495b" if p else "#2f9e8f", alpha=0.18, lw=1)
ax.plot(grid, avg, color="black", lw=3, label="Partial dependence (average)")
ax.set_xlabel("age (years)")
ax.set_ylabel("Predicted price")
ax.legend()
plt.show()

premium = sub["premium"].to_numpy() == 1
print("slope per year, premium:", round(np.polyfit(grid, ice[premium].mean(axis=0), 1)[0]))
print("slope per year, standard:", round(np.polyfit(grid, ice[~premium].mean(axis=0), 1)[0]))
print("slope per year, average:", round(np.polyfit(grid, avg, 1)[0]))
```

![ICE lines for 300 cars colored by brand tier: premium lines start higher and fall faster than standard lines, with the black average line between the two groups](https://www.pythoncharts.com/machine-learning/partial-dependence-ice-plot-python/images/ice-lines-by-group.png)

The fitted slopes are about -1,975 per year for premium cars, -1,076 for standard cars and -1,505 for the average. The built-in truth is -2,000 and -900. The black average line fits neither group well, and the ICE lines show why. Here the coloring comes from a column we know about. When you do not know which column explains the spread, look for ICE lines that fan out or cross, which signals an interaction between the feature and something else.

## Centered ICE Plots

Starting levels differ a lot between rows, which makes slopes hard to compare. `centered=True` shifts every line so it starts at zero:

```python
fig, ax = plt.subplots(figsize=(7, 4.4))
PartialDependenceDisplay.from_estimator(
    model, sub, ["age"], kind="both", centered=True, subsample=150, random_state=0, ax=ax,
    ice_lines_kw={"color": "#9aa5b1", "alpha": 0.4}, pd_line_kw={"color": "black", "lw": 3},
)
plt.show()
```

![Centered ICE plot: all lines start at zero and split into two bundles, one reaching about minus 14,000 and one about minus 25,000 at age 14, with the average between them](https://www.pythoncharts.com/machine-learning/partial-dependence-ice-plot-python/images/ice-centered.png)

The lines now split into two clear bundles, one ending around -14,000 and the other around -25,000 at age 14. The average, near -19,500, sits in the gap between them. `subsample=150` limits the number of ICE lines drawn.

## Two-Way Partial Dependence

Pass a tuple to see how two features act together:

```python
fig, ax = plt.subplots(figsize=(6.2, 4.6))
PartialDependenceDisplay.from_estimator(
    model, X_train, [("age", "mileage")], kind="average", method="brute",
    grid_resolution=30, ax=ax, contour_kw={"cmap": "viridis"},
)
plt.show()
```

![Two-way partial dependence contour of price over age and mileage: contour bands are nearly vertical, so price depends mainly on age](https://www.pythoncharts.com/machine-learning/partial-dependence-ice-plot-python/images/pdp-two-way.png)

The bands run nearly vertically, which means that once age is known, mileage adds little. That fits the data: mileage is driven by age and has a small direct effect (0.04 per mile).

## PDP vs ICE vs SHAP

| Tool | Shows | Good for | Watch out for |
|---|---|---|---|
| PDP | Average prediction vs one feature | A quick global view | Hides subgroups and interactions |
| ICE | One curve per row | Spotting heterogeneity | Cluttered with many rows, so use `subsample` |
| Two-way PDP | Two features together | Interactions between a pair | Sparse regions are extrapolation |
| [SHAP dependence](https://www.pythoncharts.com/machine-learning/shap-plots-python/) | Per-row contribution, colored by a second feature | Interactions and local explanations | Depends on a SHAP explainer |

## Practical Tips

- Correlated features distort PDPs. When age and mileage move together, the PDP averages over combinations that rarely occur in the data (a 14-year-old car with 5,000 miles). The tick marks help you spot this.
- Use `categorical_features=["premium"]` for categorical columns, which draws bars instead of a line.
- Plot on held-out data or a sample of training data, and pass `grid_resolution` and `percentiles` to control the range. The default `percentiles=(0.05, 0.95)` trims extreme values.
- A PDP describes the model, not the world. It shows what the model does, which is only as good as the model.
- Use [permutation importance](https://www.pythoncharts.com/machine-learning/feature-importance-python/) to decide which features deserve a PDP.

## Similar Topics

- [SHAP Plots in Python: Beeswarm, Bar, Waterfall, and Dependence](https://www.pythoncharts.com/machine-learning/shap-plots-python/)
- [Feature Importance in Python: Impurity vs Permutation Importance](https://www.pythoncharts.com/machine-learning/feature-importance-python/)
- [Machine Learning Charts in Python: A Guide to Evaluating and Exploring Models](https://www.pythoncharts.com/machine-learning/machine-learning-python-guide/)
