Skip to content

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.

Advanced ~15 min12 steps

What runs in CodeSplash

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

Read first

01

The question comes first

Read

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

Fit without peeking

Read

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

03

Audit 1: is the arithmetic right?

Read

Before 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.
Gradient attributions for a saved model — learn.ft_transformer/regression_airquality_full_batchRecorded · Python and R agreeRecorded 2026-11-25 · 17 values compared
R

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

Mean |attribution| (Integrated Gradients, prediction scale)Which features does the model rely on most?
View data
FeatureMean |attribution|
Temp13.742
Wind10.405
solar radiation7.557
Integrated Gradients attributions per rowHow does each feature push individual predictions up or down, and for which values?
View data
FeatureAttribution (prediction)Feature value (scaled)
Temp−16.2620
Temp−12.9470.0645
Temp−4.3170.0323
Temp−2.8920.3226
Temp19.7050.5806
Temp24.8060.6774
Temp20.2090.6452
Temp9.7440.6452
Temp23.6900.6452
Temp51.5241
Temp0.09430.3871
Temp−2.0050.3548
Temp−1.4410.3226
Temp3.7170.4839
Temp−12.7690.1290
Wind2.0190.5942
Wind−1.7410.8406
Wind−1.3751
Wind6.7060.3333
Wind42.2800.1739
Wind40.1970
Wind5.3960.5072
Wind−2.9201
Wind18.4370.3333
Wind1.4860.6667
Wind−0.57030.7536
Wind23.7250.1739
Wind−0.26820.7536
Wind−0.31060.7536
Wind8.6460.2609
solar radiation6.4260.9858
solar radiation6.0330.9288
solar radiation−12.1520
solar radiation6.7750.9466
solar radiation7.8910.9680
solar radiation2.4000.6192
solar radiation6.6401
solar radiation−14.5500.2456
solar radiation6.7160.9324
solar radiation4.1530.6762
solar radiation5.0520.7367
solar radiation6.3320.8007
solar radiation−14.3150.0498
solar radiation−11.2790.4484
solar radiation2.6420.6406
Why row 13 got its score (Integrated Gradients, prediction scale)Which features pushed this one prediction up, and which pulled it down?
View data
Attribution (prediction)FeatureValue
−16.262Temp66
2.019Wind9.2
6.426solar radiation290

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

FeatureMean |attribution|
Temp13.742
Wind10.405
solar radiation7.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")
))
Python

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

FeatureMean |attribution|
Temp13.742
Wind10.405
solar radiation7.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.

04

Audit 2: does the reference change the story?

Read

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

1.0
How sure?

Model

A fixed model with known gradients. In the saturating one, tanh flattens out for large x₁.

2.0

The row being explained.

1.0

The row being explained.

1.0

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

1.0

Used when the baseline is Custom.

20

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

x₁x₂x₃
  • 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 first; the figure appears when you commit.

Make your prediction to see the result.

05

Audit 3: how local is local?

Read

Fit 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 (∑w)2/∑w2(\sum w)^2/\sum w^2 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..

06

Audit 4: does it depend on the model at all?

Read

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

07

Predict: explainers that agree

Predict

Predict first

For a linear model, SHAP values and Integrated Gradients rank the features the same way. How much does that agreement tell you?

Strong independent evidence that both are rightExpected by construction here, so weak evidence
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.

08

Agreement, read carefully

Read

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

SHAP values for a saved model — learn.linear/regression_airqualityRecorded · Python and R agreeRecorded 2026-11-25 · 15 values compared
R

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

Mean |SHAP| (linear SHAP, prediction scale)Which features does the model rely on most?
View data
FeatureMean |SHAP|
Temp11.429
Wind7.405
solar radiation5.235
Month3.552
SHAP values per row (linear SHAP)How does each feature push individual predictions up or down, and for which values?
View data
FeatureSHAP (prediction)Feature value (scaled)
Temp−20.1930
Temp−5.7300.2813
Temp−18.5860.0313
Temp−15.3720.0938
Temp−16.9790.0625
Temp−2.5150.3438
Temp−20.1930
Temp10.3410.5938
Temp15.1630.6875
Temp13.5550.6563
Temp13.5550.6563
Temp13.5550.6563
Temp8.7340.5625
Temp15.1630.6875
Temp−0.90840.3750
Temp31.2341
Temp3.9130.4688
Temp0.69870.4063
Temp−0.90840.3750
Temp−2.5150.3438
Temp−15.3720.0938
Temp5.5200.5000
Temp−12.1580.1563
Wind1.3320.3670
Wind7.6080.2110
Wind−0.88280.4220
Wind−7.1580.5780
Wind−11.2190.6789
Wind5.7620.2569
Wind−0.88280.4220
Wind9.8230.1560
Wind14.2520.0459
Wind1.3320.3670
Wind−11.2190.6789
Wind5.7620.2569
Wind5.7620.2569
Wind16.0980
Wind−24.1391
Wind−2.7290.4679
Wind−7.1580.5780
Wind−4.9430.5229
Wind9.8230.1560
Wind−4.9430.5229
Wind−4.9430.5229
Wind−4.9430.5229
Wind7.6080.2110
solar radiation7.1741
solar radiation−0.8421—
solar radiation6.4840.9685
solar radiation5.2560.9126
solar radiation−14.7650
solar radiation5.6400.9301
solar radiation−12.9240.0839
solar radiation6.1000.9510
solar radiation−1.4170.6084
solar radiation6.7900.9825
solar radiation−9.4720.2413
solar radiation5.3330.9161
solar radiation3.6450.8392
solar radiation−0.8421—

First 60 of 92 rows.

SHAP dependence — TempHow does one feature's value change its contribution, and does another feature modify it?
View data
SHAP (prediction)Temp
−20.19365
−5.73074
−18.58666
−15.37268
−16.97967
−2.51576
−20.19365
10.34184
15.16387
13.55586
13.55586
13.55586
8.73483
15.16387
−0.908477
31.23497
3.91380
0.698778
−0.908477
−2.51576
−15.37268
5.52081
−12.15870
Why row 7 got its score (linear SHAP, prediction scale)Which features pushed this one prediction up, and which pulled it down?
View data
SHAP (prediction)FeatureValue
−20.193Temp65
1.332Wind8.6
7.174solar radiation299
5.819Month5

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

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.

09

Writing it up

Read

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

Where it stands in CodeSplash

Read
Part of the auditIn 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 workflowExplained here: no randomization check is built in, and CodeSplash doesn't run the reference's workflow script; the parts above run as methods
11

Check your understanding

Checkpoint

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

12

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