Sub topic 11
ICE curves: seeing the individual behind the average
This chapter assumes you can already compute a one-way partial dependence curve, either by hand or with PartialDependenceDisplay. It also assumes you have a fitted scikit-learn regressor and a held-out test set. Here you will take the partial dependence computation apart into its per-row pieces. Those pieces are called individual conditional expectation (ICE) curves. They show where an averaged curve is hiding something.
What an ICE curve is
A partial dependence curve is one line. For each grid value of a feature, it sets that feature to the value in every row, predicts, and averages the predictions.
An ICE curve keeps the predictions separate. For one row, it holds every other feature at that row's actual values. It then varies the chosen feature across the grid and records the prediction at each step. One row gives one curve, and 200 rows give 200 curves.
The relationship to partial dependence is exact. The partial dependence curve is the pointwise mean of all ICE curves, computed over the same grid and the same rows.
This is why ICE is a diagnostic for partial dependence and not a separate method. The two come from the same computation. Partial dependence discards the per-row information, and ICE keeps it.
Why the average can mislead
An average can be flat, or gently sloped, for very different reasons:
- Every row has a flat curve. The feature really does not matter.
- Half the rows rise and half fall by the same amount. The feature matters a lot, but the effects cancel in the mean.
- Every row has the same shape, shifted up or down by the other features. The feature has a consistent effect and only the baseline differs.
A single partial dependence line cannot tell these cases apart. ICE curves can, because you see the spread directly.
There are three patterns to look for:
| What you see | What it means |
|---|---|
| Curves roughly parallel, only vertically offset | The feature's effect is about the same for every row. Other features set the baseline. Little interaction. |
| Curves with different slopes, some crossing | The effect depends on other features. This is an interaction. |
| A bundle of curves that all follow the average, plus a few that depart | A subgroup behaves differently. Investigate which rows they are. |
Drawing ICE curves with scikit-learn
Setting kind="both" draws the ICE curves and the partial dependence curve together. This block includes the setup so it runs on its own.
import matplotlib.pyplot as plt
from sklearn.datasets import fetch_california_housing
from sklearn.ensemble import RandomForestRegressor
from sklearn.inspection import PartialDependenceDisplay
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)
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()The subsample=200 argument draws 200 randomly chosen rows for the ICE lines. Plotting all of the test rows (about 5,000 here) produces a solid blob that you cannot read. The random_state argument makes the chosen rows reproducible.
The thick line is the partial dependence curve. The thin lines are individual rows. How far the thin lines spread around the thick one tells you how much the average hides.
Subsampling and what it changes
Subsampling affects only how many ICE curves are drawn. It is not obvious whether the plotted average uses all rows or only the sample. In recent scikit-learn versions, kind="both" computes the average from the same subsampled rows, so the thick line can differ slightly from a full-data partial dependence curve. If you need the exact full-data average, compute it separately with kind="average" and compare. Differences should be small if the sample is representative.
Computing ICE by hand
Reproducing the computation shows exactly what the plot contains. This function extends the one-feature partial dependence function from the earlier chapter. It stores every row's predictions instead of only their mean.
import numpy as np
def ice_1d(model, X, feature, grid_size=20):
grid = np.linspace(X[feature].quantile(0.05), X[feature].quantile(0.95), grid_size)
curves = np.empty((len(X), grid_size))
for j, value in enumerate(grid):
X_mod = X.copy()
X_mod[feature] = value
curves[:, j] = model.predict(X_mod)
return grid, curves
X_sample = X_test.sample(200, random_state=0)
grid, curves = ice_1d(model, X_sample, "MedInc")
pd_curve = curves.mean(axis=0)
print(curves.shape) # (200, 20): one row of predictions per sampled house
print(pd_curve.round(2)) # the partial dependence curve over the same gridThe array curves has one row per sampled house and one column per grid value. Its column means are the partial dependence curve. You can verify this against PartialDependenceDisplay by passing the same subsample.
The grid uses the 5th to 95th percentile of the feature, as before. This keeps the curves away from the extreme tails where there is little data.
Centered ICE curves
Raw ICE curves start at different heights, because rows have different baseline predictions. A cheap house and an expensive house have very different curves even if the feature affects them identically. That vertical scatter makes slope differences hard to see.
Centered ICE (c-ICE) fixes this by subtracting each curve's value at a reference point, usually the first grid value. Every curve then starts at zero, and what remains is the change in prediction relative to that starting point.
centered = curves - curves[:, [0]]
# Spread of the effect at the right edge of the grid
end_effects = centered[:, -1]
print(f"mean change: {end_effects.mean():.3f}")
print(f"std of change: {end_effects.std():.3f}")
print(f"min / max: {end_effects.min():.3f} / {end_effects.max():.3f}")The mean of end_effects is the partial dependence change across the grid. The standard deviation is a rough measure of heterogeneity. If it is small compared with the mean, the curves are close to parallel. If it is as large as the mean, or larger, rows disagree strongly about the feature's effect.
This number is a screening heuristic and not a formal test. It depends on the grid endpoints, and it cannot catch curves that diverge in the middle and reconverge. Always look at the plot.
To plot the centered curves yourself:
fig, ax = plt.subplots(figsize=(7, 4))
ax.plot(grid, centered.T, color="steelblue", alpha=0.15, linewidth=0.8)
ax.plot(grid, centered.mean(axis=0), color="darkorange", linewidth=3, label="average")
ax.set_xlabel("MedInc")
ax.set_ylabel("Change in prediction vs. first grid value")
ax.legend()
plt.show()The transposed array centered.T has one column per row, which is what ax.plot expects for drawing many lines at once.
Finding what drives the differences
Seeing that curves differ is the first step. The next question is why. A practical approach:
- Compute the end-of-grid change for each sampled row, as in
end_effectsabove. - Fit or inspect a relationship between that change and the other features. A simple correlation table is a quick start. A shallow decision tree on
end_effectsis better for picking out thresholds. - Confirm with a two-way partial dependence plot for the candidate pair, such as
("MedInc", "AveOccup").
import pandas as pd
drivers = X_sample.assign(effect=end_effects)
print(drivers.corr()["effect"].drop("effect").sort_values().round(2))Correlation only catches monotone relationships. A feature that matters through a threshold may show a weak correlation. Treat the result as a lead to check with the two-way plot, not as a finding.
You can also color the ICE lines by another feature, for example by splitting rows into low and high AveOccup, and plot each group's average. If the group averages separate, you have found the interaction directly.
Limits of ICE
ICE inherits the weaknesses of partial dependence and adds some of its own.
- Extrapolation. Setting a feature to a grid value can produce a row that never occurs in real data. For example, a high
MedIncpaired with a very lowAveRoomsmay be implausible. The model's prediction there is unconstrained, and a curve segment can look dramatic for that reason alone. ICE shows this more plainly than the average, since a few implausible rows show up as odd lines. They do not disappear into the mean. Look for isolated lines that diverge only at one end of the grid. - Correlated features. When the chosen feature is strongly tied to another, individual curves cross regions where the combination is unrealistic. Interpretation of every line is then suspect.
- Readability. More than a few hundred lines becomes unreadable. Subsample, lower the line opacity, or use centered curves.
- Cost. The cost is one prediction pass over the data per grid point, the same as partial dependence. Expensive models with large samples are slow. Reduce
grid_sizeor the sample size. - One feature at a time. ICE for a single feature shows that an interaction exists but does not name the partner. You still need step 2 and 3 above.
Summary of when to use ICE
Use ICE when a partial dependence curve is flat or weakly sloped yet the feature ranks high in permutation importance. That combination is a strong hint of cancelling effects or interactions. Use it also before you report any partial dependence curve as "the effect of feature X". ICE tells you whether a single effect exists to report.
Exercise
A random forest's partial dependence curve for feature age is nearly flat, but permutation importance on the test set ranks age second. You draw 200 centered ICE curves and see about half of them rising steadily and the other half falling by a similar amount. What explains the flat average, and what is your next step?
Show answer
The rising and falling curves cancel when averaged, so the partial dependence curve is flat even though age strongly affects individual predictions. That is why permutation importance, which shuffles the feature and hurts every row's prediction, still ranks it high. Next, find what separates the two groups of rows. Compute each row's change across the grid, check it against the other features (a correlation table or a shallow tree on that change), and confirm the candidate partner with a two-way partial dependence plot.
Exercise
You build ICE curves with ice_1d and compute curves.mean(axis=0). A colleague asks how this relates to the partial dependence curve from PartialDependenceDisplay with kind="average" on the same model. What do you tell them, and what could make the two differ slightly?
Show answer
They are the same quantity. The partial dependence curve is the pointwise mean of the ICE curves over the same grid. They can differ if the ICE version used only a subsample of rows while the plot used all rows, or if the two used different grids (for example, different percentile bounds).