DRegression models · explain.gradients
Gradient attributions for a saved model
Which features move a saved network's (or linear model's) predictions, measured along the path from a baseline row to each row?
Explains a registered model version with attributions that read the model's own computation instead of probing it with altered rows: Integrated Gradients averages the gradient of the prediction along the straight path from a baseline row (the training rows' mean, or zeros) to each row, so a row's attributions add up to its prediction minus the baseline's; DeepLIFT (dense networks) passes each unit's change against the baseline back through the network and adds up exactly. It needs a model whose inside the helper can read: a linear model, or a torch network (dense network, CNN, FT-Transformer). It runs the model's own code in the engine that trained it, so Python and R agree whenever their models do.
A real result
Example “Ig mlp pima”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
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.
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.
Do it in CodeSplash Run it on your own data. It's in the Experimental lane in the app.
Worked examples in the app
- Ig mlp pimaml_pima ·
- Deeplift mlp penguinsml_penguins ·
- Ig linear airqualityml_airquality ·
- Ig logistic zero pimaml_pima ·
- Ig ft airqualityml_airquality ·
- Tree unsupported pimaml_pima ·
- Coxnet unsupported veteranveteran ·
In the guides
Where it sits in the decision guides
- Interpretable ML (trees, GAMs, SHAP, LIME) · DS & ML Decision Guide · Explain — why is it happening?
Choices you make
statistics
- Modeldefault —
The registered model version to explain: a linear model or a torch network. It runs in the engine that trained it, on this dataset's rows.
- Algorithmdefault integrated_gradients
Integrated Gradients works for linear models and every torch network; DeepLIFT for dense networks only.
- Integrated Gradients(default) — Averages the gradient along the straight path from the baseline to each row; the sum matches the prediction's change up to a small, reported gap.
- DeepLIFT (dense networks) — Passes each unit's change against the baseline back through the network (Rescale rule); the sum matches the change exactly.
- Rows to explaindefault 50
The first rows of the explained sample (the model's held-out rows, or this dataset's). Time grows in proportion.
options
- Path stepsdefault 50
Midpoints on the path from the baseline to each row; more steps shrink the completeness gap.
- Baseline rowdefault mean
What each row is compared with. Attributions answer: why this prediction rather than the baseline's?
- The training rows' mean(default) — Every design column at its training mean: an average row.
- All zeros — Every design column at 0: for scaled columns that is again the mean; for images a black image.
Advanced
- Class to explaindefault —
Multiclass models: the class whose probability is explained, empty for the first class (binary models explain the positive class).
Checks and remedies
CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.
Attributions add up
Each row's attributions should add up to its prediction minus the baseline's; a gap above 5% of the largest change means too few path steps.
- If violated → More path steps — The midpoint rule's error shrinks with the square of the number of steps.
A meaningful baselineNot checked from data: state why it holds
Attributions explain the difference from the baseline row, so a different baseline gives different attributions.
Features vary independently
The path changes all features together, but correlated features can still share or swap credit.
- If violated → Accumulated local effects — ALE compares predictions within narrow bins of the data, so correlated features never create unlikely rows.
Rows resemble the training data
Explanations of rows outside the training range describe extrapolation, not learned patterns.
The model's inside is readable
Gradient attributions need a linear model or a torch network; other models fail this check.
- If violated → KernelSHAP — KernelSHAP needs only the model's predictions, so it explains any model.
What it reports
- n_explained
- How many independent units the analysis used; it sets precision and power.
- n_background
- How many independent units the analysis used; it sets precision and power.
- n_features
- How many independent units the analysis used; it sets precision and power.
- base_value
- The row an attribution compares each row with: here the training rows' mean design row, or every design column at zero.
- top_feature
- The feature with the largest mean absolute attribution over the explained rows, and that mean (in the units of the prediction).
- top_value
- Each feature's share of the change from a baseline row to this row: the gradient averaged along the straight path, times the change.
- completeness_gap
- How 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.
- max_abs_corr
- The largest |Spearman ρ| between two numeric features in the background rows; above 0.7 the card warns that features move together.
- outside_share
- Asking a model about feature combinations it never saw, as shuffling or fixing a correlated feature does; answers are guesses, not patterns.
- score_label
- What the attributions add up to: the prediction (numbers), P(positive) for two classes, or P(class) for several.
Per group, level or term: ig_mean_abs[<feature>], deeplift_mean_abs[<feature>], ig_base, deeplift_base, ig_gap, deeplift_gap, ig_steps, ig_rows, deeplift_rows
Python and R
Python and R agree to 6 decimals (relative tolerance 1e-6). Python uses codesplash, numpy, pandas; R uses codesplashr, nanoparquet.
Default traps between the two languages
- The explanation runs the saved model's own learner code in each engine (the engine that trained it), so the two engines agree as closely as their models do: the torch networks are trained from the same initial weights, batches and written-out optimizers in double precision on LibTorch in both engines, and linear models are solved the same way. Gradients come from torch autograd for the networks and from the link's derivative for linear models; the path steps, baseline and accumulation order are written out identically in both engines.
- Path steps use the midpoint rule α_k = (k − ½)/m (Captum's 'riemann_middle'); Captum's default Gauss–Legendre steps give slightly different attributions for the same m, and both converge to the same integral.
The exact script CodeSplash ran for example “Ig mlp pima” · 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 exact script CodeSplash ran for example “Ig mlp pima” · 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")
))
Sources
- Sundararajan, M., Taly, A., & Yan, Q. (2017). Axiomatic attribution for deep networks. Proceedings of the 34th ICML, PMLR 70, 3319–3328.
- Shrikumar, A., Greenside, P., & Kundaje, A. (2017). Learning important features through propagating activation differences. Proceedings of the 34th ICML, PMLR 70, 3145–3153.
- Ancona, M., Ceolini, E., Öztireli, C., & Gross, M. (2018). Towards better understanding of gradient-based attribution methods for deep neural networks. ICLR 2018.
- Kokhlikyan, N., et al. (2020). Captum: A unified and generic model interpretability library for PyTorch. arXiv:2009.07896.
From the CodeSplash method registry · explain.gradients v1.1.0.