Skip to content

DRegression models · explain.lime

LIME local explanations for a saved model

Around one row, which features would change a saved model's prediction, and how reliable is that local picture?

Explains single predictions of a registered model version with LIME: around each chosen row it draws perturbed copies from the training distribution, weights them by closeness, and fits a small weighted ridge line to the model's predictions. The line's slopes are the local effects; its R² says how well a line describes the model there, and a second fit on new draws measures how stable the top features are. It runs the model's own code in the engine that trained it.

Experimental Python and R agree to 6 decimals Seeded Also called LIME, local interpretable model-agnostic explanations, local surrogate…

A real result

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

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

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 pimaml_pima ·
  • Knn airqualityml_airquality ·
  • Coxnet veteranveteran ·

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.

Rows to explaindefault 5

Rows sampled from the dataset (shared random stream); each gets its own local line.

Perturbed samplesdefault 400

Perturbed copies per row. More copies give steadier slopes and stability.

options

Background datadefault model

Where perturbations draw values and spreads from.

  • The model's training sample(default) — Rows saved with the model version; perturbations then look like training data.
  • These rows — This dataset's rows; pick it when the new data differ from the training data.

Advanced

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.

  • A line fits locally

    A low local R² means the model bends sharply near the row, so the slopes are rough.

    • If violated → KernelSHAP — Shapley values do not assume the model is linear near the row and add up to the prediction.
  • Stable top features

    If a second draw picks different top features, the explanation depends on chance.

    • If violated → More perturbed samples — More perturbed copies steady the local line and its top features.
  • Features vary independently

    Perturbations change features one at a time, so correlated features create unlikely rows.

  • Rows resemble the training data

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

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.
lime_r2_mean
How well LIME's local line fits the model near each row (mean local R²) and how many top features a second draw keeps (stability).
lime_stability_mean
How well LIME's local line fits the model near each row (mean local R²) and how many top features a second draw keeps (stability).
top_feature
The feature with the largest summary in this explanation: mean |SHAP|, average local effect, score drop or range of the average curve.
top_value
The feature with the largest summary in this explanation: mean |SHAP|, average local effect, score drop or range of the average curve.
max_abs_corr
The largest |Spearman ρ| between two numeric features in the background rows; above 0.7 the card warns that features move together.
outside_share
Asking a model about feature combinations it never saw, as shuffling or fixing a correlated feature does; answers are guesses, not patterns.
score_label
What the explanation is in units of: the prediction for regression, or one class's probability.

Per group, level or term: lime[<row>|<feature>], lime_r2[<row>], lime_stability[<row>], lime_intercept[<row>]

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

  • Perturbations come from the shared random stream and the local fit is the codesplash ridge twin, so the two engines agree as closely as their models do. The lime packages draw with their own generators and discretize numbers into quartiles by default, so their slopes are on a different scale.
Python

The exact script CodeSplash ran for example “Tree pima” · 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"),
    )
)
R

The exact script CodeSplash ran for example “Tree pima” · 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")
))

Sources

  • Ribeiro, M. T., Singh, S., & Guestrin, C. (2016). "Why should I trust you?": Explaining the predictions of any classifier. KDD '16, 1135–1144.
  • Alvarez-Melis, D., & Jaakkola, T. S. (2018). On the robustness of interpretability methods. ICML Workshop on Human Interpretability, arXiv:1806.08049.
  • Molnar, C. (2022). Interpretable Machine Learning (2nd ed.), ch. 9.2.

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