Skip to content

DRegression models · explain.pdp

Partial dependence and accumulated local effects for a saved model

How does a saved model's prediction change as one feature changes, on average and row by row?

Shows how a registered model version responds to each feature on the rows of this dataset. Partial dependence sets a feature to each grid value for every row and averages the predictions (ICE lines show single rows, so diverging lines reveal interactions); accumulated local effects instead average prediction changes within narrow bins of the data, which stays valid when features are correlated. Without features to plot, they are ranked by how far their partial dependence moves the prediction. It runs the model's own code in the engine that trained it.

Experimental Python and R agree to 6 decimals Seeded Also called partial dependence plot, PDP, ICE…

A real result

Example “Tree airquality both”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

Partial dependence and accumulated local effects for a saved model — learn.tree/regression_prunedRecorded · Python and R agreeRecorded 2026-11-25 · 74 values compared
R

Across 23 rows, Wind moves the model's average prediction the most (range 62.7).

Range of the average prediction, Wind
62.668

Plots

Partial dependence — WindHow does the prediction change as one feature changes, on average and for individual rows?
View data
KindLineWindprediction
pdpaverage4.40096.227
pdpaverage6.90034.929
pdpaverage834.929
pdpaverage9.70034.929
pdpaverage10.30034.929
pdpaverage11.50033.559
pdpaverage13.80033.559
pdpaverage15.94033.559
icerow 74.400112.56
icerow 76.90020.750
icerow 7820.750
icerow 79.70020.750
icerow 710.30020.750
icerow 711.50020.750
icerow 713.80020.750
icerow 715.94020.750
icerow 114.40075
icerow 116.90016.667
icerow 11816.667
icerow 119.70016.667
icerow 1110.30016.667
icerow 1111.50016.667
icerow 1113.80016.667
icerow 1115.94016.667
icerow 134.400112.56
icerow 136.90031.714
icerow 13831.714
icerow 139.70031.714
icerow 1310.30031.714
icerow 1311.50031.714
icerow 1313.80031.714
icerow 1315.94031.714
icerow 144.400112.56
icerow 146.90031.714
icerow 14831.714
icerow 149.70031.714
icerow 1410.30031.714
icerow 1411.50031.714
icerow 1413.80031.714
icerow 1415.94031.714
icerow 284.40075
icerow 286.90011.385
icerow 28811.385
icerow 289.70011.385
icerow 2810.30011.385
icerow 2811.50011.385
icerow 2813.80011.385
icerow 2815.94011.385
Partial dependence — TempHow does the prediction change as one feature changes, on average and for individual rows?
View data
KindLineTempprediction
pdpaverage6130.376
pdpaverage6834.190
pdpaverage7329.159
pdpaverage7848.016
pdpaverage8148.016
pdpaverage82.74337.483
pdpaverage8765.507
pdpaverage92.40089.693
icerow 76120.750
icerow 76831.714
icerow 77316.667
icerow 77847.250
icerow 78147.250
icerow 782.74329
icerow 78759.556
icerow 792.40088.833
icerow 116120.750
icerow 116831.714
icerow 117316.667
icerow 117847.250
icerow 118147.250
icerow 1182.74329
icerow 118759.556
icerow 1192.40088.833
icerow 136120.750
icerow 136831.714
icerow 137316.667
icerow 137847.250
icerow 138147.250
icerow 1382.74329
icerow 138759.556
icerow 1392.40088.833
icerow 146120.750
icerow 146831.714
icerow 147316.667
icerow 147836.750
icerow 148136.750
icerow 1482.74329
icerow 148759.556
icerow 1492.40088.833
icerow 286111.385
icerow 286811.385
icerow 287311.385
icerow 287813
icerow 288113
icerow 2882.74313
icerow 288759.556
icerow 2892.40088.833
Accumulated local effect — WindWhat is a feature's effect on predictions when features are correlated?
View data
Effect on predictionWind
48.9244.600
−3.6596.700
−3.6597.400
−3.6599.200
−3.65910.300
−8.90910.900
−8.90915.500
Accumulated local effect — TempWhat is a feature's effect on predictions when features are correlated?
View data
Effect on predictionTemp
−12.03265
−6.55067.667
−13.74074.667
−13.74077
−1.40782.333
26.23786
35.99797

Assumptions

  • One average describes the rows — Single-row curves for Wind differ from the average by 0.16 of its range.
  • Features vary independently — Wind and Temp: |ρ| = 0.57.
  • Rows resemble the training data — 4.3% of the explained rows fall outside the background's range.
  • Features were ranked by the range of their partial dependence (Greenwell, Boehmke & McCarthy 2018).
Python

Across 23 rows, Wind moves the model's average prediction the most (range 62.7).

Range of the average prediction, Wind
62.668

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • One average describes the rows — Single-row curves for Wind differ from the average by 0.16 of its range.
  • Features vary independently — Wind and Temp: |ρ| = 0.57.
  • Rows resemble the training data — 4.3% of the explained rows fall outside the background's range.
  • Features were ranked by the range of their partial dependence (Greenwell, Boehmke & McCarthy 2018).

Do it in CodeSplash Run it on your own data. It's in the Experimental lane in the app.

Worked examples in the app

  • Tree airquality bothml_airquality ·
  • Xgboost penguins showml_penguins · show: bill_len, island
  • Coxnet lung bothlung ·
  • Rsf veteran showveteran · show: karno, celltype

In the guides

Where it sits in the decision guides

  • Interpretable ML (trees, GAMs, SHAP, LIME) · DS & ML Decision Guide · Explain — why is it happening?

What you need

Features to plot (optional)numeric / categorical / boolean · 0–6 columns
Features of the model to draw. Leave empty to plot the features with the largest effects.

Choices you make

statistics

Modeldefault —

The registered model version to explain. It runs in the engine that trained it, on this dataset's rows.

Effectdefault pdp

Partial dependence with ICE lines, accumulated local effects, or both.

  • Partial dependence + ICE(default) — Averages predictions with the feature set to each grid value; ICE lines show single rows.
  • Accumulated local effects — Averages changes within bins of the data; valid when features are correlated (numbers only).
  • Both — Draws both; where they disagree, correlation or interactions are at work.
Features to rank and plotdefault 4

Without chosen features, this many with the widest partial dependence are plotted.

options

Grid pointsdefault 20

Grid values per number (training quantiles 5–95%); categories use their levels.

ICE linesdefault 30

Rows drawn as single lines under the average.

ALE binsdefault 10

Quantile bins for accumulated local effects. More bins show detail but get noisier.

Rows to average overdefault 500

Rows sampled from the dataset (shared random stream).

Grid datadefault model

Where grid values come from.

  • The model's training sample(default) — Grid quantiles from the rows saved with the model version; the usual choice.
  • These rows — Grid quantiles from this dataset; pick it to focus on the new data's range.

Advanced

Class to explaindefault —

Multiclass models: the class whose probability is plotted, empty for the first class (binary models plot the positive class).

Checks and remedies

CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.

  • Features vary independently

    Partial dependence sets one feature on every row, so with correlated features it averages over unlikely rows.

    • If violated → Accumulated local effects — ALE compares predictions within narrow bins of the data, so correlated features never create unlikely rows.
  • Rows resemble the training data

    Effects outside the training range describe extrapolation, not learned patterns.

  • One average describes the rows

    Crossing or diverging ICE lines mean the effect depends on other features; the average hides that.

    • If violated → More ICE lines — More single-row lines show how the effect varies across rows.

What it reports

n_explained
How many independent units the analysis used; it sets precision and power.
n_background
How many independent units the analysis used; it sets precision and power.
n_features
How many independent units the analysis used; it sets precision and power.
n_plotted
How many independent units the analysis used; it sets precision and power.
top_feature
The feature with the largest summary in this explanation: mean |SHAP|, average local effect, score drop or range of the average curve.
top_value
The feature with the largest summary in this explanation: mean |SHAP|, average local effect, score drop or range of the average curve.
max_abs_corr
The largest |Spearman ρ| between two numeric features in the background rows; above 0.7 the card warns that features move together.
outside_share
Asking a model about feature combinations it never saw, as shuffling or fixing a correlated feature does; answers are guesses, not patterns.
score_label
What the explanation is in units of: the prediction for regression, or one class's probability.

Per group, level or term: pdp[<feature>|<i>], pdpx[<feature>|<i>], ale[<feature>|<i>], alex[<feature>|<i>], pdp_range[<feature>]

Python and R

Python and R agree to 6 decimals (relative tolerance 1e-6). Python uses codesplash, numpy, pandas; R uses codesplashr, nanoparquet.

Default traps between the two languages

  • Grids are type-7 quantiles with pinned arithmetic and ALE bins follow Apley and Zhu, so the engines agree as closely as their models do. scikit-learn's partial_dependence uses a percentile grid; on the same grid its average equals ours (checked in tests/crosscheck/w3ds2c_explain.py).
Python

The exact script CodeSplash ran for example “Tree airquality both” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0

# Partial dependence and accumulated local effects for a saved model
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method explain.pdp 1.1.0 · spec 04273997ed25dac9
# Explains the saved model learn.tree/regression_pruned with its own learner code (learn.tree 1.0.0, driver mode "explain").
# Decision tree (CART)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method learn.tree 1.0.0 · spec eb6363d43453be00
# Dataset: ml_airquality (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os

import numpy as np
import pandas as pd

import codesplash as cs
from codesplash import ml as csml
from codesplash.ml.tree import CART, tree_json

# %% Data and split plan
TARGET = "Ozone"
FEATURES = ["solar radiation", "Wind", "Temp", "Month"]
TASK = "regression"
CLASSES = []
POSITIVE = None
METRIC = "rmse"
SEED = 42
PARAMS = {
    "max_depth": None,
    "min_samples_split": 10,
    "min_samples_leaf": 3,
    "criterion": "gini",
    "min_impurity_decrease": 0,
    "ccp_alpha": 2,
}

df = pd.read_parquet("tests/parity/fixtures/ml_airquality.parquet", columns=list(dict.fromkeys([TARGET] + FEATURES)))
plan = csml.read_plan("model-python/folds.parquet")  # host-written folds: identical in Python and R
design = csml.Design.for_frame(
    df,
    FEATURES,
    kinds={
        "solar radiation": "numeric",
        "Wind": "numeric",
        "Temp": "numeric",
        "Month": "numeric",
    },
    levels={
    },
    impute="median",
    scale="none",
    indicators=False,
)
y, y_index = csml.encode_target(df[TARGET], TASK, CLASSES, POSITIVE)
weights = csml.class_weights(y_index, TASK, "none", plan.train)
run = csml.LearnerRun(TASK, CLASSES, POSITIVE, METRIC)
out = csml.out_dir("explain-out-python")
warnings = []


def sample_weights(rows):
    return None if weights is None else weights[rows]


# %% Model
# CART with scikit-learn's DecisionTree rules and a deterministic split search (features in design
# order) — the codesplash twin, identical in Python and R.


def fit_model(X, y, w):
    k = 0 if TASK == "regression" else (2 if TASK == "binary" else len(CLASSES))
    model = CART(
        TASK,
        k,
        criterion=PARAMS["criterion"],
        max_depth=PARAMS["max_depth"],
        min_samples_split=int(PARAMS["min_samples_split"]),
        min_samples_leaf=int(PARAMS["min_samples_leaf"]),
        min_impurity_decrease=PARAMS["min_impurity_decrease"],
        ccp_alpha=PARAMS["ccp_alpha"],
    )
    return model.fit(X, y, w)


def predict_model(model, X):
    p = model.predict(X)
    return p[:, 1] if TASK == "binary" else p


def feature_importance(model, names):
    return model.importances(names)


def save_model(model, directory):
    import joblib

    path = os.path.join(directory, "model.joblib")
    joblib.dump(model, path)
    if TASK == "binary":
        classes = [[c for c in CLASSES if c != POSITIVE][0], POSITIVE]  # probabilities: [other, positive]
    else:
        classes = CLASSES or None
    return [{"key": "model", "path": path, "format": "joblib"}, tree_json(directory, model, names, classes)]


def load_model(directory):
    import joblib

    return joblib.load(os.path.join(directory, "model.joblib"))


# %% Explain the model
import json

from codesplash.ml import explain as csx

REQUEST = json.loads("{\"aleBins\":6,\"analyze\":{\"kind\":\"pdp\",\"method\":\"explain.pdp\",\"model\":\"learn.tree/regression_pruned\",\"title\":\"Partial dependence and accumulated local effects for a saved model\",\"version\":\"1.1.0\"},\"grid\":8,\"iceRows\":5,\"maxRows\":500,\"methods\":[\"pdp\",\"ale\"],\"modelDir\":\"model-python/out\",\"rows\":\"auto\",\"topFeatures\":2}") or {}
model_dir = REQUEST.get("modelDir") or out
with open(os.path.join(model_dir, "design.json"), encoding="utf-8") as fh:
    prep = csml.FittedDesign.from_json(fh.read())
model = load_model(model_dir)
explainer = csx.Explainer(predict_model, model, prep, TASK, CLASSES, POSITIVE, METRIC, cls=REQUEST.get("class"))
rows = csx.explain_rows(plan, REQUEST.get("rows") or "auto", int(REQUEST.get("maxRows") or 1000), SEED)
cs.publish(
    csx.explain(
        explainer,
        df,
        rows,
        plan.train,
        y,
        y_index,
        REQUEST,
        SEED,
        model_dir,
        out,
        warnings=warnings,
        title="Decision tree (CART)",
        engine=cs.engine_info("numpy", "numpy", "pandas"),
    )
)
R

The exact script CodeSplash ran for example “Tree airquality both” · R version 4.5.1 (2025-06-13)

# Partial dependence and accumulated local effects for a saved model
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method explain.pdp 1.1.0 · spec 04273997ed25dac9
# Explains the saved model learn.tree/regression_pruned with its own learner code (learn.tree 1.0.0, driver mode "explain").
# Decision tree (CART)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method learn.tree 1.0.0 · spec eb6363d43453be00
# Dataset: ml_airquality (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

# %% Data and split plan
TARGET <- "Ozone"
FEATURES <- c("solar radiation", "Wind", "Temp", "Month")
TASK <- "regression"
CLASSES <- c()
POSITIVE <- NULL
METRIC <- "rmse"
SEED <- 42
PARAMS <- list(
  max_depth = NULL,
  min_samples_split = 10,
  min_samples_leaf = 3,
  criterion = "gini",
  min_impurity_decrease = 0,
  ccp_alpha = 2
)

df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_airquality.parquet", col_select = unique(c(TARGET, FEATURES))))
plan <- cs_ml_read_plan("model-r/folds.parquet")  # host-written folds: identical in Python and R
design <- cs_ml_design(
  df, FEATURES,
  kinds = list(
    `solar radiation` = "numeric",
    Wind = "numeric",
    Temp = "numeric",
    Month = "numeric"
  ),
  levels = list(
  ),
  impute = "median",
  scale = "none",
  indicators = FALSE
)
target <- cs_ml_encode_target(df[[TARGET]], TASK, CLASSES, POSITIVE)
y <- target$fit
y_index <- target$index
weights <- cs_ml_class_weights(y_index, TASK, "none", plan$train)
run <- cs_ml_run(TASK, CLASSES, POSITIVE, METRIC)
out <- cs_ml_out_dir("explain-out-r")
warnings <- list()
sample_weights <- function(rows) if (is.null(weights)) NULL else weights[rows + 1L]
rows_of <- function(rows) df[rows + 1L, , drop = FALSE]

# %% Model
# CART with scikit-learn's DecisionTree rules and a deterministic split search (features in design
# order) — the codesplash twin, identical in R and Python (rpart differs: surrogates, cp scaling,
# internal cross-validation).
fit_model <- function(X, y, w) {
  k <- if (TASK == "regression") 0L else if (TASK == "binary") 2L else length(CLASSES)
  cs_ml_cart_fit(X, y, TASK, k, criterion = PARAMS$criterion, max_depth = PARAMS$max_depth,
                 min_samples_split = as.integer(PARAMS$min_samples_split),
                 min_samples_leaf = as.integer(PARAMS$min_samples_leaf),
                 min_impurity_decrease = PARAMS$min_impurity_decrease, ccp_alpha = PARAMS$ccp_alpha, w = w)
}

predict_model <- function(model, X) {
  p <- cs_ml_cart_predict(model, X)
  if (TASK == "binary") p[, 2] else p
}

feature_importance <- function(model, names) cs_ml_cart_importances(model, names)

save_model <- function(model, directory) {
  path <- file.path(directory, "model.rds")
  saveRDS(model, path)
  classes <- if (TASK == "binary") c(setdiff(CLASSES, POSITIVE)[1], POSITIVE) else if (length(CLASSES)) CLASSES else NULL
  list(list(key = "model", path = path, format = "rds"), cs_ml_tree_json(directory, model, names_, classes))
}

load_model <- function(directory) readRDS(file.path(directory, "model.rds"))

# %% Explain the model
REQUEST <- jsonlite::fromJSON("{\"aleBins\":6,\"analyze\":{\"kind\":\"pdp\",\"method\":\"explain.pdp\",\"model\":\"learn.tree/regression_pruned\",\"title\":\"Partial dependence and accumulated local effects for a saved model\",\"version\":\"1.1.0\"},\"grid\":8,\"iceRows\":5,\"maxRows\":500,\"methods\":[\"pdp\",\"ale\"],\"modelDir\":\"model-r/out\",\"rows\":\"auto\",\"topFeatures\":2}", simplifyVector = FALSE)
if (is.null(REQUEST)) REQUEST <- list()
model_dir <- if (is.null(REQUEST$modelDir)) out else REQUEST$modelDir
prep <- cs_ml_design_from_json(paste(readLines(file.path(model_dir, "design.json"), warn = FALSE), collapse = "\n"))
# S3 predict methods (ranger, e1071, …) need their package's namespace loaded.
for (pkg in c("stats")) {
  suppressWarnings(suppressPackageStartupMessages(requireNamespace(pkg, quietly = TRUE)))
}
model <- load_model(model_dir)
explainer <- cs_ml_explainer(predict_model, model, prep, TASK, CLASSES, POSITIVE, METRIC, cls = REQUEST$class)
rows <- cs_ml_explain_rows(plan, if (is.null(REQUEST$rows)) "auto" else REQUEST$rows,
                           as.integer(if (is.null(REQUEST$maxRows)) 1000 else REQUEST$maxRows), SEED)
cs_publish(cs_ml_explain(
  explainer, df, rows, plan$train, y, y_index, REQUEST, SEED, model_dir, out,
  warnings = warnings,
  title = "Decision tree (CART)",
  engine = cs_engine_info("stats", "nanoparquet")
))

Sources

  • Friedman, J. H. (2001). Greedy function approximation: A gradient boosting machine. Annals of Statistics, 29, 1189–1232.
  • Goldstein, A., Kapelner, A., Bleich, J., & Pitkin, E. (2015). Peeking inside the black box: Visualizing statistical learning with plots of individual conditional expectation. JCGS, 24, 44–65.
  • Apley, D. W., & Zhu, J. (2020). Visualizing the effects of predictor variables in black box supervised learning models. JRSS B, 82, 1059–1086.
  • Greenwell, B. M., Boehmke, B. C., & McCarthy, A. J. (2018). A simple and effective model-based variable importance measure. arXiv:1805.04755.

From the CodeSplash method registry · explain.pdp v1.1.0.