Skip to content

Integrated Gradients in depth: paths, baselines and completeness

Integrated Gradients sums a network's gradients along a path from a baseline to the row. Learn the formula and its completeness property, check the numerical integration, and see why the baseline and the path are part of the question.

Advanced ~14 min8 steps

What runs in CodeSplash

You will be able to

  • Write Integrated Gradients and explain completeness
  • Use the completeness gap to choose the number of path steps
  • Show how the baseline changes the attribution, and why no baseline means "absence"
  • Explain why IG and Shapley values can differ while both add up

Read first

01

Gradients along a path

Read

A plain gradient says how the output would change for a tiny nudge at the row itself. In a saturated network that gradient can be near zero even for a feature that moved the output a lot. 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. (IG) instead walks a straight path from a baselineAttribution baselineThe row an attribution compares each row with: here the training rows' mean design row, or every design column at zero. x0x_0 to the row xx and adds up the gradients along the way:

IGi(x;x0)=(xi−x0i)∫01∂f(x0+α(x−x0))∂xi dα,∑iIGi=f(x)−f(x0).\mathrm{IG}_i(x;x_0)=(x_i-x_{0i})\int_0^1\frac{\partial f\big(x_0+\alpha(x-x_0)\big)}{\partial x_i}\,d\alpha,\qquad \sum_i\mathrm{IG}_i=f(x)-f(x_0).

The second identity, completeness, holds for any differentiable model. For f=x12+x1x2f=x_1^2+x_1x_2 at (1,2)(1,2) from zero, IG gives 2 and 1, which add up to f=3f=3.

Reference · EXP004 · Runs in CodeSplashIntegrated GradientsAllocate the change in a differentiable scalar output between a reference input and the input of interest by integrating gradients along a path.
02

Completeness as a numerical check

Read

In practice the integral is a sum over mm path steps. The difference between the attributions' sum and f(x)−f(x0)f(x)-f(x_0), 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., measures the integration error, so it tells you whether you used enough steps.

Gradient attributions for a saved model — learn.torch_mlp/binary_pimaRecorded · Python and R agreeRecorded 2026-11-25 · 21 values compared
R

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

Mean |attribution| (Integrated Gradients, probability scale)Which features does the model rely on most?
View data
FeatureMean |attribution|
glu0.2374
age0.1234
ped0.0799
bp0.0592
npreg0.0534
bmi0.0517
skin0.0248
Integrated Gradients attributions per rowHow does each feature push individual predictions up or down, and for which values?
View data
FeatureAttribution (probability)Feature value (scaled)
glu−0.11690.1429
glu0.74350.7048
glu0.50590.8762
glu0.05730.3905
glu−0.03880.2952
glu−0.22130
glu−0.00500.3429
glu−0.09630.2095
glu−0.14640.0476
glu−0.14990.0857
glu−0.13970.0381
glu−0.12720.2381
glu−0.02200.3143
glu0.85251
glu0.37040.8476
glu−0.15000.1429
glu0.56560.5619
glu0.12480.4286
glu0.22770.5429
glu−0.08690.2095
age−0.09470
age−0.24030.0811
age0.16131
age−0.02550.2703
age−0.14060
age−0.11020
age−0.04180.2432
age0.05130.6486
age−0.06410.0541
age−0.08500.0270
age−0.06910.0270
age−0.14720.1081
age−0.10060.0811
age0.11290.5405
age0.09651
age−0.14270
age−0.33160.0541
age−0.17160.1081
age−0.17710.0270
age−0.10400.0270
ped0.01350.4323
ped−0.10560.1933
ped−0.02390.3539
ped−0.19110
ped−0.02780.3109
ped0.15630.8217
ped−0.03730.3399
ped−0.06540.0840
ped−0.07580.0971
ped0.00980.4146
ped−0.05910.1317
ped0.00940.3978
ped−0.19470.0009
ped−0.06340.3240
ped0.00501
ped−0.03480.3025
ped0.41070.7507
ped0.05550.4697
ped−0.03710.3221
ped−0.02120.3156

First 60 of 140 rows.

Why row 27 got its score (Integrated Gradients, probability scale)Which features pushed this one prediction up, and which pulled it down?
View data
Attribution (probability)FeatureValue
−0.1169glu99
−0.0947age21
0.0135ped0.551
−0.0025bp58
−0.0329npreg1
−0.0835bmi25.4
−0.0142skin10

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

FeatureMean |attribution|
glu0.2374
age0.1234
ped0.0799
bp0.0592
npreg0.0534
bmi0.0517
skin0.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")
))
Python

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

FeatureMean |attribution|
glu0.2374
age0.1234
ped0.0799
bp0.0592
npreg0.0534
bmi0.0517
skin0.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"),
    )
)

For a small network on pima with 32 steps, the gap is 0.030 of a probability. For a linear model the gradient is constant along the path, so IG is exact: the gap is 0.00. A small gap validates the arithmetic, nothing more: not that the path stays in the data, nor that the attribution is causal.

03

The baseline is part of the question

Read

IG explains f(x)−f(x0)f(x)-f(x_0): the difference from the baseline. Change the baseline and you change the question, and the answer.

  • Zero is meaningful only when zero means something in raw units (no dose, a blank image). Zero glucose is not a "neutral" patient.
  • The training mean is a descriptive reference, not "absence of information".
  • A quantile row can be an unusual combination of values.
Gradient attributions for a saved model — learn.linear/binary_pimaRecorded · Python and R agreeRecorded 2026-11-25 · 21 values compared
R

Across 25 rows, glu moves the model's P(true) the most (Integrated Gradients, mean |attribution| 0.142).

Mean |attribution|, glu
0.1422
Baseline P(true)
0.2648
Completeness gap
3.537e-5

Plots

Mean |attribution| (Integrated Gradients, probability scale)Which features does the model rely on most?
View data
FeatureMean |attribution|
glu0.1422
bmi0.0796
npreg0.0602
ped0.0487
age0.0481
bp0.0244
skin0.0042
Integrated Gradients attributions per rowHow does each feature push individual predictions up or down, and for which values?
View data
FeatureAttribution (probability)Feature value (scaled)
glu−0.08890.1429
glu0.30330.7048
glu0.40820.8762
glu0.02880.3905
glu−0.08580.1619
glu−0.03600.2857
glu−0.02980.2952
glu−0.19300
glu−0.00380.3429
glu−0.11740.2095
glu−0.10840.0476
glu−0.11090.0857
glu−0.11090.0381
glu−0.07460.2381
glu−0.07970.2381
glu−0.02240.3143
glu−0.09000.2190
glu0.23880.6381
glu0.57891
glu0.29440.8476
glu−0.11470.1429
glu0.17150.5619
glu0.06090.4286
glu0.13370.5429
glu−0.07050.2095
bmi−0.08680.0705
bmi−0.03920.3260
bmi0.01540.4361
bmi0.01500.4405
bmi−0.10710.0176
bmi−0.14160
bmi−0.03250.3084
bmi−0.03740.2907
bmi0.22590.8414
bmi0.08240.5639
bmi−0.01670.3260
bmi−0.04770.2159
bmi−0.03740.2291
bmi−0.09120.1806
bmi0.05510.5286
bmi0.22030.9427
bmi0.06780.5639
bmi0.21610.8414
bmi0.03170.4626
bmi0.21091
bmi0.08390.6520
bmi−0.06020.2775
bmi0.00500.4141
bmi−0.00990.3789
bmi−0.05350.2291
npreg−0.03620.0769
npreg−0.01840.2308
npreg0.10200.6154
npreg−0.03500.1538
npreg−0.02430.1538
npreg0.05930.5385
npreg−0.03010.1538
npreg−0.02920.1538
npreg−0.01870.2308
npreg0.24381

First 60 of 175 rows.

Why row 27 got its score (Integrated Gradients, probability scale)Which features pushed this one prediction up, and which pulled it down?
View data
Attribution (probability)FeatureValue
−0.0889glu99
−0.0868bmi25.4
−0.0362npreg1
0.0095ped0.551
−0.0393age21
0.0226bp58
0.0077skin10

Assumptions

  • Attributions add up — Largest gap 3.5e-05 of the biggest change from the baseline.
  • A meaningful baseline — Attributions compare each row with an all-zero 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

FeatureMean |attribution|
glu0.1422
bmi0.0796
npreg0.0602
ped0.0487
age0.0481
bp0.0244
skin0.0042
  • Integrated Gradients: the gradient of the P(true) averaged along the straight path from the baseline (zeros) to each row, 64 midpoint steps; each row's attributions add up to its P(true) minus the baseline's (0.2648), within 3.5e-05 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 33ce2a48ade90328
# Explains the saved model learn.linear/binary_pima 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 d4ad9fca485c3b22
# Dataset: ml_pima (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

# %% Data and split plan
TARGET <- "diabetic"
FEATURES <- c("npreg", "glu", "bp", "skin", "bmi", "ped", "age")
TASK <- "binary"
CLASSES <- c("false", "true")
POSITIVE <- "true"
METRIC <- "roc_auc"
SEED <- 42
PARAMS <- list(
  max_iter = 50
)

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
# 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/binary_pima\",\"title\":\"Gradient attributions for a saved model\",\"version\":\"1.1.0\"},\"gradRows\":25,\"igBaseline\":\"zero\",\"igSteps\":64,\"maxRows\":25,\"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")
))
Python

Across 25 rows, glu moves the model's P(true) the most (Integrated Gradients, mean |attribution| 0.142).

Mean |attribution|, glu
0.1422
Baseline P(true)
0.2648
Completeness gap
3.537e-5

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • Attributions add up — Largest gap 3.5e-05 of the biggest change from the baseline.
  • A meaningful baseline — Attributions compare each row with an all-zero 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

FeatureMean |attribution|
glu0.1422
bmi0.0796
npreg0.0602
ped0.0487
age0.0481
bp0.0244
skin0.0042
  • Integrated Gradients: the gradient of the P(true) averaged along the straight path from the baseline (zeros) to each row, 64 midpoint steps; each row's attributions add up to its P(true) minus the baseline's (0.2648), within 3.5e-05 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 33ce2a48ade90328
# Explains the saved model learn.linear/binary_pima 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 d4ad9fca485c3b22
# Dataset: ml_pima (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os

import numpy as np
import pandas as pd

import codesplash as cs
from codesplash import ml as csml
from codesplash.ml import linear as cslin

# %% Data and split plan
TARGET = "diabetic"
FEATURES = ["npreg", "glu", "bp", "skin", "bmi", "ped", "age"]
TASK = "binary"
CLASSES = ["false", "true"]
POSITIVE = "true"
METRIC = "roc_auc"
SEED = 42
PARAMS = {
    "max_iter": 50,
}

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
# 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/binary_pima\",\"title\":\"Gradient attributions for a saved model\",\"version\":\"1.1.0\"},\"gradRows\":25,\"igBaseline\":\"zero\",\"igSteps\":64,\"maxRows\":25,\"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"),
    )
)

With a zero baseline the reference prediction is 0.265; with the mean baseline used for the network above it is 0.355. The reference's audit saw a feature flip from a positive to a negative contribution when only the baseline changed.

Change the baseline and the number of path steps, and compare the credits with exact Shapley values.

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.

04

Predict: same sum, same split?

Predict

Predict first

For h(a,b)=a2bh(a,b)=a^2b at (2,1)(2,1) with baseline (0,0)(0,0), both exact Shapley values and straight-path IG add up to h=4h=4. Do they give the same attributions?

Yes: both add up to the same total, so they agreeNot necessarily: both are complete, but they split interactions differently
Reveal

No. Exact Shapley gives (2, 2)(2,\,2); straight-path IG gives (8/3, 4/3)(8/3,\,4/3). Both satisfy completeness, yet they share the interaction differently because they follow different axioms. Agreement between methods on simple additive models isn't independent validation.

05

Other things that bend IG

Read
  • The path leaves the data. Points between a baseline and a row may be unlike any real input.
  • Input scale. Gradients are per unit of input; standardize consistently, and keep the chain rule through any scaler.
  • Discrete inputs. For words, IG runs in embedding space; attributing to an embedding isn't intervening on a word.
  • Signed versus absolute. A heat map of absolute values hides which features pushed down. Show both.
  • Sanity check. Recompute after scrambling the model's weights; an explanation that barely changes isn't explaining the model.
06

Where it stands in CodeSplash

Read
EntryIn CodeSplash
Integrated Gradients (EXP004)Runs in CodeSplash: Gradient attributions for a saved model (Analyze) and the Explain tab, for linear and logistic models, torch MLPs and FT-Transformers, with a choice of baseline, path steps and the completeness gap; Python ≡ R
07

Check your understanding

Checkpoint

Check yourself

What does completeness guarantee for Integrated Gradients?

Show the answer

Answer: b

Completeness is a bookkeeping property. It holds for misleading baselines too.

Check yourself

An IG run with 8 path steps has a completeness gap of 0.04 on a probability scale. What should you do?

Show the answer

Answer: b

The gap shrinks as the path sum approaches the integral. Changing the baseline changes the question, not the integration accuracy.

Check yourself

A clinic uses an all-zeros baseline for IG on a model with glucose, blood pressure and BMI. What's the problem?

Show the answer

Answer: b

Pick a baseline whose meaning you can state (for example a typical patient), and show how much the attribution moves across reasonable baselines.

08

Recap

Recap
  • IG integrates gradients along a straight path from a baseline; attributions add up to f(x)−f(x0)f(x)-f(x_0).
  • The completeness gap checks the numerical integration; raise the steps until it is small.
  • The baseline defines the question; zero rarely means "absent".
  • Complete methods can disagree; completeness isn't correctness.

Concepts in this lesson