Skip to content

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.

Advanced ~14 min9 steps

What runs in CodeSplash

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

Read first

01

Two model-agnostic explainers, two questions

Read

Both 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.

02

LIME's objective

Read

LIMELIMEA simple line fitted to a model's predictions on perturbed copies of one row: a local explanation of that prediction. samples perturbed rows zjz_j around the row xx, asks the model for f(zj)f(z_j), and fits a simple model gg weighted by closeness:

g^x=arg⁡min⁡g∈G∑jπx(zj) (f(zj)−g(zj′))2+Ω(g),πx(z)=e−D(x,z)2/σ2.\hat g_x=\arg\min_{g\in\mathcal G}\sum_{j}\pi_x(z_j)\,\big(f(z_j)-g(z_j')\big)^2+\Omega(g),\qquad \pi_x(z)=e^{-D(x,z)^2/\sigma^2}.

The choices: how rows are perturbed, the distance DD and kernel width σ\sigma, the interpretable features z′z' (raw values, bins, words present), and the complexity penalty Ω\Omega. 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.
03

Is the line any good?

Read

A 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.
LIME local explanations for a saved model — learn.tree/binary_pimaRecorded · Python and R agreeRecorded 2026-11-25 · 40 values compared
R

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

LIME around row 297 — local effect on P(true)Which features does the model rely on most?
View data
FeatureLocal effect
glu0.1641
ped0.0368
age0.0329
bp−0.0324
npreg0.0135
bmi−0.0114
skin0.0086
LIME local effects on the P(true), row by rowWhat do the values of a square or rectangular result matrix look like at a glance?
View data
FeatureExplained rowLocal effect
glurow 10.1641
pedrow 10.0368
agerow 10.0329
bmirow 1−0.0114
npregrow 10.0135
bprow 1−0.0324
skinrow 10.0086
glurow 20.2526
pedrow 20.0511
agerow 20.0868
bmirow 20.1180
npregrow 2−0.0451
bprow 20.0293
skinrow 20.0305
glurow 30.2959
pedrow 30.0669
agerow 30.0317
bmirow 3−0.0013
npregrow 30.0257
bprow 3−0.0112
skinrow 30.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)

RowFeatureValueLocal effectLocal R²Top-feature stability
297glu1170.16410.43780.3333
297ped0.0890.03680.43780.3333
297age240.03290.43780.3333
297bp80−0.03240.43780.3333
297npreg00.01350.43780.3333
297bmi45.2−0.01140.43780.3333
454glu1430.25260.38370.6667
454bmi30.10.11800.38370.6667
454age230.08680.38370.6667
454ped0.8920.05110.38370.6667
454npreg1−0.04510.38370.6667
454skin300.03050.38370.6667
511glu1410.29590.57561
511ped0.4330.06690.57561
511age220.03170.57561
511npreg00.02570.57561
511skin260.01420.57561
511bp84−0.01120.57561

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")
))
Python

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)

RowFeatureValueLocal effectLocal R²Top-feature stability
297glu1170.16410.43780.3333
297ped0.0890.03680.43780.3333
297age240.03290.43780.3333
297bp80−0.03240.43780.3333
297npreg00.01350.43780.3333
297bmi45.2−0.01140.43780.3333
454glu1430.25260.38370.6667
454bmi30.10.11800.38370.6667
454age230.08680.38370.6667
454ped0.8920.05110.38370.6667
454npreg1−0.04510.38370.6667
454skin300.03050.38370.6667
511glu1410.29590.57561
511ped0.4330.06690.57561
511age220.03170.57561
511npreg00.02570.57561
511skin260.01420.57561
511bp84−0.01120.57561

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.

04

Shapley values and the coalition game

Read

A 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 SS of the other features:

ϕi=∑S⊆F∖{i}∣S∣! (d−∣S∣−1)!d![v(S∪{i})−v(S)].\phi_i=\sum_{S\subseteq F\setminus\{i\}}\frac{|S|!\,(d-|S|-1)!}{d!}\big[v(S\cup\{i\})-v(S)\big].

Everything depends on v(S)v(S), 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 SS 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 v(∅)=0v(\emptyset)=0, v({1})=1v(\{1\})=1, v({2})=2v(\{2\})=2, v({1,2})=7v(\{1,2\})=7, 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.
05

KernelSHAP: a weighted regression

Read

With dd features there are 2d2^d 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

w(S)=d−1(d∣S∣) ∣S∣ (d−∣S∣)(0<∣S∣<d),w(S)=\frac{d-1}{\binom{d}{|S|}\,|S|\,(d-|S|)}\qquad(0<|S|<d),

constrained so the values add up exactly to f(x)−v(∅)f(x)-v(\emptyset). Its solution approaches the Shapley values as the sampled subsets cover the space; with few features it can enumerate them all.

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.
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")
))
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.
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.

06

Predict: masking a correlated feature

Predict

Predict 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?

Realistic rows, since each value comes from real dataRows unlike any real row, because the two values no longer go together
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.

07

Where they stand in CodeSplash

Read
EntryIn 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.

08

Check your understanding

Checkpoint

Check 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.

09

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