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.
A real result
Example “Tree kernel pima”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
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
View data
| Feature | Mean |SHAP| |
|---|---|
| glu | 0.1976 |
| age | 0.1304 |
| ped | 0.0752 |
| bp | 0.0498 |
| bmi | 0.0475 |
| skin | 0.0081 |
| npreg | 0.0037 |
View data
| Feature | SHAP (probability) | Feature value (scaled) |
|---|---|---|
| glu | −0.1625 | 0.1429 |
| glu | 0.2928 | 0.8762 |
| glu | −0.1874 | 0.2952 |
| glu | −0.3038 | 0 |
| glu | −0.2261 | 0.2095 |
| glu | −0.1821 | 0.3143 |
| glu | 0.3351 | 1 |
| glu | −0.2160 | 0.1429 |
| glu | 0.1721 | 0.5619 |
| glu | 0.0562 | 0.4286 |
| glu | 0.0781 | 0.5429 |
| glu | −0.1584 | 0.2095 |
| age | −0.1000 | 0 |
| age | 0.0272 | 1 |
| age | −0.1723 | 0 |
| age | −0.1118 | 0 |
| age | 0.1704 | 0.6486 |
| age | −0.1167 | 0.0811 |
| age | −0.0454 | 0.5405 |
| age | −0.1537 | 0 |
| age | −0.1339 | 0.0541 |
| age | −0.2017 | 0.1081 |
| age | −0.1808 | 0.0270 |
| age | −0.1503 | 0.0270 |
| ped | 0.0626 | 0.5256 |
| ped | 0.0988 | 0.4300 |
| ped | −0.0337 | 0.3777 |
| ped | −0.0349 | 1 |
| ped | −0.2299 | 0.1013 |
| ped | −0.0523 | 0 |
| ped | 0.0537 | 0.3936 |
| ped | 0.0005 | 0.3675 |
| ped | 0.2805 | 0.9135 |
| ped | 0.0142 | 0.5711 |
| ped | −0.0047 | 0.3914 |
| ped | −0.0361 | 0.3834 |
| bp | 0.0783 | 0.1481 |
| bp | −0.0058 | 0.7407 |
| bp | −0.0389 | 0.2593 |
| bp | 0.1010 | 0 |
| bp | −0.0248 | 0.4074 |
| bp | −0.0129 | 0.5556 |
| bp | −0.0245 | 1 |
| bp | −0.0661 | 0.4074 |
| bp | −0.0327 | 0.6667 |
| bp | −0.1242 | 0.4444 |
| bp | −0.0743 | 0.6296 |
| bp | 0.0136 | 0.1111 |
| bmi | −0.0747 | 0 |
| bmi | 0.0356 | 0.4192 |
| bmi | 0.0222 | 0.2727 |
| bmi | −0.0475 | 0.2525 |
| bmi | 0.0467 | 0.5657 |
| bmi | 0.0136 | 1 |
| bmi | 0.0195 | 0.4495 |
| bmi | 0.0221 | 0.6667 |
| bmi | 0.0929 | 0.2374 |
| bmi | 0.1008 | 0.3939 |
| bmi | 0.0261 | 0.3535 |
| bmi | −0.0680 | 0.1818 |
First 60 of 84 rows.
View data
| SHAP (probability) | glu |
|---|---|
| −0.1625 | 99 |
| 0.2928 | 176 |
| −0.1874 | 115 |
| −0.3038 | 84 |
| −0.2261 | 106 |
| −0.1821 | 117 |
| 0.3351 | 189 |
| −0.2160 | 99 |
| 0.1721 | 143 |
| 0.0562 | 129 |
| 0.0781 | 141 |
| −0.1584 | 106 |
View data
| SHAP (probability) | Feature | Value |
|---|---|---|
| −0.1625 | glu | 99 |
| −0.1000 | age | 21 |
| 0.0626 | ped | 0.551 |
| 0.0783 | bp | 58 |
| −0.0747 | bmi | 25.4 |
| −0.0115 | skin | 10 |
| 0.0115 | npreg | 1 |
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.
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).
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"),
)
)
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.