Auditing an explanation: a complete workflow
Fit a model without peeking, explain one prediction three ways, then try to break the explanation: change the baseline, the steps, the neighborhood and the model's weights. Keep the failures in the report.
What runs in CodeSplash
- EXP001LIME: local interpretable model-agnostic explanations Runs in CodeSplash (Experimental)
- EXP002KernelSHAP Runs in CodeSplash (Experimental)
- EXP004Integrated Gradients Runs in CodeSplash (Experimental)
- Gradient attributions for a saved model Experimental
- SHAP values for a saved model Experimental
- LIME local explanations for a saved model Experimental
You will be able to
- State an explanation's question, target scale and reference before computing it
- Run four audits (numerical, baseline, locality, randomization) and say what each supports
- Use agreement between explainers carefully, knowing when agreement is guaranteed
- Write up an explanation with its choices and its failed checks
The question comes first
ReadThe reference's interpretability workflow starts by writing down the question: what does this fitted prediction depend on, relative to a stated reference, and how sensitive is that answer to the analyst's choices? That is not "what causes the outcome", "what should this person change" or "which training row is to blame"; other lessons cover those.
Then fix three things before computing anything:
- The target scale. Probability, log-odds, margin or loss give different attributions.
- The reference. Zero, the training mean, a quantile row or a background sample.
- The row. Choose the row to explain before seeing any explanation, or you'll pick the one with the nicest story.
Fit without peeking
ReadAn explanation of a badly chosen model explains the wrong thing. The workflow fits scaling on training rows only, picks the regularization by validation error, refits on the development rows and scores the held-out test rows once. It deliberately includes a feature that is a near-copy of another (correlation close to 1) but plays no part in generating the outcome, to show what masking does to it.
The audits below ask whether the explanation is a faithful, stable description of that fitted model. None of them makes the model causal.
Audit 1: is the arithmetic right?
ReadBefore interpreting anything, check the computation:
- Gradients against finite differences on a few rows.
- Completeness of Integrated Gradients as the path steps increase: the gap should shrink toward zero.
- Exact Shapley values by enumerating all subsets when features are few, as a unit test for KernelSHAP.
Across 15 rows, Temp moves the model's prediction the most (Integrated Gradients, mean |attribution| 13.7).
- Mean |attribution|, Temp
- 13.742
- Baseline prediction
- 30.874
- Completeness gap
- 0.0576
Plots
View data
| Feature | Mean |attribution| |
|---|---|
| Temp | 13.742 |
| Wind | 10.405 |
| solar radiation | 7.557 |
View data
| Feature | Attribution (prediction) | Feature value (scaled) |
|---|---|---|
| Temp | −16.262 | 0 |
| Temp | −12.947 | 0.0645 |
| Temp | −4.317 | 0.0323 |
| Temp | −2.892 | 0.3226 |
| Temp | 19.705 | 0.5806 |
| Temp | 24.806 | 0.6774 |
| Temp | 20.209 | 0.6452 |
| Temp | 9.744 | 0.6452 |
| Temp | 23.690 | 0.6452 |
| Temp | 51.524 | 1 |
| Temp | 0.0943 | 0.3871 |
| Temp | −2.005 | 0.3548 |
| Temp | −1.441 | 0.3226 |
| Temp | 3.717 | 0.4839 |
| Temp | −12.769 | 0.1290 |
| Wind | 2.019 | 0.5942 |
| Wind | −1.741 | 0.8406 |
| Wind | −1.375 | 1 |
| Wind | 6.706 | 0.3333 |
| Wind | 42.280 | 0.1739 |
| Wind | 40.197 | 0 |
| Wind | 5.396 | 0.5072 |
| Wind | −2.920 | 1 |
| Wind | 18.437 | 0.3333 |
| Wind | 1.486 | 0.6667 |
| Wind | −0.5703 | 0.7536 |
| Wind | 23.725 | 0.1739 |
| Wind | −0.2682 | 0.7536 |
| Wind | −0.3106 | 0.7536 |
| Wind | 8.646 | 0.2609 |
| solar radiation | 6.426 | 0.9858 |
| solar radiation | 6.033 | 0.9288 |
| solar radiation | −12.152 | 0 |
| solar radiation | 6.775 | 0.9466 |
| solar radiation | 7.891 | 0.9680 |
| solar radiation | 2.400 | 0.6192 |
| solar radiation | 6.640 | 1 |
| solar radiation | −14.550 | 0.2456 |
| solar radiation | 6.716 | 0.9324 |
| solar radiation | 4.153 | 0.6762 |
| solar radiation | 5.052 | 0.7367 |
| solar radiation | 6.332 | 0.8007 |
| solar radiation | −14.315 | 0.0498 |
| solar radiation | −11.279 | 0.4484 |
| solar radiation | 2.642 | 0.6406 |
View data
| Attribution (prediction) | Feature | Value |
|---|---|---|
| −16.262 | Temp | 66 |
| 2.019 | Wind | 9.2 |
| 6.426 | solar radiation | 290 |
Assumptions
- Attributions add up — Largest gap 0.058 of the biggest change from the baseline; use more steps.
- A meaningful baseline — Attributions compare each row with the training rows' mean design row.
- Features vary independently — Wind and Temp: |ρ| = 0.57.
- Rows resemble the training data — 6.7% of the explained rows fall outside the background's range; those explanations extrapolate.
Integrated Gradients: mean |attribution| per feature
| Feature | Mean |attribution| |
|---|---|
| Temp | 13.742 |
| Wind | 10.405 |
| solar radiation | 7.557 |
- Integrated Gradients: the gradient of the prediction averaged along the straight path from the baseline (the training rows' mean) to each row, 16 midpoint steps; each row's attributions add up to its prediction minus the baseline's (30.87), within 0.058 of the largest difference.
The exact R script · R R version 4.5.1 (2025-06-13)
# Gradient attributions for a saved model
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method explain.gradients 1.1.0 · spec 0b7f23589bd0b6f2
# Explains the saved model learn.ft_transformer/regression_airquality_full_batch with its own learner code (learn.ft_transformer 1.1.2, driver mode "explain").
# FT-Transformer
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method learn.ft_transformer 1.1.2 · spec 852f455cd9d99b38
# Dataset: ml_airquality (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# torch for R (LibTorch); the network is built by codesplashr's cs_deep_fit_ft twin.
# %% Data and split plan
TARGET <- "Ozone"
FEATURES <- c("solar radiation", "Wind", "Temp")
TASK <- "regression"
CLASSES <- c()
POSITIVE <- NULL
METRIC <- "rmse"
SEED <- 42
PARAMS <- list(
d_token = 16,
n_blocks = 2,
n_heads = 4,
ffn_factor = 1.3333333333333333,
attention_dropout = 0.2,
ffn_dropout = 0.1,
residual_dropout = 0.1,
epochs = 60,
learning_rate = 0.003,
batch_size = NULL,
weight_decay = 0.0001,
early_stopping = 0,
validation_fraction = 0.1,
optimizer = "default",
lr_schedule = "none",
warmup_epochs = 0,
grad_clip = 0,
ema_decay = 0,
swa_start = 0,
label_smoothing = 0,
mixup_alpha = 0,
history_every_step = FALSE,
profile = "parity",
checkpoint_every = NULL
)
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_airquality.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(
`solar radiation` = "numeric",
Wind = "numeric",
Temp = "numeric"
),
levels = list(
),
impute = "median",
scale = "standard",
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
# Training options, live progress and checkpoints (twin: codesplash.deep.trainer.configure).
cs_deep_trainer_configure(list(
optimizer = "default",
lr_schedule = "none",
warmup_epochs = 0,
grad_clip = 0,
ema_decay = 0,
swa_start = 0,
label_smoothing = 0,
mixup_alpha = 0,
history_every_step = FALSE,
profile = "parity",
checkpoint_every = NULL
), out_dir = "explain-out-r")
# FT-Transformer on torch for R (float64, one thread): every design column becomes a token, a [CLS] token
# is appended, and pre-norm Transformer blocks mix them; the head reads [CLS]. Initial weights, batches,
# dropout masks and early-stopping rows come from the shared random stream, so Python's torch trains the
# same network.
fit_model <- function(X, y, w) {
if (TASK == "regression") {
# Standardize the target (training mean and population SD); predictions are mapped back.
mu <- mean(y); sd <- sqrt(mean((y - mu)^2)); if (!(sd > 0)) sd <- 1
target <- (as.numeric(y) - mu) / sd; o <- 1L
} else if (TASK == "binary") {
mu <- 0; sd <- 1
target <- as.numeric(y); o <- 1L
} else {
mu <- 0; sd <- 1
target <- cs_deep_one_hot(y, length(CLASSES)); o <- length(CLASSES)
}
fit <- cs_deep_fit_ft(
unname(X), target, w, TASK, o,
d_token = as.integer(PARAMS$d_token),
n_blocks = as.integer(PARAMS$n_blocks),
n_heads = as.integer(PARAMS$n_heads),
ffn_factor = PARAMS$ffn_factor,
attention_dropout = PARAMS$attention_dropout,
ffn_dropout = PARAMS$ffn_dropout,
residual_dropout = PARAMS$residual_dropout,
epochs = as.integer(PARAMS$epochs),
lr = PARAMS$learning_rate,
batch_size = if (is.null(PARAMS$batch_size)) NULL else as.integer(PARAMS$batch_size),
weight_decay = PARAMS$weight_decay,
early_stopping = as.integer(PARAMS$early_stopping) > 0,
validation_fraction = PARAMS$validation_fraction,
patience = max(1L, as.integer(PARAMS$early_stopping)),
seed = SEED
)
fit$mu <- mu
fit$sd <- sd
fit
}
predict_model <- function(model, X) {
p <- cs_deep_ft_predict(model, unname(X), TASK)
if (TASK == "regression") model$mu + model$sd * p else p
}
feature_importance <- function(model, names) NULL
save_model <- function(model, directory) {
path <- file.path(directory, "model.rds")
saveRDS(model, path) # plain numeric weights, the architecture and the target scaling
hist <- file.path(directory, "history.parquet")
nanoparquet::write_parquet(cs_deep_history_frame(model$history), hist)
list(list(key = "model", path = path, format = "rds"), list(key = "history", path = hist, format = "parquet"))
}
load_model <- function(directory) readRDS(file.path(directory, "model.rds"))
# %% Explain the model
REQUEST <- jsonlite::fromJSON("{\"analyze\":{\"kind\":\"gradients\",\"method\":\"explain.gradients\",\"model\":\"learn.ft_transformer/regression_airquality_full_batch\",\"title\":\"Gradient attributions for a saved model\",\"version\":\"1.1.0\"},\"gradRows\":15,\"igBaseline\":\"mean\",\"igSteps\":16,\"maxRows\":15,\"methods\":[\"ig\"],\"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("torch", "codesplashr")) {
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 = "FT-Transformer",
engine = cs_engine_info("torch", "codesplashr", "nanoparquet")
))
Across 15 rows, Temp moves the model's prediction the most (Integrated Gradients, mean |attribution| 13.7).
- Mean |attribution|, Temp
- 13.742
- Baseline prediction
- 30.874
- Completeness gap
- 0.0576
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Attributions add up — Largest gap 0.058 of the biggest change from the baseline; use more steps.
- A meaningful baseline — Attributions compare each row with the training rows' mean design row.
- Features vary independently — Wind and Temp: |ρ| = 0.57.
- Rows resemble the training data — 6.7% of the explained rows fall outside the background's range; those explanations extrapolate.
Integrated Gradients: mean |attribution| per feature
| Feature | Mean |attribution| |
|---|---|
| Temp | 13.742 |
| Wind | 10.405 |
| solar radiation | 7.557 |
- Integrated Gradients: the gradient of the prediction averaged along the straight path from the baseline (the training rows' mean) to each row, 16 midpoint steps; each row's attributions add up to its prediction minus the baseline's (30.87), within 0.058 of the largest difference.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Gradient attributions for a saved model
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method explain.gradients 1.1.0 · spec 0b7f23589bd0b6f2
# Explains the saved model learn.ft_transformer/regression_airquality_full_batch with its own learner code (learn.ft_transformer 1.1.2, driver mode "explain").
# FT-Transformer
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method learn.ft_transformer 1.1.2 · spec 852f455cd9d99b38
# Dataset: ml_airquality (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.deep import core as deep
from codesplash.deep import tabular as deeptab # twin of codesplashr::cs_deep_fit_ft (shared weights, AdamW written out)
# %% Data and split plan
TARGET = "Ozone"
FEATURES = ["solar radiation", "Wind", "Temp"]
TASK = "regression"
CLASSES = []
POSITIVE = None
METRIC = "rmse"
SEED = 42
PARAMS = {
"d_token": 16,
"n_blocks": 2,
"n_heads": 4,
"ffn_factor": 1.3333333333333333,
"attention_dropout": 0.2,
"ffn_dropout": 0.1,
"residual_dropout": 0.1,
"epochs": 60,
"learning_rate": 0.003,
"batch_size": None,
"weight_decay": 0.0001,
"early_stopping": 0,
"validation_fraction": 0.1,
"optimizer": "default",
"lr_schedule": "none",
"warmup_epochs": 0,
"grad_clip": 0,
"ema_decay": 0,
"swa_start": 0,
"label_smoothing": 0,
"mixup_alpha": 0,
"history_every_step": False,
"profile": "parity",
"checkpoint_every": None,
}
df = pd.read_parquet("tests/parity/fixtures/ml_airquality.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={
"solar radiation": "numeric",
"Wind": "numeric",
"Temp": "numeric",
},
levels={
},
impute="median",
scale="standard",
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
from codesplash.deep import trainer as deep_trainer # training options, live progress, checkpoints (twin: cs_deep_trainer_*)
deep_trainer.configure(
{
"optimizer": "default",
"lr_schedule": "none",
"warmup_epochs": 0,
"grad_clip": 0,
"ema_decay": 0,
"swa_start": 0,
"label_smoothing": 0,
"mixup_alpha": 0,
"history_every_step": False,
"profile": "parity",
"checkpoint_every": None,
},
out_dir="explain-out-python",
)
# FT-Transformer on PyTorch (float64, one thread): every design column becomes a token, a [CLS] token is
# appended, and pre-norm Transformer blocks mix them; the head reads [CLS]. Initial weights, batches,
# dropout masks and early-stopping rows come from the shared random stream, so R's torch trains the same
# network.
def fit_model(X, y, w):
if TASK == "regression":
# Standardize the target (training mean and population SD); predictions are mapped back.
mu, sd = float(np.mean(y)), float(np.std(y)) or 1.0
target, o = (np.asarray(y, dtype=np.float64) - mu) / sd, 1
elif TASK == "binary":
mu, sd = 0.0, 1.0
target, o = np.asarray(y, dtype=np.float64), 1
else:
mu, sd = 0.0, 1.0
target, o = deep.one_hot(y, len(CLASSES)), len(CLASSES)
fit = deeptab.fit_ft_transformer(
X, target, w, TASK, o,
d_token=int(PARAMS["d_token"]),
n_blocks=int(PARAMS["n_blocks"]),
n_heads=int(PARAMS["n_heads"]),
ffn_factor=PARAMS["ffn_factor"],
attention_dropout=PARAMS["attention_dropout"],
ffn_dropout=PARAMS["ffn_dropout"],
residual_dropout=PARAMS["residual_dropout"],
epochs=int(PARAMS["epochs"]),
lr=PARAMS["learning_rate"],
batch_size=None if PARAMS["batch_size"] is None else int(PARAMS["batch_size"]),
weight_decay=PARAMS["weight_decay"],
early_stopping=int(PARAMS["early_stopping"]) > 0,
validation_fraction=PARAMS["validation_fraction"],
patience=max(1, int(PARAMS["early_stopping"])),
seed=SEED,
)
fit.update({"mu": mu, "sd": sd})
return fit
def predict_model(model, X):
p = deeptab.ft_predict(model, X, TASK)
if TASK == "regression":
return model["mu"] + model["sd"] * p
return p
def feature_importance(model, names):
return None
def save_model(model, directory):
import joblib
path = os.path.join(directory, "model.joblib")
joblib.dump(model, path) # plain numpy weights, the architecture and the target scaling
hist = os.path.join(directory, "history.parquet")
deep.history_frame(model["history"]).to_parquet(hist, index=False)
return [{"key": "model", "path": path, "format": "joblib"}, {"key": "history", "path": hist, "format": "parquet"}]
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\":\"gradients\",\"method\":\"explain.gradients\",\"model\":\"learn.ft_transformer/regression_airquality_full_batch\",\"title\":\"Gradient attributions for a saved model\",\"version\":\"1.1.0\"},\"gradRows\":15,\"igBaseline\":\"mean\",\"igSteps\":16,\"maxRows\":15,\"methods\":[\"ig\"],\"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="FT-Transformer",
engine=cs.engine_info("torch", "codesplash", "numpy", "pandas"),
)
)
For an FT-Transformer with only 16 path steps, the completeness gap is 0.058 on the scale of the prediction: too coarse to report without more steps. These checks prove the numbers are computed as defined, nothing more.
Audit 2: does the reference change the story?
ReadRecompute the attributions with each plausible referenceAttribution baselineThe row an attribution compares each row with: here the training rows' mean design row, or every design column at zero.. In the reference's run, switching from a zero baseline to a coordinatewise quartile row flipped one feature from a positive to a negative contribution and changed which feature dominated. That isn't a bug: the comparison point and the interaction context changed.
Report the attributions under at least two references, or state why only one is meaningful.
Before auditing a real model, check how a baseline and the step count move integrated gradients on a model whose answer you know.
DExplorable · Integrated gradients: credit along a path
A gradient says how sensitive a prediction is right here. How do you turn sensitivity into credit that adds up?
At x1 = 2 the tanh is nearly flat, so the gradient for x1 is close to 0. How much credit will integrated gradients give x1?
Model
A fixed model with known gradients. In the saturating one, tanh flattens out for large x₁.
The row being explained.
The row being explained.
The row being explained.
Baseline
Where the path starts: the input meant to stand for 'no information'. The training mean here is (0.5, −0.3, 0.2).
Used when the baseline is Custom.
Gradients are averaged at m midpoints along the path.
f = 2·tanh(2x₁) + x₂ − 0.5x₃ · baseline (0, 0, 0) · f(x) − f(baseline) = 2.499
- Integrated gradients
- Exact Shapley
- Gradient × change
The left curve is what integrated gradients walks along: the prediction as every feature moves together from the baseline to the row. Where the curve flattens, the local gradient is near zero even though the prediction has already changed a lot.
Commit your prediction above to see the result
Make your prediction to see the result.
Audit 3: how local is local?
ReadFit the local surrogate at several kernel widths and score each on fresh perturbations, weighted by closeness. Narrow widths fit closely but rest on few effectively weighted samples; wide ones summarize a bigger, more curved region less faithfully. Report the weighted fit and the effective sample size at each width, and don't tune the width until the explanation looks right.
Also check how many perturbed or masked rows lie outside the data. With two nearly copied features, independent masking puts most coalitions off the data's ridge, so the explanation partly describes extrapolationExtrapolation (explanations)Asking a model about feature combinations it never saw, as shuffling or fixing a correlated feature does; answers are guesses, not patterns..
Audit 4: does it depend on the model at all?
ReadReplace the model's learned weights with random ones and recompute. A faithful explanation should change substantially. The reference's run kept its uncomfortable result: the attributions changed in size and one sign flipped, yet their cosine similarity stayed high, because one feature dominated both vectors.
The workflow does not call that a pass. One random draw and one similarity score are too weak; repeat seeds, randomize layers separately, randomize labels and refit, and compare signed and absolute maps.
Predict: explainers that agree
PredictPredict first
For a linear model, SHAP values and Integrated Gradients rank the features the same way. How much does that agreement tell you?
Reveal
Little. For linear (and additive, pairwise-bilinear) models, the two are known to coincide given matching references, so agreement checks the arithmetic, not faithfulness. On a model with higher-order interactions they can split credit differently while both adding up.
Agreement, read carefully
ReadOn a linear model of air quality, SHAP and IG both name Temp first, with mean absolute values 11.43 and 11.46; the small difference comes from their different reference rows and explained rows.
Across 23 rows, Temp moves the model's prediction the most (mean |SHAP| 11.4).
- Mean |SHAP|, Temp
- 11.429
- Average prediction
- 48.879
Plots
View data
| Feature | Mean |SHAP| |
|---|---|
| Temp | 11.429 |
| Wind | 7.405 |
| solar radiation | 5.235 |
| Month | 3.552 |
View data
| Feature | SHAP (prediction) | Feature value (scaled) |
|---|---|---|
| Temp | −20.193 | 0 |
| Temp | −5.730 | 0.2813 |
| Temp | −18.586 | 0.0313 |
| Temp | −15.372 | 0.0938 |
| Temp | −16.979 | 0.0625 |
| Temp | −2.515 | 0.3438 |
| Temp | −20.193 | 0 |
| Temp | 10.341 | 0.5938 |
| Temp | 15.163 | 0.6875 |
| Temp | 13.555 | 0.6563 |
| Temp | 13.555 | 0.6563 |
| Temp | 13.555 | 0.6563 |
| Temp | 8.734 | 0.5625 |
| Temp | 15.163 | 0.6875 |
| Temp | −0.9084 | 0.3750 |
| Temp | 31.234 | 1 |
| Temp | 3.913 | 0.4688 |
| Temp | 0.6987 | 0.4063 |
| Temp | −0.9084 | 0.3750 |
| Temp | −2.515 | 0.3438 |
| Temp | −15.372 | 0.0938 |
| Temp | 5.520 | 0.5000 |
| Temp | −12.158 | 0.1563 |
| Wind | 1.332 | 0.3670 |
| Wind | 7.608 | 0.2110 |
| Wind | −0.8828 | 0.4220 |
| Wind | −7.158 | 0.5780 |
| Wind | −11.219 | 0.6789 |
| Wind | 5.762 | 0.2569 |
| Wind | −0.8828 | 0.4220 |
| Wind | 9.823 | 0.1560 |
| Wind | 14.252 | 0.0459 |
| Wind | 1.332 | 0.3670 |
| Wind | −11.219 | 0.6789 |
| Wind | 5.762 | 0.2569 |
| Wind | 5.762 | 0.2569 |
| Wind | 16.098 | 0 |
| Wind | −24.139 | 1 |
| Wind | −2.729 | 0.4679 |
| Wind | −7.158 | 0.5780 |
| Wind | −4.943 | 0.5229 |
| Wind | 9.823 | 0.1560 |
| Wind | −4.943 | 0.5229 |
| Wind | −4.943 | 0.5229 |
| Wind | −4.943 | 0.5229 |
| Wind | 7.608 | 0.2110 |
| solar radiation | 7.174 | 1 |
| solar radiation | −0.8421 | — |
| solar radiation | 6.484 | 0.9685 |
| solar radiation | 5.256 | 0.9126 |
| solar radiation | −14.765 | 0 |
| solar radiation | 5.640 | 0.9301 |
| solar radiation | −12.924 | 0.0839 |
| solar radiation | 6.100 | 0.9510 |
| solar radiation | −1.417 | 0.6084 |
| solar radiation | 6.790 | 0.9825 |
| solar radiation | −9.472 | 0.2413 |
| solar radiation | 5.333 | 0.9161 |
| solar radiation | 3.645 | 0.8392 |
| solar radiation | −0.8421 | — |
First 60 of 92 rows.
View data
| SHAP (prediction) | Temp |
|---|---|
| −20.193 | 65 |
| −5.730 | 74 |
| −18.586 | 66 |
| −15.372 | 68 |
| −16.979 | 67 |
| −2.515 | 76 |
| −20.193 | 65 |
| 10.341 | 84 |
| 15.163 | 87 |
| 13.555 | 86 |
| 13.555 | 86 |
| 13.555 | 86 |
| 8.734 | 83 |
| 15.163 | 87 |
| −0.9084 | 77 |
| 31.234 | 97 |
| 3.913 | 80 |
| 0.6987 | 78 |
| −0.9084 | 77 |
| −2.515 | 76 |
| −15.372 | 68 |
| 5.520 | 81 |
| −12.158 | 70 |
View data
| SHAP (prediction) | Feature | Value |
|---|---|---|
| −20.193 | Temp | 65 |
| 1.332 | Wind | 8.6 |
| 7.174 | solar radiation | 299 |
| 5.819 | Month | 5 |
Assumptions
- Enough rows — 23 explained rows, 23 background rows.
- Features vary independently — solar radiation and Month: |ρ| = 0.36.
- Rows resemble the training data — 0.0% of the explained rows fall outside the background's range.
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 1933f420f1805d9c
# Explains the saved model learn.linear/regression_airquality with its own learner code (learn.linear 1.0.0, driver mode "explain").
# Linear / logistic regression
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method learn.linear 1.0.0 · spec a4fea70974660463
# Dataset: ml_airquality (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 <- "Ozone"
FEATURES <- c("solar radiation", "Wind", "Temp", "Month")
TASK <- "regression"
CLASSES <- c()
POSITIVE <- NULL
METRIC <- "rmse"
SEED <- 42
PARAMS <- list(
max_iter = 50
)
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_airquality.parquet", col_select = unique(c(TARGET, FEATURES))))
plan <- cs_ml_read_plan("model-r/folds-data.parquet") # host-written folds: identical in Python and R
design <- cs_ml_design(
df, FEATURES,
kinds = list(
`solar radiation` = "numeric",
Wind = "numeric",
Temp = "numeric",
Month = "numeric"
),
levels = list(
),
impute = "median",
scale = "standard",
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
# Unpenalized linear / logistic / multinomial regression. The twins solve every step with the
# minimum-norm least-squares solution (SVD, relative cutoff 1e-10), so collinear one-hot designs give
# the same coefficients in R and Python (lm/glm give the same predictions but drop aliased columns).
fit_model <- function(X, y, w) {
maxit <- as.integer(PARAMS$max_iter)
if (TASK == "regression") {
f <- cs_ml_ols(X, y, w)
return(list(intercept = f$intercept, coef = f$coef, converged = TRUE))
}
if (TASK == "binary") return(cs_ml_irls_logistic(X, y, w, maxit = maxit))
cs_ml_newton_multinomial(X, y, length(CLASSES), w, maxit = maxit)
}
predict_model <- function(model, X) {
if (TASK == "multiclass") {
eta <- sweep(X %*% t(model$coef), 2, model$intercept, "+")
eta <- eta - apply(eta, 1, max)
P <- exp(eta)
return(P / rowSums(P))
}
eta <- model$intercept + as.numeric(X %*% model$coef)
if (TASK == "regression") eta else 1 / (1 + exp(-eta))
}
feature_importance <- function(model, names) {
if (!isTRUE(model$converged)) {
warnings[[length(warnings) + 1L]] <<- "The fit did not converge (separation or a near-singular design): coefficients are unreliable."
}
cs_ml_coef_importance(names, model$coef)
}
save_model <- function(model, directory) {
path <- file.path(directory, "model.rds")
saveRDS(model, path)
link <- switch(TASK, regression = "identity", binary = "logit", multiclass = "softmax")
classes <- if (TASK == "multiclass") CLASSES else POSITIVE
list(list(key = "model", path = path, format = "rds"),
cs_ml_linear_json(directory, link, names_, model$intercept, model$coef, 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.linear/regression_airquality\",\"title\":\"SHAP values for a saved model\",\"version\":\"1.1.0\"},\"coalitions\":256,\"kernelBackground\":30,\"kernelRows\":30,\"maxRows\":30,\"methods\":[\"shap\"],\"modelDir\":\"model-r/out\",\"rows\":\"auto\",\"shapRows\":30}", 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 = "Linear / logistic regression",
engine = cs_engine_info("stats", "nanoparquet")
))
Across 23 rows, Temp moves the model's prediction the most (mean |SHAP| 11.4).
- Mean |SHAP|, Temp
- 11.429
- Average prediction
- 48.879
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Enough rows — 23 explained rows, 23 background rows.
- Features vary independently — solar radiation and Month: |ρ| = 0.36.
- Rows resemble the training data — 0.0% of the explained rows fall outside the background's range.
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 1933f420f1805d9c
# Explains the saved model learn.linear/regression_airquality with its own learner code (learn.linear 1.0.0, driver mode "explain").
# Linear / logistic regression
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method learn.linear 1.0.0 · spec a4fea70974660463
# Dataset: ml_airquality (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 import linear as cslin
# %% Data and split plan
TARGET = "Ozone"
FEATURES = ["solar radiation", "Wind", "Temp", "Month"]
TASK = "regression"
CLASSES = []
POSITIVE = None
METRIC = "rmse"
SEED = 42
PARAMS = {
"max_iter": 50,
}
df = pd.read_parquet("tests/parity/fixtures/ml_airquality.parquet", columns=list(dict.fromkeys([TARGET] + FEATURES)))
plan = csml.read_plan("model-python/folds-data.parquet") # host-written folds: identical in Python and R
design = csml.Design.for_frame(
df,
FEATURES,
kinds={
"solar radiation": "numeric",
"Wind": "numeric",
"Temp": "numeric",
"Month": "numeric",
},
levels={
},
impute="median",
scale="standard",
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
# Unpenalized linear / logistic / multinomial regression. The twins solve every step with the
# minimum-norm least-squares solution (SVD, relative cutoff 1e-10), so collinear one-hot designs give
# the same coefficients in Python and R (statsmodels OLS/GLM give the same predictions).
def fit_model(X, y, w):
maxit = int(PARAMS["max_iter"])
if TASK == "regression":
b0, b = cslin.ols(X, y, w)
return {"intercept": b0, "coef": b, "converged": True}
if TASK == "binary":
b0, b, ok = cslin.irls_logistic(X, y, w, maxit=maxit)
return {"intercept": b0, "coef": b, "converged": ok}
b0, B, ok = cslin.newton_multinomial(X, y, len(CLASSES), w, maxit=maxit)
return {"intercept": b0, "coef": B, "converged": ok}
def predict_model(model, X):
if TASK == "multiclass":
return cslin.softmax_rows(model["intercept"][None, :] + X @ model["coef"].T)
eta = model["intercept"] + X @ model["coef"]
return eta if TASK == "regression" else 1.0 / (1.0 + np.exp(-eta))
def feature_importance(model, names):
if not model["converged"]:
warnings.append("The fit did not converge (separation or a near-singular design): coefficients are unreliable.")
return cslin.coef_importance(names, model["coef"])
def save_model(model, directory):
import joblib
path = os.path.join(directory, "model.joblib")
joblib.dump(model, path)
link = {"regression": "identity", "binary": "logit", "multiclass": "softmax"}[TASK]
classes = CLASSES if TASK == "multiclass" else POSITIVE
return [
{"key": "model", "path": path, "format": "joblib"},
cslin.linear_json(directory, link, names, model["intercept"], model["coef"], 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.linear/regression_airquality\",\"title\":\"SHAP values for a saved model\",\"version\":\"1.1.0\"},\"coalitions\":256,\"kernelBackground\":30,\"kernelRows\":30,\"maxRows\":30,\"methods\":[\"shap\"],\"modelDir\":\"model-python/out\",\"rows\":\"auto\",\"shapRows\":30}") 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="Linear / logistic regression",
engine=cs.engine_info("numpy", "numpy", "pandas"),
)
)
Use disagreement as a signal and agreement as a sanity check. Where explainers disagree, the reason (a different game, a different reference, an interaction) is usually the most useful finding.
Writing it up
ReadAn explanation report should let a reader rerun and doubt it:
- The question, target scale, reference and explained rows, chosen before looking.
- The model's held-out performance, scored once.
- Each audit with its result, including failures: the baseline flip, the coarse integration, the weak randomization check.
- What the explanation does not show: cause, feasible action or blame.
Where it stands in CodeSplash
Read| Part of the audit | In CodeSplash |
|---|---|
| KernelSHAP and exact Shapley (EXP002), LIME with local fit and stability (EXP001), IG with baselines and the completeness gap (EXP004) | Runs in CodeSplash: SHAP values, LIME local explanations and Gradient attributions for a saved model, plus the Explain tab's faithfulness check |
| Model randomization and the full scripted workflow | Explained here: no randomization check is built in, and CodeSplash doesn't run the reference's workflow script; the parts above run as methods |
Check your understanding
CheckpointCheck yourself
When should you choose the row to explain and the reference?
Show the answer
Answer: b
Choosing after looking is a forking path. Fix the row, scale and reference first, and show sensitivity to the reference.
Check yourself
Integrated Gradients' completeness gap falls to nearly zero with enough steps. What has the audit established?
Show the answer
Answer: b
Numerical checks validate arithmetic. Baseline, locality and randomization audits ask the harder questions.
Check yourself
A local surrogate at the narrowest width has the best weighted fit but an effective sample size of about 14. What does that mean?
Show the answer
Answer: b
Fidelity and stability trade off with width. Report both, rather than choosing the width that flatters the explanation.
Check yourself
Two features are nearly copies of each other. Why do masked coalitions in KernelSHAP fall off the data?
Show the answer
Answer: b
Check the share of rows outside the data; group the copies into one player or use a conditional method.
Check yourself
After randomizing the model's weights, the attribution vector's cosine similarity to the original is still high. What's the right conclusion?
Show the answer
Answer: b
Keep the uncomfortable result in the report. An explanation that barely depends on the learned weights can't be explaining them.
Recap
Recap- Fix the question, scale, reference and row before computing.
- Audit the arithmetic, the reference, the locality and the dependence on learned weights.
- Agreement between explainers can be guaranteed by construction; disagreement is informative.
- Report the choices and the failed checks, and what the explanation doesn't show.
Concepts in this lesson