LIME and KernelSHAP in depth: the neighborhood and the game
LIME fits a small model near one row; KernelSHAP solves a weighted regression over feature subsets. Learn the choices hidden in each, and the checks that say whether an explanation is faithful.
What runs in CodeSplash
- EXP001LIME: local interpretable model-agnostic explanations Runs in CodeSplash (Experimental)
- EXP002KernelSHAP Runs in CodeSplash (Experimental)
- LIME local explanations for a saved model Experimental
- SHAP values for a saved model Experimental
You will be able to
- Write LIME's weighted surrogate objective and name the choices that change it
- Read local fit (weighted R²) and stability as LIME's quality checks
- Write the Shapley value and the KernelSHAP weights, and say what the coalition value function is
- Explain how masking correlated features creates off-manifold rows
Two model-agnostic explainers, two questions
ReadBoth explainers need only a model's predictions, and both answer "what does this prediction depend on?" for one row. They differ in the question underneath:
- LIME asks: near this row, which straight line best imitates the model? Its answer is a set of local slopes.
- KernelSHAP asks: how should the gap between this prediction and a baseline be shared among the features, fairly? Its answer is a set of Shapley values that add up to the gap.
Each hides choices that change the answer. This lesson makes them visible.
LIME's objective
ReadLIMELIMEA simple line fitted to a model's predictions on perturbed copies of one row: a local explanation of that prediction. samples perturbed rows around the row , asks the model for , and fits a simple model weighted by closeness:
The choices: how rows are perturbed, the distance and kernel width , the interpretable features (raw values, bins, words present), and the complexity penalty . On the reference's tiny fixture the weighted line recovers slopes 1.00 and 2.00 for a function whose interaction term it can't represent.
Reference · EXP001 · Runs in CodeSplashLIME: local interpretable model-agnostic explanationsFit an interpretable surrogate around a particular input by querying a fixed predictor on perturbed examples. The explanation describes a chosen local approximation rather than the complete predictor.Is the line any good?
ReadA bar chart of LIME slopes looks equally confident whether the line fits or not. Two checks, both reported by LIME local explanations for a saved model:
- Local fitLIME local fit and stabilityHow well LIME's local line fits the model near each row (mean local R²) and how many top features a second draw keeps (stability)., the weighted R² of the line on fresh perturbations, measured against the model, not the labels.
- Stability, whether a second draw keeps the same top features.
Around 3 rows, local lines fit with mean R² 0.47; glu has the largest average local effect (0.238).
- Mean local R²
- 0.4657
- Top-feature stability
- 0.6667
Plots
View data
| Feature | Local effect |
|---|---|
| glu | 0.1641 |
| ped | 0.0368 |
| age | 0.0329 |
| bp | −0.0324 |
| npreg | 0.0135 |
| bmi | −0.0114 |
| skin | 0.0086 |
View data
| Feature | Explained row | Local effect |
|---|---|---|
| glu | row 1 | 0.1641 |
| ped | row 1 | 0.0368 |
| age | row 1 | 0.0329 |
| bmi | row 1 | −0.0114 |
| npreg | row 1 | 0.0135 |
| bp | row 1 | −0.0324 |
| skin | row 1 | 0.0086 |
| glu | row 2 | 0.2526 |
| ped | row 2 | 0.0511 |
| age | row 2 | 0.0868 |
| bmi | row 2 | 0.1180 |
| npreg | row 2 | −0.0451 |
| bp | row 2 | 0.0293 |
| skin | row 2 | 0.0305 |
| glu | row 3 | 0.2959 |
| ped | row 3 | 0.0669 |
| age | row 3 | 0.0317 |
| bmi | row 3 | −0.0013 |
| npreg | row 3 | 0.0257 |
| bp | row 3 | −0.0112 |
| skin | row 3 | 0.0142 |
Assumptions
- A line fits locally — Mean local R² 0.47; the model bends near these rows, so the slopes are rough.
- Stable top features — A second draw keeps 67% of the top features; use more perturbed samples.
- 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.
LIME: local effects on P(true)
| Row | Feature | Value | Local effect | Local R² | Top-feature stability |
|---|---|---|---|---|---|
| 297 | glu | 117 | 0.1641 | 0.4378 | 0.3333 |
| 297 | ped | 0.089 | 0.0368 | 0.4378 | 0.3333 |
| 297 | age | 24 | 0.0329 | 0.4378 | 0.3333 |
| 297 | bp | 80 | −0.0324 | 0.4378 | 0.3333 |
| 297 | npreg | 0 | 0.0135 | 0.4378 | 0.3333 |
| 297 | bmi | 45.2 | −0.0114 | 0.4378 | 0.3333 |
| 454 | glu | 143 | 0.2526 | 0.3837 | 0.6667 |
| 454 | bmi | 30.1 | 0.1180 | 0.3837 | 0.6667 |
| 454 | age | 23 | 0.0868 | 0.3837 | 0.6667 |
| 454 | ped | 0.892 | 0.0511 | 0.3837 | 0.6667 |
| 454 | npreg | 1 | −0.0451 | 0.3837 | 0.6667 |
| 454 | skin | 30 | 0.0305 | 0.3837 | 0.6667 |
| 511 | glu | 141 | 0.2959 | 0.5756 | 1 |
| 511 | ped | 0.433 | 0.0669 | 0.5756 | 1 |
| 511 | age | 22 | 0.0317 | 0.5756 | 1 |
| 511 | npreg | 0 | 0.0257 | 0.5756 | 1 |
| 511 | skin | 26 | 0.0142 | 0.5756 | 1 |
| 511 | bp | 84 | −0.0112 | 0.5756 | 1 |
A number's effect is per +1 training SD; a category's effect is what its current value adds over a random other value.
- LIME fits a local line to 200 perturbed copies of each row. Stability is the share of the top features that a second fit also picks; a low value means the explanation depends on the random draw.
The exact R script · R R version 4.5.1 (2025-06-13)
# LIME local explanations for a saved model
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method explain.lime 1.1.0 · spec 5c82609f306c59fc
# 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\":\"lime\",\"method\":\"explain.lime\",\"model\":\"learn.tree/binary_pima\",\"title\":\"LIME local explanations for a saved model\",\"version\":\"1.1.0\"},\"limeRows\":3,\"limeSamples\":200,\"maxRows\":3,\"methods\":[\"lime\"],\"modelDir\":\"model-r/out\",\"rows\":\"auto\"}", 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")
))
Around 3 rows, local lines fit with mean R² 0.47; glu has the largest average local effect (0.238).
- Mean local R²
- 0.4657
- Top-feature stability
- 0.6667
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- A line fits locally — Mean local R² 0.47; the model bends near these rows, so the slopes are rough.
- Stable top features — A second draw keeps 67% of the top features; use more perturbed samples.
- 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.
LIME: local effects on P(true)
| Row | Feature | Value | Local effect | Local R² | Top-feature stability |
|---|---|---|---|---|---|
| 297 | glu | 117 | 0.1641 | 0.4378 | 0.3333 |
| 297 | ped | 0.089 | 0.0368 | 0.4378 | 0.3333 |
| 297 | age | 24 | 0.0329 | 0.4378 | 0.3333 |
| 297 | bp | 80 | −0.0324 | 0.4378 | 0.3333 |
| 297 | npreg | 0 | 0.0135 | 0.4378 | 0.3333 |
| 297 | bmi | 45.2 | −0.0114 | 0.4378 | 0.3333 |
| 454 | glu | 143 | 0.2526 | 0.3837 | 0.6667 |
| 454 | bmi | 30.1 | 0.1180 | 0.3837 | 0.6667 |
| 454 | age | 23 | 0.0868 | 0.3837 | 0.6667 |
| 454 | ped | 0.892 | 0.0511 | 0.3837 | 0.6667 |
| 454 | npreg | 1 | −0.0451 | 0.3837 | 0.6667 |
| 454 | skin | 30 | 0.0305 | 0.3837 | 0.6667 |
| 511 | glu | 141 | 0.2959 | 0.5756 | 1 |
| 511 | ped | 0.433 | 0.0669 | 0.5756 | 1 |
| 511 | age | 22 | 0.0317 | 0.5756 | 1 |
| 511 | npreg | 0 | 0.0257 | 0.5756 | 1 |
| 511 | skin | 26 | 0.0142 | 0.5756 | 1 |
| 511 | bp | 84 | −0.0112 | 0.5756 | 1 |
A number's effect is per +1 training SD; a category's effect is what its current value adds over a random other value.
- LIME fits a local line to 200 perturbed copies of each row. Stability is the share of the top features that a second fit also picks; a low value means the explanation depends on the random draw.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# LIME local explanations for a saved model
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method explain.lime 1.1.0 · spec 5c82609f306c59fc
# 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\":\"lime\",\"method\":\"explain.lime\",\"model\":\"learn.tree/binary_pima\",\"title\":\"LIME local explanations for a saved model\",\"version\":\"1.1.0\"},\"limeRows\":3,\"limeSamples\":200,\"maxRows\":3,\"methods\":[\"lime\"],\"modelDir\":\"model-python/out\",\"rows\":\"auto\"}") 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"),
)
)
For a decision tree on pima, the mean local R² is 0.47 and stability 0.67: a tree's steps aren't locally linear. For k-nearest neighbors on air quality, local R² is 0.78 and stability 1.00.
Shapley values and the coalition game
ReadA Shapley valueShapley valueA feature's average contribution to a prediction, over all orders in which features could arrive. averages a feature's marginal contribution over every subset of the other features:
Everything depends on , the coalition value functionCoalition value functionWhat a model 'predicts' when only some features are known. Its choice (fixed baseline, background, conditional) defines the SHAP game.: what the model "predicts" when only the features in are known. Fill absent features from a fixed baseline, from a background sample, or from their conditional distribution, and you get three different games with three sets of exact Shapley values. For two features with , , , , the values are 3 and 4, adding up to 7.
Reference · EXP002 · Runs in CodeSplashKernelSHAPEstimate Shapley feature attributions by fitting a weighted additive explanation over feature coalitions, using the SHAP kernel and constraints that fix the empty and full coalition values.KernelSHAP: a weighted regression
ReadWith features there are subsets. KernelSHAPKernelSHAPShapley values for any model, estimated from its predictions on subsets of features; base value + all values = the prediction. samples some, evaluates the model with the absent features masked, and fits a linear model by weighted least squares with weights
constrained so the values add up exactly to . Its solution approaches the Shapley values as the sampled subsets cover the space; with few features it can enumerate them all.
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.
The exact R script · R 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")
))
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.
The exact Python script · Python 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"),
)
)
Here the average prediction (the baseline) is 0.410, and the top feature is glu.
Predict: masking a correlated feature
PredictPredict first
Height and weight are strongly correlated. KernelSHAP fills an absent "weight" with background values while keeping this row's "height". What rows does the model see?
Reveal
Rows unlike any real row. A tall person paired with a background weight from a short one is an off-manifold inputOff-manifold inputA perturbed or masked row unlike any real row, such as one that breaks a strong correlation. Explanations built on such rows mislead.. The model's prediction there is extrapolation, and the attribution can credit or blame features for behavior on rows that never occur. LIME's independent perturbations have the same problem.
Where they stand in CodeSplash
Read| Entry | In CodeSplash |
|---|---|
| LIME (EXP001) | Runs in CodeSplash: LIME local explanations for a saved model (Analyze) and the Predict Explain tab, with local R² and stability |
| KernelSHAP (EXP002) | Runs in CodeSplash: SHAP values for a saved model with algorithm Kernel (exact when the subsets can be enumerated), and the Explain tab |
The lesson Exact Shapley values, anchors, diverse counterfactuals, influence and the audit shows how CodeSplash checks faithfulness.
Check your understanding
CheckpointCheck yourself
A LIME explanation has a mean local R² of 0.2. What should you conclude about its slopes?
Show the answer
Answer: b
Local R² measures fidelity to the model, not accuracy against labels. A low value means the model bends sharply there; try a narrower kernel or another explainer.
Check yourself
You widen LIME's kernel. The local R² drops but the slopes become more stable. Which is the "right" width?
Show the answer
Answer: b
Kernel width defines the question ("how far is near?"). Tuning it until a pleasing story appears is a forking path; show the sensitivity instead.
Check yourself
Two teams compute exact Shapley values for the same model and row and get different numbers. Both are correct. How?
Show the answer
Answer: b
"Exact" is exact for a game. Name the value function and the background whenever you report SHAP values.
Check yourself
What constraint does KernelSHAP's weighted regression enforce?
Show the answer
Answer: b
Additivity is built in. It is bookkeeping for the chosen game, not evidence that the attribution is causal or faithful.
Check yourself
Why do correlated features trouble both LIME and KernelSHAP?
Show the answer
Answer: b
Count how many perturbed rows fall outside the data's range or dependence pattern. Grouping correlated features into one player helps.
Recap
Recap- LIME fits a weighted line near a row; check local R² and stability before reading slopes.
- Shapley values average marginal contributions; the coalition value function defines the game.
- KernelSHAP is a constrained weighted regression over sampled subsets.
- Masking or perturbing correlated features creates off-manifold rows.
Concepts in this lesson