Gradient attributions: Integrated Gradients, DeepLIFT and what a network looks at
When the model is a network or a linear model, attributions can read its gradients instead of probing it with altered rows. Learn what the baseline means, why the shares add up, and what attention rollout, Grad-CAM and concept tests add.
What runs in CodeSplash
- Gradient attributions for a saved model Experimental
You will be able to
- Explain Integrated Gradients as the gradient averaged along a path from a baseline row
- Read the completeness gap and pick a baseline that makes the question useful
- Tell attention rollout, Grad-CAM and TCAV apart from attributions that add up
Read first
Probing versus reading
ReadSHAP, LIME and permutation importance treat the model as a black box: they change rows and watch the prediction move. A network or a linear model can do better, because its gradient says how the prediction responds to each input.
The gradient alone is a poor explanation, though. A saturated sigmoid has a gradient near zero even for the feature that pushed it there.
The path from a baseline
PredictPredict first
Integrated GradientsIntegrated GradientsEach feature's share of the change from a baseline row to this row: the gradient averaged along the straight path, times the change. explain one prediction. What do they multiply each feature's change by?
Reveal
The average gradient along the path. Walk in a straight line from an attribution baselineAttribution baselineThe row an attribution compares each row with: here the training rows' mean design row, or every design column at zero. to the row, average each feature's gradient on the way and multiply by how far that feature moved. Because of calculus' fundamental theorem, the shares add up to the prediction minus the baseline's.
Read the result
ExploreA dense network trained on the Pima rows predicts P(diabetic). Against an average row, glu moves the explained rows' probability the most, by 0.237 on average. The average row itself gets 0.355.
Across 20 rows, glu moves the model's P(true) the most (Integrated Gradients, mean |attribution| 0.237).
- Mean |attribution|, glu
- 0.2374
- Baseline P(true)
- 0.3550
- Completeness gap
- 0.0298
Plots
View data
| Feature | Mean |attribution| |
|---|---|
| glu | 0.2374 |
| age | 0.1234 |
| ped | 0.0799 |
| bp | 0.0592 |
| npreg | 0.0534 |
| bmi | 0.0517 |
| skin | 0.0248 |
View data
| Feature | Attribution (probability) | Feature value (scaled) |
|---|---|---|
| glu | −0.1169 | 0.1429 |
| glu | 0.7435 | 0.7048 |
| glu | 0.5059 | 0.8762 |
| glu | 0.0573 | 0.3905 |
| glu | −0.0388 | 0.2952 |
| glu | −0.2213 | 0 |
| glu | −0.0050 | 0.3429 |
| glu | −0.0963 | 0.2095 |
| glu | −0.1464 | 0.0476 |
| glu | −0.1499 | 0.0857 |
| glu | −0.1397 | 0.0381 |
| glu | −0.1272 | 0.2381 |
| glu | −0.0220 | 0.3143 |
| glu | 0.8525 | 1 |
| glu | 0.3704 | 0.8476 |
| glu | −0.1500 | 0.1429 |
| glu | 0.5656 | 0.5619 |
| glu | 0.1248 | 0.4286 |
| glu | 0.2277 | 0.5429 |
| glu | −0.0869 | 0.2095 |
| age | −0.0947 | 0 |
| age | −0.2403 | 0.0811 |
| age | 0.1613 | 1 |
| age | −0.0255 | 0.2703 |
| age | −0.1406 | 0 |
| age | −0.1102 | 0 |
| age | −0.0418 | 0.2432 |
| age | 0.0513 | 0.6486 |
| age | −0.0641 | 0.0541 |
| age | −0.0850 | 0.0270 |
| age | −0.0691 | 0.0270 |
| age | −0.1472 | 0.1081 |
| age | −0.1006 | 0.0811 |
| age | 0.1129 | 0.5405 |
| age | 0.0965 | 1 |
| age | −0.1427 | 0 |
| age | −0.3316 | 0.0541 |
| age | −0.1716 | 0.1081 |
| age | −0.1771 | 0.0270 |
| age | −0.1040 | 0.0270 |
| ped | 0.0135 | 0.4323 |
| ped | −0.1056 | 0.1933 |
| ped | −0.0239 | 0.3539 |
| ped | −0.1911 | 0 |
| ped | −0.0278 | 0.3109 |
| ped | 0.1563 | 0.8217 |
| ped | −0.0373 | 0.3399 |
| ped | −0.0654 | 0.0840 |
| ped | −0.0758 | 0.0971 |
| ped | 0.0098 | 0.4146 |
| ped | −0.0591 | 0.1317 |
| ped | 0.0094 | 0.3978 |
| ped | −0.1947 | 0.0009 |
| ped | −0.0634 | 0.3240 |
| ped | 0.0050 | 1 |
| ped | −0.0348 | 0.3025 |
| ped | 0.4107 | 0.7507 |
| ped | 0.0555 | 0.4697 |
| ped | −0.0371 | 0.3221 |
| ped | −0.0212 | 0.3156 |
First 60 of 140 rows.
View data
| Attribution (probability) | Feature | Value |
|---|---|---|
| −0.1169 | glu | 99 |
| −0.0947 | age | 21 |
| 0.0135 | ped | 0.551 |
| −0.0025 | bp | 58 |
| −0.0329 | npreg | 1 |
| −0.0835 | bmi | 25.4 |
| −0.0142 | skin | 10 |
Assumptions
- Attributions add up — Largest gap 0.03 of the biggest change from the baseline.
- A meaningful baseline — Attributions compare each row with the training rows' mean design row.
- 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.
Integrated Gradients: mean |attribution| per feature
| Feature | Mean |attribution| |
|---|---|
| glu | 0.2374 |
| age | 0.1234 |
| ped | 0.0799 |
| bp | 0.0592 |
| npreg | 0.0534 |
| bmi | 0.0517 |
| skin | 0.0248 |
- Integrated Gradients: the gradient of the P(true) averaged along the straight path from the baseline (the training rows' mean) to each row, 32 midpoint steps; each row's attributions add up to its P(true) minus the baseline's (0.355), within 0.03 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 5efa8c7dcc631cff
# Explains the saved model learn.torch_mlp/binary_pima with its own learner code (learn.torch_mlp 1.4.2, driver mode "explain").
# Deep neural network (torch MLP)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method learn.torch_mlp 1.4.2 · spec d818e821457ce417
# 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)
# torch for R (LibTorch); the network itself is built by codesplashr's cs_deep_* twins.
# %% 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(
hidden_layers = c(16, 8),
activation = "relu",
epochs = 120,
learning_rate = 0.01,
batch_size = NULL,
weight_decay = 0.0001,
early_stopping = 0,
validation_fraction = 0.1,
dropout = 0,
mc_passes = 0,
variational_weights = FALSE,
prior_scale = 1,
kl_weight = 1,
robust_training = "none",
dro_step = 0.01,
adv_epsilon = 0.1,
adv_steps = 5,
trades_beta = 6,
loss = "cross_entropy",
focal_gamma = 2,
focal_alpha = NULL,
dp_epsilon = NULL,
dp_noise_multiplier = NULL,
dp_max_grad_norm = 1,
dp_delta = NULL,
dp_sampling = "poisson",
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_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 = "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(
dp_epsilon = NULL,
dp_noise_multiplier = NULL,
dp_max_grad_norm = 1,
dp_delta = NULL,
dp_sampling = "poisson",
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")
# A dense network on torch for R (float64, one thread): hidden layers HIDDEN with ACTIVATION units, a
# linear output (1 value, 1 logit or K logits), trained by Adam from weights drawn from the shared
# random stream — Python's torch starts from the same weights and takes the same steps.
HIDDEN <- as.integer(unlist(PARAMS$hidden_layers))
if (!length(HIDDEN)) HIDDEN <- 32L
ACTIVATION <- PARAMS$activation
DROPOUT <- as.numeric(PARAMS$dropout)
PASSES <- as.integer(PARAMS$mc_passes)
VARIATIONAL <- isTRUE(PARAMS$variational_weights)
ROBUST <- PARAMS$robust_training
# Any of the options on: train with cs_deep_fit_mlp_ext (otherwise the plain network, unchanged).
EXTENDED <- DROPOUT > 0 || PASSES > 0 || VARIATIONAL || ROBUST != "none"
fit_model <- function(X, y, w) {
if (cs_deep_dp_enabled() && !is.null(w) && diff(range(as.numeric(w))) > 0) {
cs_error("CS_E_INVALID_OPTION", option = "Differential privacy", allowed = "off with row or class weights", value = "on")
}
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)
}
if (!EXTENDED) {
fit <- cs_deep_fit_mlp(
unname(X), target, w, TASK, HIDDEN, o,
activation = ACTIVATION,
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
)
return(list(params = fit$params, mu = mu, sd = sd, history = fit$history, best_epoch = fit$best_epoch))
}
fit <- cs_deep_fit_mlp_ext(
unname(X), target, w, TASK, HIDDEN, o,
activation = ACTIVATION,
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,
dropout = DROPOUT,
variational = VARIATIONAL,
prior_scale = PARAMS$prior_scale,
kl_weight = PARAMS$kl_weight,
robust = ROBUST,
groups = if (ROBUST != "group_dro") NULL else SUBGROUPS[FIT_ROWS + 1L],
dro_step = PARAMS$dro_step,
adv_epsilon = PARAMS$adv_epsilon,
adv_steps = as.integer(PARAMS$adv_steps),
trades_beta = PARAMS$trades_beta,
mc_passes = PASSES
)
fit$mu <- mu; fit$sd <- sd; fit$extended <- TRUE
fit
}
predict_model <- function(model, X) {
p <- if (!isTRUE(model$extended)) cs_deep_mlp_predict(model$params, unname(X), ACTIVATION, TASK) else cs_deep_mlp_predict_ext(model, unname(X), TASK)$mean
if (TASK == "regression") model$mu + model$sd * p else p
}
# Predictive SD (numbers, with prediction passes): sqrt(training residual variance + spread across passes).
predict_sd <- function(model, X) model$sd * sqrt(model$noise_var + cs_deep_mlp_predict_ext(model, unname(X), TASK)$spread)
feature_importance <- function(model, names) NULL
save_model <- function(model, directory) {
path <- file.path(directory, "model.rds")
saveRDS(model, path) # plain numeric weights + 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.torch_mlp/binary_pima\",\"title\":\"Gradient attributions for a saved model\",\"version\":\"1.1.0\"},\"gradRows\":20,\"igBaseline\":\"mean\",\"igSteps\":32,\"maxRows\":20,\"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 = "Deep neural network (torch MLP)",
engine = cs_engine_info("torch", "codesplashr", "nanoparquet")
))
Across 20 rows, glu moves the model's P(true) the most (Integrated Gradients, mean |attribution| 0.237).
- Mean |attribution|, glu
- 0.2374
- Baseline P(true)
- 0.3550
- Completeness gap
- 0.0298
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Attributions add up — Largest gap 0.03 of the biggest change from the baseline.
- A meaningful baseline — Attributions compare each row with the training rows' mean design row.
- 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.
Integrated Gradients: mean |attribution| per feature
| Feature | Mean |attribution| |
|---|---|
| glu | 0.2374 |
| age | 0.1234 |
| ped | 0.0799 |
| bp | 0.0592 |
| npreg | 0.0534 |
| bmi | 0.0517 |
| skin | 0.0248 |
- Integrated Gradients: the gradient of the P(true) averaged along the straight path from the baseline (the training rows' mean) to each row, 32 midpoint steps; each row's attributions add up to its P(true) minus the baseline's (0.355), within 0.03 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 5efa8c7dcc631cff
# Explains the saved model learn.torch_mlp/binary_pima with its own learner code (learn.torch_mlp 1.4.2, driver mode "explain").
# Deep neural network (torch MLP)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method learn.torch_mlp 1.4.2 · spec d818e821457ce417
# 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.deep import core as deep # twin of codesplashr::cs_deep_* (shared initial weights, Adam written out)
from codesplash.deep import mlp_ext as mlpx # dropout, variational weights, Group DRO, PGD/TRADES (twin: cs_deep_*_ext)
from codesplash.deep import dp as deep_dp # differentially private training, DP-SGD (twin: cs_deep_dp_*)
# %% 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 = {
"hidden_layers": [16, 8],
"activation": "relu",
"epochs": 120,
"learning_rate": 0.01,
"batch_size": None,
"weight_decay": 0.0001,
"early_stopping": 0,
"validation_fraction": 0.1,
"dropout": 0,
"mc_passes": 0,
"variational_weights": False,
"prior_scale": 1,
"kl_weight": 1,
"robust_training": "none",
"dro_step": 0.01,
"adv_epsilon": 0.1,
"adv_steps": 5,
"trades_beta": 6,
"loss": "cross_entropy",
"focal_gamma": 2,
"focal_alpha": None,
"dp_epsilon": None,
"dp_noise_multiplier": None,
"dp_max_grad_norm": 1,
"dp_delta": None,
"dp_sampling": "poisson",
"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_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="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(
{
"dp_epsilon": None,
"dp_noise_multiplier": None,
"dp_max_grad_norm": 1,
"dp_delta": None,
"dp_sampling": "poisson",
"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",
)
# A dense network on PyTorch (float64, one thread): hidden layers HIDDEN with ACTIVATION units, a
# linear output (1 value, 1 logit or K logits), trained by Adam from weights drawn from the shared
# random stream — R's torch starts from the same weights and takes the same steps.
HIDDEN = [int(u) for u in PARAMS["hidden_layers"]] or [32]
ACTIVATION = PARAMS["activation"]
DROPOUT = float(PARAMS["dropout"])
PASSES = int(PARAMS["mc_passes"])
VARIATIONAL = bool(PARAMS["variational_weights"])
ROBUST = PARAMS["robust_training"]
# Any of the options on: train with codesplash.deep.mlp_ext (otherwise the plain network, unchanged).
EXTENDED = DROPOUT > 0 or PASSES > 0 or VARIATIONAL or ROBUST != "none"
def fit_model(X, y, w):
if deep_dp.enabled() and w is not None and float(np.ptp(np.asarray(w, dtype=np.float64))) > 0:
cs.cs_error("CS_E_INVALID_OPTION", option="Differential privacy", allowed="off with row or class weights", value="on")
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)
common = dict(
activation=ACTIVATION,
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,
)
if not EXTENDED:
fit = deep.fit_mlp(X, target, w, TASK, HIDDEN, o, **common)
return {"params": fit["params"], "mu": mu, "sd": sd, "history": fit["history"], "best_epoch": fit["best_epoch"]}
fit = mlpx.fit_mlp_ext(
X, target, w, TASK, HIDDEN, o, **common,
dropout=DROPOUT,
variational=VARIATIONAL,
prior_scale=PARAMS["prior_scale"],
kl_weight=PARAMS["kl_weight"],
robust=ROBUST,
groups=None if ROBUST != "group_dro" else SUBGROUPS[FIT_ROWS],
dro_step=PARAMS["dro_step"],
adv_epsilon=PARAMS["adv_epsilon"],
adv_steps=int(PARAMS["adv_steps"]),
trades_beta=PARAMS["trades_beta"],
mc_passes=PASSES,
)
fit.update({"mu": mu, "sd": sd, "extended": True})
return fit
def predict_model(model, X):
if not model.get("extended"):
p = deep.mlp_predict(model["params"], X, ACTIVATION, TASK)
else:
p, _ = mlpx.mlp_predict_ext(model, X, TASK)
if TASK == "regression":
return model["mu"] + model["sd"] * p
return p
def predict_sd(model, X):
"""Predictive SD (numbers, with prediction passes): √(training residual variance + spread across passes)."""
_, spread = mlpx.mlp_predict_ext(model, X, TASK)
return model["sd"] * np.sqrt(model["noise_var"] + spread)
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 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.torch_mlp/binary_pima\",\"title\":\"Gradient attributions for a saved model\",\"version\":\"1.1.0\"},\"gradRows\":20,\"igBaseline\":\"mean\",\"igSteps\":32,\"maxRows\":20,\"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="Deep neural network (torch MLP)",
engine=cs.engine_info("torch", "codesplash", "numpy", "pandas"),
)
)
The card's Attributions add up row reports the completeness gapCompleteness gapHow far a row's attributions miss its prediction minus the baseline's, as a share of the largest such change; 0 means they add up.: 0.03 of the largest change here. The path is cut into midpoint steps, and the gap shrinks as they grow: with the square of their number for a smooth model, more slowly where ReLU units switch on or off along the path. The card warns above 5%.
The baseline is part of the question
ReflectAttributions answer "why this prediction rather than the baseline's?". Against the training rows' mean, a feature at its average value gets nothing. Against all zeros, scaled columns still sit at their mean, but a black image or a zero count is a very different reference. Which baseline would make the question useful in your own data?
Notebook exercise · ~15 min
Integrated Gradients and a randomization check
Compute Integrated Gradients for a small network, check completeness, and run the sanity check that an explanation must change when the weights are scrambled.
- Integrated Gradients
Integrated Gradients multiplies (x − baseline) by the average gradient along the straight path from the baseline to x. Approximate the average with 200 midpoints, α = (k + 0.5) / 200 for k = 0 … 199, and store the five attributions in
ig.Show a solution
Pythondef integrated_gradients(grad, x, base, m=200): alphas = (np.arange(m) + 0.5) / m return (x - base) * np.mean([grad(base + a * (x - base)) for a in alphas], axis=0) ig = integrated_gradients(grad_f, x_star, baseline)Rintegrated_gradients <- function(grad, x, base, m = 200) { alphas <- ((0:(m - 1)) + 0.5) / m (x - base) * rowMeans(sapply(alphas, function(a) grad(base + a * (x - base)))) } ig <- integrated_gradients(grad_f, x_star, baseline) - Completeness
Integrated Gradients should add up to f(x) − f(baseline). Store the absolute gap between the sum of
igand that difference ingap. Is it small?Show a solution
Pythongap = abs(ig.sum() - (f(x_star) - f(baseline)))Rgap <- abs(sum(ig) - (f(x_star) - f(baseline))) - The randomization check
Compute Integrated Gradients for the randomized network (
grad_rand) at the same point and baseline. Store the Spearman rank correlation between the absolute attributions of the real and the randomized network inrank_r. A value near 1 would mean the method ignores the weights.Show a solution
Pythonrank_r = stats.spearmanr(np.abs(ig), np.abs(integrated_gradients(grad_rand, x_star, baseline)))[0]Rrank_r <- cor(abs(ig), abs(integrated_gradients(grad_rand, x_star, baseline)), method = "spearman")
In the app this opens as a Python or R notebook with the sample data, and its checks mark your progress.
A linear model is the check
ExploreFor a straight-line model the gradient never changes, so Integrated Gradients reduce to coefficient × (value − baseline): exactly the linear SHAP values. On the air-quality regression the largest mean attribution is 11.456 ppb, for Temp, with a completeness gap of 0.00.
Across 23 rows, Temp moves the model's prediction the most (Integrated Gradients, mean |attribution| 11.5).
- Mean |attribution|, Temp
- 11.456
- Baseline prediction
- 43.323
- Completeness gap
- 8.615e-16
Plots
View data
| Feature | Mean |attribution| |
|---|---|
| Temp | 11.456 |
| Wind | 7.917 |
| solar radiation | 5.961 |
| Month | 3.563 |
View data
| Feature | Attribution (prediction) | Feature value (scaled) |
|---|---|---|
| Temp | −20.806 | 0 |
| Temp | −6.342 | 0.2813 |
| Temp | −19.199 | 0.0313 |
| Temp | −15.985 | 0.0938 |
| Temp | −17.592 | 0.0625 |
| Temp | −3.128 | 0.3438 |
| Temp | −20.806 | 0 |
| Temp | 9.729 | 0.5938 |
| Temp | 14.550 | 0.6875 |
| Temp | 12.943 | 0.6563 |
| Temp | 12.943 | 0.6563 |
| Temp | 12.943 | 0.6563 |
| Temp | 8.122 | 0.5625 |
| Temp | 14.550 | 0.6875 |
| Temp | −1.521 | 0.3750 |
| Temp | 30.621 | 1 |
| Temp | 3.301 | 0.4688 |
| Temp | 0.0864 | 0.4063 |
| Temp | −1.521 | 0.3750 |
| Temp | −3.128 | 0.3438 |
| Temp | −15.985 | 0.0938 |
| Temp | 4.908 | 0.5000 |
| Temp | −12.770 | 0.1563 |
| Wind | 5.482 | 0.3670 |
| Wind | 11.757 | 0.2110 |
| Wind | 3.267 | 0.4220 |
| Wind | −3.009 | 0.5780 |
| Wind | −7.069 | 0.6789 |
| Wind | 9.912 | 0.2569 |
| Wind | 3.267 | 0.4220 |
| Wind | 13.972 | 0.1560 |
| Wind | 18.402 | 0.0459 |
| Wind | 5.482 | 0.3670 |
| Wind | −7.069 | 0.6789 |
| Wind | 9.912 | 0.2569 |
| Wind | 9.912 | 0.2569 |
| Wind | 20.248 | 0 |
| Wind | −19.990 | 1 |
| Wind | 1.421 | 0.4679 |
| Wind | −3.009 | 0.5780 |
| Wind | −0.7939 | 0.5229 |
| Wind | 13.972 | 0.1560 |
| Wind | −0.7939 | 0.5229 |
| Wind | −0.7939 | 0.5229 |
| Wind | −0.7939 | 0.5229 |
| Wind | 11.757 | 0.2110 |
| solar radiation | 9.112 | 1 |
| solar radiation | 1.096 | — |
| solar radiation | 8.422 | 0.9685 |
| solar radiation | 7.195 | 0.9126 |
| solar radiation | −12.826 | 0 |
| solar radiation | 7.578 | 0.9301 |
| solar radiation | −10.985 | 0.0839 |
| solar radiation | 8.038 | 0.9510 |
| solar radiation | 0.5209 | 0.6084 |
| solar radiation | 8.729 | 0.9825 |
| solar radiation | −7.534 | 0.2413 |
| solar radiation | 7.271 | 0.9161 |
| solar radiation | 5.584 | 0.8392 |
| solar radiation | 1.096 | — |
First 60 of 92 rows.
View data
| Attribution (prediction) | Feature | Value |
|---|---|---|
| −20.806 | Temp | 65 |
| 5.482 | Wind | 8.6 |
| 9.112 | solar radiation | 299 |
| 5.900 | Month | 5 |
Assumptions
- Attributions add up — Largest gap 8.6e-16 of the biggest change from the baseline.
- 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 — 4.3% of the explained rows fall outside the background's range.
Integrated Gradients: mean |attribution| per feature
| Feature | Mean |attribution| |
|---|---|
| Temp | 11.456 |
| Wind | 7.917 |
| solar radiation | 5.961 |
| Month | 3.563 |
- Integrated Gradients: the gradient of the prediction averaged along the straight path from the baseline (the training rows' mean) to each row, 50 midpoint steps; each row's attributions add up to its prediction minus the baseline's (43.32), within 8.6e-16 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 ddfbb33e839abcd9
# 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.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\":\"gradients\",\"method\":\"explain.gradients\",\"model\":\"learn.linear/regression_airquality\",\"title\":\"Gradient attributions for a saved model\",\"version\":\"1.1.0\"},\"gradRows\":30,\"igBaseline\":\"mean\",\"igSteps\":50,\"maxRows\":30,\"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("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 (Integrated Gradients, mean |attribution| 11.5).
- Mean |attribution|, Temp
- 11.456
- Baseline prediction
- 43.323
- Completeness gap
- 7.571e-16
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Attributions add up — Largest gap 7.6e-16 of the biggest change from the baseline.
- 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 — 4.3% of the explained rows fall outside the background's range.
Integrated Gradients: mean |attribution| per feature
| Feature | Mean |attribution| |
|---|---|
| Temp | 11.456 |
| Wind | 7.917 |
| solar radiation | 5.961 |
| Month | 3.563 |
- Integrated Gradients: the gradient of the prediction averaged along the straight path from the baseline (the training rows' mean) to each row, 50 midpoint steps; each row's attributions add up to its prediction minus the baseline's (43.32), within 7.6e-16 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 ddfbb33e839abcd9
# 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.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\":\"gradients\",\"method\":\"explain.gradients\",\"model\":\"learn.linear/regression_airquality\",\"title\":\"Gradient attributions for a saved model\",\"version\":\"1.1.0\"},\"gradRows\":30,\"igBaseline\":\"mean\",\"igSteps\":50,\"maxRows\":30,\"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="Linear / logistic regression",
engine=cs.engine_info("numpy", "numpy", "pandas"),
)
)
DeepLIFT: exact sums, one pass
PredictPredict first
DeepLIFTDeepLIFTPasses each unit's change against a baseline row back through a network, scaled by its input's change, so contributions add up exactly. passes each unit's change against the baseline back through the network, divided by its input's change. When does it equal Integrated Gradients?
Reveal
When no unit changes side. If every ReLU stays on or off along the path, the network is linear there and both methods give the exact path integral. Otherwise they differ, and only DeepLIFT adds up exactly without extra steps.
On the penguins network (tanh units, three species), DeepLIFT explains P(Gentoo): its largest mean contribution is 0.190, with a gap of 0.00.
Across 20 rows, bill_dep moves the model's P(Gentoo) the most (DeepLIFT, mean |attribution| 0.19).
- Mean |attribution|, bill_dep
- 0.1902
- Baseline P(Gentoo)
- 0.6267
- Completeness gap
- 1.037e-6
Plots
View data
| Feature | Mean |attribution| |
|---|---|
| bill_dep | 0.1902 |
| island | 0.1560 |
| bill_len | 0.1263 |
| body_mass | 0.0951 |
| flipper_len | 0.0633 |
| sex | 0.0401 |
View data
| Feature | Attribution (probability) | Feature value (scaled) |
|---|---|---|
| bill_dep | −0.2406 | 0.7468 |
| bill_dep | −0.4134 | 1 |
| bill_dep | −0.4948 | 0.7848 |
| bill_dep | −0.0731 | 0.5316 |
| bill_dep | −0.1881 | 0.7722 |
| bill_dep | −0.1992 | 0.6709 |
| bill_dep | −0.2205 | 0.7089 |
| bill_dep | −0.1701 | 0.6329 |
| bill_dep | 0.2043 | 0.0127 |
| bill_dep | 0.1530 | 0 |
| bill_dep | 0.1177 | 0.1392 |
| bill_dep | 0.0962 | 0.2278 |
| bill_dep | 0.0956 | 0.2405 |
| bill_dep | 0.1308 | 0.1266 |
| bill_dep | −0.2503 | 0.7975 |
| bill_dep | −0.2124 | 0.8481 |
| bill_dep | −0.0449 | 0.5696 |
| bill_dep | −0.1565 | 0.6203 |
| bill_dep | −0.1564 | 0.7342 |
| bill_dep | −0.1849 | 0.7215 |
| island | 0.0918 | 0 |
| island | −0.0315 | 0.5000 |
| island | 0.1644 | 0 |
| island | 0.1330 | 0 |
| island | −0.1171 | 1 |
| island | 0.0927 | 0 |
| island | 0.0944 | 0 |
| island | −0.2207 | 1 |
| island | 0.1037 | 0 |
| island | 0.0760 | 0 |
| island | 0.0896 | 0 |
| island | 0.0728 | 0 |
| island | 0.1294 | 0 |
| island | 0.0986 | 0 |
| island | −0.2811 | 0.5000 |
| island | −0.1756 | 0.5000 |
| island | −0.1975 | 0.5000 |
| island | −0.4480 | 0.5000 |
| island | −0.2165 | 0.5000 |
| island | −0.2853 | 0.5000 |
| bill_len | −0.3733 | 0.0349 |
| bill_len | −0.0636 | 0.3144 |
| bill_len | −0.1534 | 0.3013 |
| bill_len | −0.4341 | 0.1703 |
| bill_len | −0.2472 | 0 |
| bill_len | −0.3380 | 0.1223 |
| bill_len | −0.2071 | 0.2009 |
| bill_len | −0.1319 | 0.2795 |
| bill_len | −0.0029 | 0.3581 |
| bill_len | 0.0035 | 0.4279 |
| bill_len | 0.0053 | 0.4847 |
| bill_len | 0.0318 | 0.5677 |
| bill_len | −0.0495 | 0.6725 |
| bill_len | 0.0003 | 0.5109 |
| bill_len | −0.0735 | 0.6725 |
| bill_len | −0.0108 | 0.6638 |
| bill_len | −0.0990 | 1 |
| bill_len | −0.1361 | 0.6157 |
| bill_len | −0.0624 | 0.6900 |
| bill_len | −0.1025 | 0.7118 |
First 60 of 120 rows.
View data
| Attribution (probability) | Feature | Value |
|---|---|---|
| −0.2406 | bill_dep | 19.2 |
| 0.0918 | island | Biscoe |
| −0.3733 | bill_len | 35.9 |
| −0.0566 | body_mass | 3800 |
| −0.0958 | flipper_len | 189 |
| 0.0479 | sex | female |
Assumptions
- Attributions add up — Largest gap 1e-06 of the biggest change from the baseline.
- A meaningful baseline — Attributions compare each row with the training rows' mean design row.
- Features vary independently — flipper_len and body_mass: |ρ| = 0.85; changing one alone creates unlikely rows, so read their shares as joint.
- Rows resemble the training data — 0.0% of the explained rows fall outside the background's range.
DeepLIFT: mean |attribution| per feature
| Feature | Mean |attribution| |
|---|---|
| bill_dep | 0.1902 |
| island | 0.1560 |
| bill_len | 0.1263 |
| body_mass | 0.0951 |
| flipper_len | 0.0633 |
| sex | 0.0401 |
- DeepLIFT (Rescale rule): each unit passes back its change against the baseline (the training rows' mean) divided by its input's change, so each row's contributions add up to its P(Gentoo) minus the baseline's (gap 1e-06).
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 abdb212379a0402c
# Explains the saved model learn.torch_mlp/multiclass_penguins_tanh_batches with its own learner code (learn.torch_mlp 1.4.2, driver mode "explain").
# Deep neural network (torch MLP)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method learn.torch_mlp 1.4.2 · spec ae5076502a5bb0d4
# Dataset: ml_penguins (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 itself is built by codesplashr's cs_deep_* twins.
# %% Data and split plan
TARGET <- "species"
FEATURES <- c("island", "bill_len", "bill_dep", "flipper_len", "body_mass", "sex")
TASK <- "multiclass"
CLASSES <- c("Adelie", "Chinstrap", "Gentoo")
POSITIVE <- NULL
METRIC <- "log_loss"
SEED <- 42
PARAMS <- list(
hidden_layers = c(12),
activation = "tanh",
epochs = 60,
learning_rate = 0.02,
batch_size = 32,
weight_decay = 0.0001,
early_stopping = 0,
validation_fraction = 0.1,
dropout = 0,
mc_passes = 0,
variational_weights = FALSE,
prior_scale = 1,
kl_weight = 1,
robust_training = "none",
dro_step = 0.01,
adv_epsilon = 0.1,
adv_steps = 5,
trades_beta = 6,
loss = "cross_entropy",
focal_gamma = 2,
focal_alpha = NULL,
dp_epsilon = NULL,
dp_noise_multiplier = NULL,
dp_max_grad_norm = 1,
dp_delta = NULL,
dp_sampling = "poisson",
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_penguins.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(
island = "categorical",
bill_len = "numeric",
bill_dep = "numeric",
flipper_len = "numeric",
body_mass = "numeric",
sex = "categorical"
),
levels = list(
island = c("Biscoe", "Dream", "Torgersen"),
sex = c("female", "male")
),
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(
dp_epsilon = NULL,
dp_noise_multiplier = NULL,
dp_max_grad_norm = 1,
dp_delta = NULL,
dp_sampling = "poisson",
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")
# A dense network on torch for R (float64, one thread): hidden layers HIDDEN with ACTIVATION units, a
# linear output (1 value, 1 logit or K logits), trained by Adam from weights drawn from the shared
# random stream — Python's torch starts from the same weights and takes the same steps.
HIDDEN <- as.integer(unlist(PARAMS$hidden_layers))
if (!length(HIDDEN)) HIDDEN <- 32L
ACTIVATION <- PARAMS$activation
DROPOUT <- as.numeric(PARAMS$dropout)
PASSES <- as.integer(PARAMS$mc_passes)
VARIATIONAL <- isTRUE(PARAMS$variational_weights)
ROBUST <- PARAMS$robust_training
# Any of the options on: train with cs_deep_fit_mlp_ext (otherwise the plain network, unchanged).
EXTENDED <- DROPOUT > 0 || PASSES > 0 || VARIATIONAL || ROBUST != "none"
fit_model <- function(X, y, w) {
if (cs_deep_dp_enabled() && !is.null(w) && diff(range(as.numeric(w))) > 0) {
cs_error("CS_E_INVALID_OPTION", option = "Differential privacy", allowed = "off with row or class weights", value = "on")
}
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)
}
if (!EXTENDED) {
fit <- cs_deep_fit_mlp(
unname(X), target, w, TASK, HIDDEN, o,
activation = ACTIVATION,
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
)
return(list(params = fit$params, mu = mu, sd = sd, history = fit$history, best_epoch = fit$best_epoch))
}
fit <- cs_deep_fit_mlp_ext(
unname(X), target, w, TASK, HIDDEN, o,
activation = ACTIVATION,
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,
dropout = DROPOUT,
variational = VARIATIONAL,
prior_scale = PARAMS$prior_scale,
kl_weight = PARAMS$kl_weight,
robust = ROBUST,
groups = if (ROBUST != "group_dro") NULL else SUBGROUPS[FIT_ROWS + 1L],
dro_step = PARAMS$dro_step,
adv_epsilon = PARAMS$adv_epsilon,
adv_steps = as.integer(PARAMS$adv_steps),
trades_beta = PARAMS$trades_beta,
mc_passes = PASSES
)
fit$mu <- mu; fit$sd <- sd; fit$extended <- TRUE
fit
}
predict_model <- function(model, X) {
p <- if (!isTRUE(model$extended)) cs_deep_mlp_predict(model$params, unname(X), ACTIVATION, TASK) else cs_deep_mlp_predict_ext(model, unname(X), TASK)$mean
if (TASK == "regression") model$mu + model$sd * p else p
}
# Predictive SD (numbers, with prediction passes): sqrt(training residual variance + spread across passes).
predict_sd <- function(model, X) model$sd * sqrt(model$noise_var + cs_deep_mlp_predict_ext(model, unname(X), TASK)$spread)
feature_importance <- function(model, names) NULL
save_model <- function(model, directory) {
path <- file.path(directory, "model.rds")
saveRDS(model, path) # plain numeric weights + 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.torch_mlp/multiclass_penguins_tanh_batches\",\"title\":\"Gradient attributions for a saved model\",\"version\":\"1.1.0\"},\"class\":\"Gentoo\",\"gradRows\":20,\"igBaseline\":\"mean\",\"igSteps\":32,\"maxRows\":20,\"methods\":[\"deeplift\"],\"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 = "Deep neural network (torch MLP)",
engine = cs_engine_info("torch", "codesplashr", "nanoparquet")
))
Across 20 rows, bill_dep moves the model's P(Gentoo) the most (DeepLIFT, mean |attribution| 0.19).
- Mean |attribution|, bill_dep
- 0.1902
- Baseline P(Gentoo)
- 0.6267
- Completeness gap
- 1.037e-6
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Attributions add up — Largest gap 1e-06 of the biggest change from the baseline.
- A meaningful baseline — Attributions compare each row with the training rows' mean design row.
- Features vary independently — flipper_len and body_mass: |ρ| = 0.85; changing one alone creates unlikely rows, so read their shares as joint.
- Rows resemble the training data — 0.0% of the explained rows fall outside the background's range.
DeepLIFT: mean |attribution| per feature
| Feature | Mean |attribution| |
|---|---|
| bill_dep | 0.1902 |
| island | 0.1560 |
| bill_len | 0.1263 |
| body_mass | 0.0951 |
| flipper_len | 0.0633 |
| sex | 0.0401 |
- DeepLIFT (Rescale rule): each unit passes back its change against the baseline (the training rows' mean) divided by its input's change, so each row's contributions add up to its P(Gentoo) minus the baseline's (gap 1e-06).
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 abdb212379a0402c
# Explains the saved model learn.torch_mlp/multiclass_penguins_tanh_batches with its own learner code (learn.torch_mlp 1.4.2, driver mode "explain").
# Deep neural network (torch MLP)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method learn.torch_mlp 1.4.2 · spec ae5076502a5bb0d4
# Dataset: ml_penguins (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 # twin of codesplashr::cs_deep_* (shared initial weights, Adam written out)
from codesplash.deep import mlp_ext as mlpx # dropout, variational weights, Group DRO, PGD/TRADES (twin: cs_deep_*_ext)
from codesplash.deep import dp as deep_dp # differentially private training, DP-SGD (twin: cs_deep_dp_*)
# %% Data and split plan
TARGET = "species"
FEATURES = ["island", "bill_len", "bill_dep", "flipper_len", "body_mass", "sex"]
TASK = "multiclass"
CLASSES = ["Adelie", "Chinstrap", "Gentoo"]
POSITIVE = None
METRIC = "log_loss"
SEED = 42
PARAMS = {
"hidden_layers": [12],
"activation": "tanh",
"epochs": 60,
"learning_rate": 0.02,
"batch_size": 32,
"weight_decay": 0.0001,
"early_stopping": 0,
"validation_fraction": 0.1,
"dropout": 0,
"mc_passes": 0,
"variational_weights": False,
"prior_scale": 1,
"kl_weight": 1,
"robust_training": "none",
"dro_step": 0.01,
"adv_epsilon": 0.1,
"adv_steps": 5,
"trades_beta": 6,
"loss": "cross_entropy",
"focal_gamma": 2,
"focal_alpha": None,
"dp_epsilon": None,
"dp_noise_multiplier": None,
"dp_max_grad_norm": 1,
"dp_delta": None,
"dp_sampling": "poisson",
"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_penguins.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={
"island": "categorical",
"bill_len": "numeric",
"bill_dep": "numeric",
"flipper_len": "numeric",
"body_mass": "numeric",
"sex": "categorical",
},
levels={
"island": ["Biscoe", "Dream", "Torgersen"],
"sex": ["female", "male"],
},
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(
{
"dp_epsilon": None,
"dp_noise_multiplier": None,
"dp_max_grad_norm": 1,
"dp_delta": None,
"dp_sampling": "poisson",
"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",
)
# A dense network on PyTorch (float64, one thread): hidden layers HIDDEN with ACTIVATION units, a
# linear output (1 value, 1 logit or K logits), trained by Adam from weights drawn from the shared
# random stream — R's torch starts from the same weights and takes the same steps.
HIDDEN = [int(u) for u in PARAMS["hidden_layers"]] or [32]
ACTIVATION = PARAMS["activation"]
DROPOUT = float(PARAMS["dropout"])
PASSES = int(PARAMS["mc_passes"])
VARIATIONAL = bool(PARAMS["variational_weights"])
ROBUST = PARAMS["robust_training"]
# Any of the options on: train with codesplash.deep.mlp_ext (otherwise the plain network, unchanged).
EXTENDED = DROPOUT > 0 or PASSES > 0 or VARIATIONAL or ROBUST != "none"
def fit_model(X, y, w):
if deep_dp.enabled() and w is not None and float(np.ptp(np.asarray(w, dtype=np.float64))) > 0:
cs.cs_error("CS_E_INVALID_OPTION", option="Differential privacy", allowed="off with row or class weights", value="on")
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)
common = dict(
activation=ACTIVATION,
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,
)
if not EXTENDED:
fit = deep.fit_mlp(X, target, w, TASK, HIDDEN, o, **common)
return {"params": fit["params"], "mu": mu, "sd": sd, "history": fit["history"], "best_epoch": fit["best_epoch"]}
fit = mlpx.fit_mlp_ext(
X, target, w, TASK, HIDDEN, o, **common,
dropout=DROPOUT,
variational=VARIATIONAL,
prior_scale=PARAMS["prior_scale"],
kl_weight=PARAMS["kl_weight"],
robust=ROBUST,
groups=None if ROBUST != "group_dro" else SUBGROUPS[FIT_ROWS],
dro_step=PARAMS["dro_step"],
adv_epsilon=PARAMS["adv_epsilon"],
adv_steps=int(PARAMS["adv_steps"]),
trades_beta=PARAMS["trades_beta"],
mc_passes=PASSES,
)
fit.update({"mu": mu, "sd": sd, "extended": True})
return fit
def predict_model(model, X):
if not model.get("extended"):
p = deep.mlp_predict(model["params"], X, ACTIVATION, TASK)
else:
p, _ = mlpx.mlp_predict_ext(model, X, TASK)
if TASK == "regression":
return model["mu"] + model["sd"] * p
return p
def predict_sd(model, X):
"""Predictive SD (numbers, with prediction passes): √(training residual variance + spread across passes)."""
_, spread = mlpx.mlp_predict_ext(model, X, TASK)
return model["sd"] * np.sqrt(model["noise_var"] + spread)
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 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.torch_mlp/multiclass_penguins_tanh_batches\",\"title\":\"Gradient attributions for a saved model\",\"version\":\"1.1.0\"},\"class\":\"Gentoo\",\"gradRows\":20,\"igBaseline\":\"mean\",\"igSteps\":32,\"maxRows\":20,\"methods\":[\"deeplift\"],\"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="Deep neural network (torch MLP)",
engine=cs.engine_info("torch", "codesplash", "numpy", "pandas"),
)
)
Where a network looks, and what it represents
ReadThree more views live in Predict's Explain tab for the networks that support them:
- Attention rolloutAttention rolloutMultiplies a transformer's attention maps across blocks (with half the weight on the skip path) to see which inputs the output token reads. (FT-Transformer) follows what the [CLS] token reads through every block. It shows where attention flows, not how much a feature changes the prediction.
- Grad-CAMGrad-CAMA heat map of where a CNN looks for a class: the last convolution block's maps, weighted by how much they raise the class score. (CNN) draws a heat map of the image regions that raise the class score. It is as coarse as the last convolution block.
- TCAVTCAV (concept activation vectors)Tests whether a prediction rises along the direction that separates rows matching a concept from other rows in a hidden layer. (dense networks) asks a different question: does the prediction rise along the direction that separates rows matching a concept, such as "age > 50", from other rows? Compare it with random directions before reading anything into it.
The code behind it
Readimport numpy as np
# Integrated Gradients for a logistic model, by hand: midpoint steps on the path.
def integrated_gradients(b, c, x, x0, m=50):
alphas = (np.arange(m) + 0.5) / m
grads = []
for a in alphas:
z = c + (x0 + a * (x - x0)) @ b
s = 1 / (1 + np.exp(-z))
grads.append(s * (1 - s) * b)
return (x - x0) * np.mean(grads, axis=0)# Integrated Gradients for a logistic model, by hand: midpoint steps on the path.
integrated_gradients <- function(b, c, x, x0, m = 50) {
alphas <- (seq_len(m) - 0.5) / m
grads <- sapply(alphas, function(a) {
z <- c + sum((x0 + a * (x - x0)) * b)
s <- 1 / (1 + exp(-z))
s * (1 - s) * b
})
(x - x0) * rowMeans(matrix(grads, nrow = length(b)))
}Check your understanding
CheckpointCheck yourself
An Integrated Gradients card warns that the attributions miss the prediction's change by 9% of it. What do you do?
Show the answer
Answer: a
Increase the number of path steps. The midpoint rule approximates the path integral, and its error falls as the steps grow. DeepLIFT adds up exactly if the model is a dense network.
Check yourself
You rerun Integrated Gradients with All zeros instead of The training rows' mean, and the attributions change. Why?
Show the answer
Answer: a
The baseline is part of the question. Attributions split the difference between the row's prediction and the baseline's, so a new baseline gives a new split.
Check yourself
A TCAV run scores 0.62 for the concept "glucose > 140", and random directions score 0.60 on average. What can you say?
Show the answer
Answer: a
No clear sensitivity. A concept the network doesn't represent scores like random directions; the test's p-value says whether the gap is larger than the runs' noise.
Check yourself
Which model can DeepLIFT explain in CodeSplash?
Show the answer
Answer: a
A dense torch network. DeepLIFT follows each unit's change through the layers, so it needs the network's weights; boosted trees have exact TreeSHAP instead.
Concepts in this lesson