DRegression models · explain.permutation
Permutation importance for a saved model
Which features does a saved model rely on, measured by how much its score drops when a feature is shuffled?
Measures how much a registered model version relies on each feature on the rows of this dataset: the model's own metric is computed once, then again with one feature's values shuffled (several times, from the shared random stream), and the importance is the loss in score. Rows need the model's target. A feature the model ignores scores near zero; correlated features share importance, because shuffling one leaves its twin to carry the signal. It runs the model's own code in the engine that trained it.
A real result
Example “Tree pima”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
On 106 rows the model's ROC AUC is 0.708 (higher is better); shuffling glu costs the most (0.142).
- ROC AUC on these rows
- 0.7085
- Drop when glu is shuffled
- 0.1419
Plots
View data
| Feature | High | Importance | Low |
|---|---|---|---|
| glu | 0.1764 | 0.1419 | 0.1074 |
| age | 0.0713 | 0.0543 | 0.0374 |
| bp | 0.0276 | 0.0148 | 0.0020 |
| ped | 0.0375 | 0.0143 | −0.0089 |
| skin | 0.0088 | 0.0069 | 0.0051 |
| npreg | 0 | 0 | 0 |
| bmi | 0.0114 | −0.0103 | −0.0320 |
Assumptions
- Rows have the target — 106 of 106 rows have the target.
- Enough rows — 106 scored rows.
- Features vary independently — skin and bmi: |ρ| = 0.69.
- Rows resemble the training data — 2.8% of the explained rows fall outside the background's range.
Permutation importance (drop in ROC AUC)
| Feature | Importance | SD |
|---|---|---|
| glu | 0.1419 | 0.0345 |
| age | 0.0543 | 0.0169 |
| bp | 0.0148 | 0.0128 |
| ped | 0.0143 | 0.0232 |
| skin | 0.0069 | 0.0018 |
| npreg | 0 | 0 |
| bmi | −0.0103 | 0.0217 |
On 106 rows the model's ROC AUC is 0.708 (higher is better); shuffling glu costs the most (0.142).
- ROC AUC on these rows
- 0.7085
- Drop when glu is shuffled
- 0.1419
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Rows have the target — 106 of 106 rows have the target.
- Enough rows — 106 scored rows.
- Features vary independently — skin and bmi: |ρ| = 0.69.
- Rows resemble the training data — 2.8% of the explained rows fall outside the background's range.
Permutation importance (drop in ROC AUC)
| Feature | Importance | SD |
|---|---|---|
| glu | 0.1419 | 0.0345 |
| age | 0.0543 | 0.0169 |
| bp | 0.0148 | 0.0128 |
| ped | 0.0143 | 0.0232 |
| skin | 0.0069 | 0.0018 |
| npreg | 0 | 0 |
| bmi | −0.0103 | 0.0217 |
Do it in CodeSplash Run it on your own data. It's in the Experimental lane in the app.
Worked examples in the app
- Tree pimaml_pima ·
- Xgboost airqualityml_airquality ·
- Knn penguinsml_penguins ·
- Coxnet veteranveteran ·
- Coxnet uno veteranveteran ·
- Rsf lunglung ·
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. It runs in the engine that trained it; rows need its target (a survival model's time and event).
- Shuffles per featuredefault 5
Times each feature is shuffled; the SD across shuffles shows how noisy each importance is.
- Rows to scoredefault 1000
Rows sampled from the dataset (shared random stream). More rows make small importances clearer.
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.
Rows have the target
The score needs the true outcome; rows without it are left out of the metric.
Features vary independently
Shuffling a feature breaks its link to correlated features, so the model is scored on unlikely rows.
- 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
Importance on rows outside the training range measures extrapolation, not learned patterns.
Enough rows
With few rows the score drop from one shuffle is mostly noise.
- If violated → More shuffles — More shuffles per feature give a steadier average drop and a usable SD.
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.
- n_target
- How many independent units the analysis used; it sets precision and power.
- baseline
- The model's own metric on the explained rows before any feature is shuffled; permutation importance is the drop from it.
- top_feature
- The feature with the largest summary in this explanation: mean |SHAP|, average local effect, score drop or range of the average curve.
- top_value
- The feature with the largest summary in this explanation: mean |SHAP|, average local effect, score drop or range of the average curve.
- n_informative
- How many independent units the analysis used; it sets precision and power.
- 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.
- metric_label
- The metric whose drop measures a feature's importance when its values are shuffled, e.g. log loss or ROC AUC.
Per group, level or term: perm[<feature>], perm_sd[<feature>]
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
- Shuffles come from the shared random stream (Rng(seed + 1), features in order) and the metric is the codesplash twin, so the engines agree as closely as their models do. scikit-learn's permutation_importance shuffles with numpy's generator; on the same permutations it gives the same drops (checked in tests/crosscheck/w3ds2c_explain.py).
The exact script CodeSplash ran for example “Tree pima” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Permutation importance for a saved model
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method explain.permutation 1.1.1 · spec d4da870e1dd4e34d
# Explains the saved model learn.tree/binary_pima with its own learner code (learn.tree 1.0.0, driver mode "explain").
# Decision tree (CART)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method learn.tree 1.0.0 · spec 2c9409d7e5211ff1
# 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.tree import CART, tree_json
# %% 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_depth": 6,
"min_samples_split": 10,
"min_samples_leaf": 5,
"criterion": "gini",
"min_impurity_decrease": 0,
"ccp_alpha": 0,
}
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="none",
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
# CART with scikit-learn's DecisionTree rules and a deterministic split search (features in design
# order) — the codesplash twin, identical in Python and R.
def fit_model(X, y, w):
k = 0 if TASK == "regression" else (2 if TASK == "binary" else len(CLASSES))
model = CART(
TASK,
k,
criterion=PARAMS["criterion"],
max_depth=PARAMS["max_depth"],
min_samples_split=int(PARAMS["min_samples_split"]),
min_samples_leaf=int(PARAMS["min_samples_leaf"]),
min_impurity_decrease=PARAMS["min_impurity_decrease"],
ccp_alpha=PARAMS["ccp_alpha"],
)
return model.fit(X, y, w)
def predict_model(model, X):
p = model.predict(X)
return p[:, 1] if TASK == "binary" else p
def feature_importance(model, names):
return model.importances(names)
def save_model(model, directory):
import joblib
path = os.path.join(directory, "model.joblib")
joblib.dump(model, path)
if TASK == "binary":
classes = [[c for c in CLASSES if c != POSITIVE][0], POSITIVE] # probabilities: [other, positive]
else:
classes = CLASSES or None
return [{"key": "model", "path": path, "format": "joblib"}, tree_json(directory, model, names, 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\":\"permutation\",\"method\":\"explain.permutation\",\"model\":\"learn.tree/binary_pima\",\"title\":\"Permutation importance for a saved model\",\"version\":\"1.1.1\"},\"maxRows\":1000,\"methods\":[\"permutation\"],\"modelDir\":\"model-python/out\",\"repeats\":4,\"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="Decision tree (CART)",
engine=cs.engine_info("numpy", "numpy", "pandas"),
)
)
The exact script CodeSplash ran for example “Tree pima” · R version 4.5.1 (2025-06-13)
# Permutation importance for a saved model
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method explain.permutation 1.1.1 · spec d4da870e1dd4e34d
# Explains the saved model learn.tree/binary_pima with its own learner code (learn.tree 1.0.0, driver mode "explain").
# Decision tree (CART)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method learn.tree 1.0.0 · spec 2c9409d7e5211ff1
# 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_depth = 6,
min_samples_split = 10,
min_samples_leaf = 5,
criterion = "gini",
min_impurity_decrease = 0,
ccp_alpha = 0
)
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 = "none",
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
# CART with scikit-learn's DecisionTree rules and a deterministic split search (features in design
# order) — the codesplash twin, identical in R and Python (rpart differs: surrogates, cp scaling,
# internal cross-validation).
fit_model <- function(X, y, w) {
k <- if (TASK == "regression") 0L else if (TASK == "binary") 2L else length(CLASSES)
cs_ml_cart_fit(X, y, TASK, k, criterion = PARAMS$criterion, max_depth = PARAMS$max_depth,
min_samples_split = as.integer(PARAMS$min_samples_split),
min_samples_leaf = as.integer(PARAMS$min_samples_leaf),
min_impurity_decrease = PARAMS$min_impurity_decrease, ccp_alpha = PARAMS$ccp_alpha, w = w)
}
predict_model <- function(model, X) {
p <- cs_ml_cart_predict(model, X)
if (TASK == "binary") p[, 2] else p
}
feature_importance <- function(model, names) cs_ml_cart_importances(model, names)
save_model <- function(model, directory) {
path <- file.path(directory, "model.rds")
saveRDS(model, path)
classes <- if (TASK == "binary") c(setdiff(CLASSES, POSITIVE)[1], POSITIVE) else if (length(CLASSES)) CLASSES else NULL
list(list(key = "model", path = path, format = "rds"), cs_ml_tree_json(directory, model, names_, classes))
}
load_model <- function(directory) readRDS(file.path(directory, "model.rds"))
# %% Explain the model
REQUEST <- jsonlite::fromJSON("{\"analyze\":{\"kind\":\"permutation\",\"method\":\"explain.permutation\",\"model\":\"learn.tree/binary_pima\",\"title\":\"Permutation importance for a saved model\",\"version\":\"1.1.1\"},\"maxRows\":1000,\"methods\":[\"permutation\"],\"modelDir\":\"model-r/out\",\"repeats\":4,\"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 = "Decision tree (CART)",
engine = cs_engine_info("stats", "nanoparquet")
))
Sources
- Breiman, L. (2001). Random forests. Machine Learning, 45, 5–32.
- Fisher, A., Rudin, C., & Dominici, F. (2019). All models are wrong, but many are useful: Learning a variable's importance by studying an entire class of prediction models simultaneously. JMLR, 20(177), 1–81.
- Hooker, G., Mentch, L., & Zhou, S. (2021). Unrestricted permutation forces extrapolation: variable importance requires at least one more model, or there is no free variable importance. Statistics and Computing, 31, 82.
- Strobl, C., Boulesteix, A.-L., Kneib, T., Augustin, T., & Zeileis, A. (2008). Conditional variable importance for random forests. BMC Bioinformatics, 9, 307.
From the CodeSplash method registry · explain.permutation v1.1.1.