svgpdp-ice
Partial dependence with ICE
How does the prediction change as one feature changes, on average and for individual rows?
How to read it
- Read the bold line as the average prediction at each feature value.
- Read the thin lines as individual rows.
- If thin lines cross or fan out, the effect differs across rows: look for an interaction.
- Callout 1: The bold line: the average effect.
- Callout 2: Thin lines: one row each.
- Callout 3: A jump in the average: a threshold in the model.
Watch out
- With correlated features, PDP asks about impossible rows. Use ALE instead.
Defaults
- Centre each line at its first value (c-ICE)
- Off
- Start every line at zero so differences in shape stand out from differences in level.
Pinned in the code
- Draws the run's numbers as given (computed by the host's cs-ml evaluation or the Python/R engine); the chart computes nothing statistical.
- The grid is the engine's (training quantiles of the feature); the PDP is the mean of the ICE curves over the explained rows.
- Beyond 200 ICE lines the chart draws every k-th line (deterministic) and says so in the legend.
- PDPs extrapolate into impossible combinations when features are correlated — prefer ALE then.
# Partial dependence with ICE — Codesplash Chart Lab (recipe "pdp-ice")
# controls: centered=false
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else plt.rcParams["axes.prop_cycle"].by_key()["color"]
df = pd.read_csv("pdp-ice-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["kind"] = pd.Categorical(df["kind"].astype("string"), categories=["pdp", "ice"])
_tokens = cs.palette(dark=False) if cs else {}
SEQ = _tokens.get("sequential", ["#eff6fd", "#1a469d"]) # sequential ramp (low → high)
DIV = _tokens.get("diverging", ["#c13e2e", "#f3f5f8", "#0859ac"]) # negative, midpoint, positive
REF = _tokens.get("reference", "#4e5661")
GREY = _tokens.get("dim", "#ced1d6")
X = "BMI"
YH = "predicted probability"
LINE = "line"
KIND = "kind"
CENTERED = False # c-ICE: each curve minus its value at the smallest x
d = df.dropna(subset=[X, YH, LINE]).sort_values(X)
kind = d[KIND].astype(str).str.lower() if KIND else pd.Series("ice", index=d.index)
ice, pdp = d[kind == "ice"], d[kind == "pdp"]
if pdp.empty: # no PDP rows: the PDP is the mean of the ICE curves
pdp = ice.groupby(X, as_index=False)[YH].mean().assign(**{LINE: "PDP"})
def centre(frame):
return frame.assign(_y=frame[YH] - frame.groupby(LINE, observed=True)[YH].transform("first")) if CENTERED else frame.assign(_y=frame[YH])
ice, pdp = centre(ice), centre(pdp)
fig, ax = plt.subplots(figsize=(8, 4.5))
for _, s in ice.groupby(LINE, observed=True):
ax.plot(s[X], s["_y"], color=GREY, linewidth=0.6, alpha=0.7)
ax.plot(pdp[X], pdp["_y"], color=PALETTE[0], linewidth=2.8, label="partial dependence")
ax.set_xlabel(X)
ax.set_ylabel(("centred " if CENTERED else "") + YH)
ax.legend(fontsize=8)
plt.show()Needs pandas, numpy, matplotlib · reads pdp-ice-demo.csv · app theme from the optional codesplash helper
# Partial dependence with ICE — Codesplash Chart Lab (recipe "pdp-ice")
# controls: centered=false
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("pdp-ice-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["kind"] = pd.Categorical(df["kind"].astype("string"), categories=["pdp", "ice"])
_tokens = cs.palette(dark=False) if cs else {}
SEQ = _tokens.get("sequential", ["#eff6fd", "#1a469d"]) # sequential ramp (low → high)
DIV = _tokens.get("diverging", ["#c13e2e", "#f3f5f8", "#0859ac"]) # negative, midpoint, positive
REF = _tokens.get("reference", "#4e5661")
GREY = _tokens.get("dim", "#ced1d6")
X = "BMI"
YH = "predicted probability"
LINE = "line"
KIND = "kind"
CENTERED = False
d = df.dropna(subset=[X, YH, LINE]).sort_values(X)
kind = d[KIND].astype(str).str.lower() if KIND else pd.Series("ice", index=d.index)
ice, pdp = d[kind == "ice"], d[kind == "pdp"]
if pdp.empty:
pdp = ice.groupby(X, as_index=False)[YH].mean().assign(**{LINE: "PDP"})
def centre(frame):
return frame.assign(_y=frame[YH] - frame.groupby(LINE, observed=True)[YH].transform("first")) if CENTERED else frame.assign(_y=frame[YH])
ice, pdp = centre(ice), centre(pdp)
fig = go.Figure()
for _, s in ice.groupby(LINE, observed=True):
fig.add_scatter(x=s[X], y=s["_y"], mode="lines", line=dict(color=GREY, width=0.7), opacity=0.7, showlegend=False, hoverinfo="skip")
fig.add_scatter(x=pdp[X], y=pdp["_y"], mode="lines", line=dict(color=PALETTE[0], width=3), name="partial dependence")
fig.update_layout(xaxis_title=X, yaxis_title=("centred " if CENTERED else "") + YH)
fig.show()Needs pandas, numpy, plotly · reads pdp-ice-demo.csv · app theme from the optional codesplash helper
# Partial dependence with ICE — Codesplash Chart Lab (recipe "pdp-ice")
# controls: centered=false
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("pdp-ice-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["line"]] <- factor(df[["line"]])
df[["kind"]] <- factor(df[["kind"]], levels = c("pdp", "ice"))
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
x_col <- "BMI"
y_col <- "predicted probability"
line_col <- "line"
kind_col <- "kind"
centered <- FALSE # c-ICE: each curve minus its value at the smallest x
d <- df[!is.na(df[[x_col]]) & !is.na(df[[y_col]]) & !is.na(df[[line_col]]), ]
d <- data.frame(x = d[[x_col]], y = d[[y_col]], line = as.character(d[[line_col]]), kind = if (is.null(kind_col)) "ice" else tolower(as.character(d[[kind_col]])))
d <- d[order(d$line, d$x), ]
ice <- d[d$kind == "ice", ]; pdp <- d[d$kind == "pdp", ]
if (!nrow(pdp)) { pdp <- aggregate(y ~ x, data = ice, FUN = mean); pdp$line <- "PDP" } # the PDP is the mean ICE curve
centre <- function(f) { if (centered) f$y <- f$y - stats::ave(f$y, f$line, FUN = function(v) v[1]); f }
ice <- centre(ice); pdp <- centre(pdp[order(pdp$x), ])
p <- ggplot(ice, aes(x, y, group = line)) + geom_line(colour = grey_col, linewidth = 0.3, alpha = 0.7) +
geom_line(data = pdp, colour = cs_cat[1], linewidth = 1.3) +
labs(x = x_col, y = paste0(if (centered) "centred " else "", y_col)) + theme_cs
print(p)Needs ggplot2 · reads pdp-ice-demo.csv · app theme from the optional codesplashr helper