Skip to content

DRegression models · explain.shap

SHAP values for a saved model

How much does each feature push a saved model's predictions up or down, row by row and overall?

Explains a registered model version on the rows of this dataset with Shapley additive explanations: each feature's share of the gap between a row's prediction and the average prediction, so the shares add up to the prediction. Tree boosters get exact TreeSHAP (log-odds scale), linear models exact linear SHAP; every other learner, or the KernelSHAP choice, gets the model-agnostic estimate from predictions on feature subsets with absent features taken from background rows (the model's training sample by default). It runs the model's own code in the engine that trained it, so Python and R agree whenever their models do.

Experimental Python and R agree to 6 decimals Seeded Also called SHAP, Shapley values, Shapley additive explanations…

A real result

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

SHAP values for a saved model — learn.tree/binary_pimaRecorded · Python and R agreeRecorded 2026-11-25 · 18 values compared
R

Across 12 rows, glu moves the model's P(true) the most (mean |SHAP| 0.198).

Mean |SHAP|, glu
0.1976
Average P(true)
0.4104

Plots

Mean |SHAP| (KernelSHAP, probability scale)Which features does the model rely on most?
View data
FeatureMean |SHAP|
glu0.1976
age0.1304
ped0.0752
bp0.0498
bmi0.0475
skin0.0081
npreg0.0037
SHAP values per row (KernelSHAP)How does each feature push individual predictions up or down, and for which values?
View data
FeatureSHAP (probability)Feature value (scaled)
glu−0.16250.1429
glu0.29280.8762
glu−0.18740.2952
glu−0.30380
glu−0.22610.2095
glu−0.18210.3143
glu0.33511
glu−0.21600.1429
glu0.17210.5619
glu0.05620.4286
glu0.07810.5429
glu−0.15840.2095
age−0.10000
age0.02721
age−0.17230
age−0.11180
age0.17040.6486
age−0.11670.0811
age−0.04540.5405
age−0.15370
age−0.13390.0541
age−0.20170.1081
age−0.18080.0270
age−0.15030.0270
ped0.06260.5256
ped0.09880.4300
ped−0.03370.3777
ped−0.03491
ped−0.22990.1013
ped−0.05230
ped0.05370.3936
ped0.00050.3675
ped0.28050.9135
ped0.01420.5711
ped−0.00470.3914
ped−0.03610.3834
bp0.07830.1481
bp−0.00580.7407
bp−0.03890.2593
bp0.10100
bp−0.02480.4074
bp−0.01290.5556
bp−0.02451
bp−0.06610.4074
bp−0.03270.6667
bp−0.12420.4444
bp−0.07430.6296
bp0.01360.1111
bmi−0.07470
bmi0.03560.4192
bmi0.02220.2727
bmi−0.04750.2525
bmi0.04670.5657
bmi0.01361
bmi0.01950.4495
bmi0.02210.6667
bmi0.09290.2374
bmi0.10080.3939
bmi0.02610.3535
bmi−0.06800.1818

First 60 of 84 rows.

SHAP dependence — gluHow does one feature's value change its contribution, and does another feature modify it?
View data
SHAP (probability)glu
−0.162599
0.2928176
−0.1874115
−0.303884
−0.2261106
−0.1821117
0.3351189
−0.216099
0.1721143
0.0562129
0.0781141
−0.1584106
Why row 27 got its score (KernelSHAP, probability scale)Which features pushed this one prediction up, and which pulled it down?
View data
SHAP (probability)FeatureValue
−0.1625glu99
−0.1000age21
0.0626ped0.551
0.0783bp58
−0.0747bmi25.4
−0.0115skin10
0.0115npreg1

Assumptions

  • Enough rows — 12 explained rows, 426 background rows.
  • Features vary independently — skin and bmi: |ρ| = 0.69.
  • Rows resemble the training data — 0.0% of the explained rows fall outside the background's range.
  • KernelSHAP on the probability or prediction scale: 12 rows, 16 background rows, 64 sampled feature subsets. Absent features take background values, so correlated features can borrow credit from each other.
Python

Across 12 rows, glu moves the model's P(true) the most (mean |SHAP| 0.198).

Mean |SHAP|, glu
0.1976
Average P(true)
0.4104

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

Assumptions

  • Enough rows — 12 explained rows, 426 background rows.
  • Features vary independently — skin and bmi: |ρ| = 0.69.
  • Rows resemble the training data — 0.0% of the explained rows fall outside the background's range.
  • KernelSHAP on the probability or prediction scale: 12 rows, 16 background rows, 64 sampled feature subsets. Absent features take background values, so correlated features can borrow credit from each other.

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 kernel pimaml_pima ·
  • Xgboost tree penguinsml_penguins ·
  • Linear airqualityml_airquality ·
  • Coxnet kernel veteranveteran ·
  • Rsf kernel lunglung ·
  • Xgboost aft lunglung ·
  • Regress aft treeshap risk signlung ·

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?

Choices you make

statistics

Modeldefault —

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

Algorithmdefault auto

Exact SHAP where the model has it (trees, linear models); KernelSHAP otherwise or when chosen.

  • Exact where available(default) — TreeSHAP for XGBoost and LightGBM, linear SHAP for linear models, KernelSHAP for the rest.
  • KernelSHAP (any model) — Estimates Shapley values from predictions on feature subsets, on the probability scale; slower.
Rows to explaindefault 50

Rows sampled from the dataset (shared random stream). KernelSHAP time grows in proportion.

options

Background rowsdefault 30

KernelSHAP: training rows that stand in for absent features. More rows give steadier values.

Background datadefault model

Where absent features take their values from.

  • The model's training sample(default) — Rows saved with the model version; the usual choice, because SHAP compares against the training data.
  • These rows — This dataset's rows; pick it to explain relative to a new population.

Advanced

Feature subsetsdefault 256

KernelSHAP: sampled feature subsets per row; with few features every subset is used and the values are exact.

Class to explaindefault —

Multiclass models: the class whose probability is explained, empty for the first class (binary models explain 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

    Absent features take background values, so strongly correlated features can share or borrow credit.

    • 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

    Explanations of rows outside the training range describe extrapolation, not learned patterns.

  • Enough rows

    Few explained or background rows make the averages and the KernelSHAP estimate noisy.

    • If violated → More rows — More explained and background rows steady the averages and the KernelSHAP estimate.

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.
base_value
The model's average output over the background rows: where every SHAP explanation starts, so base value + SHAP values = the prediction.
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.
shap_kernel
Whether the SHAP values are exact (TreeSHAP, linear SHAP) or estimated from predictions on feature subsets (KernelSHAP = 1).
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: shap_mean_abs[<feature>], kshap_mean_abs[<feature>], shap_base, kshap_base

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

  • The explanation runs the saved model's own learner code in each engine (the engine that trained it), so the two engines agree as closely as their models do: exactly for the CART, XGBoost and k-NN twins, to the learner's tolerance otherwise. Rows, background rows and feature subsets come from the shared random stream.
  • shap's KernelExplainer samples subsets with numpy's generator and adds an L1 step, so its estimates differ draw to draw; with every subset enumerated both give the exact Shapley values (checked in tests/crosscheck/w3ds2c_explain.py).
Python

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

# SHAP values for a saved model
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method explain.shap 1.1.0 · spec 00e71ca57842110f
# Explains the saved model learn.tree/binary_pima 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 2c9409d7e5211ff1
# Dataset: ml_pima (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 = "diabetic"
FEATURES = ["npreg", "glu", "bp", "skin", "bmi", "ped", "age"]
TASK = "binary"
CLASSES = ["false", "true"]
POSITIVE = "true"
METRIC = "roc_auc"
SEED = 42
PARAMS = {
    "max_depth": 6,
    "min_samples_split": 10,
    "min_samples_leaf": 5,
    "criterion": "gini",
    "min_impurity_decrease": 0,
    "ccp_alpha": 0,
}

df = pd.read_parquet("tests/parity/fixtures/ml_pima.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={
        "npreg": "numeric",
        "glu": "numeric",
        "bp": "numeric",
        "skin": "numeric",
        "bmi": "numeric",
        "ped": "numeric",
        "age": "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("{\"analyze\":{\"kind\":\"shap\",\"method\":\"explain.shap\",\"model\":\"learn.tree/binary_pima\",\"title\":\"SHAP values for a saved model\",\"version\":\"1.1.0\"},\"coalitions\":64,\"kernelBackground\":16,\"kernelRows\":12,\"maxRows\":12,\"methods\":[\"kernel_shap\"],\"modelDir\":\"model-python/out\",\"rows\":\"auto\",\"shapRows\":12}") 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 kernel pima” · R version 4.5.1 (2025-06-13)

# SHAP values for a saved model
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method explain.shap 1.1.0 · spec 00e71ca57842110f
# Explains the saved model learn.tree/binary_pima 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 2c9409d7e5211ff1
# Dataset: ml_pima (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 <- "diabetic"
FEATURES <- c("npreg", "glu", "bp", "skin", "bmi", "ped", "age")
TASK <- "binary"
CLASSES <- c("false", "true")
POSITIVE <- "true"
METRIC <- "roc_auc"
SEED <- 42
PARAMS <- list(
  max_depth = 6,
  min_samples_split = 10,
  min_samples_leaf = 5,
  criterion = "gini",
  min_impurity_decrease = 0,
  ccp_alpha = 0
)

df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_pima.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(
    npreg = "numeric",
    glu = "numeric",
    bp = "numeric",
    skin = "numeric",
    bmi = "numeric",
    ped = "numeric",
    age = "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("{\"analyze\":{\"kind\":\"shap\",\"method\":\"explain.shap\",\"model\":\"learn.tree/binary_pima\",\"title\":\"SHAP values for a saved model\",\"version\":\"1.1.0\"},\"coalitions\":64,\"kernelBackground\":16,\"kernelRows\":12,\"maxRows\":12,\"methods\":[\"kernel_shap\"],\"modelDir\":\"model-r/out\",\"rows\":\"auto\",\"shapRows\":12}", 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

  • Lundberg, S. M., & Lee, S.-I. (2017). A unified approach to interpreting model predictions. NeurIPS 30, 4765–4774.
  • Lundberg, S. M., Erion, G., Chen, H., et al. (2020). From local explanations to global understanding with explainable AI for trees. Nature Machine Intelligence, 2, 56–67.
  • Shapley, L. S. (1953). A value for n-person games. In Contributions to the Theory of Games II, 307–317.
  • Aas, K., Jullum, M., & Løland, A. (2021). Explaining individual predictions when features are dependent. Artificial Intelligence, 298, 103502.
  • Molnar, C. (2022). Interpretable Machine Learning (2nd ed.), ch. 9.5–9.6.

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