Skip to content

Explain a saved model in Analyze, and see what a network learns about categories

The explainers run as Analyze methods on any registered model version, with checks that say when an explanation leaves the data. Entity embeddings show which category levels a network treats alike.

Advanced ~11 min12 steps

What runs in CodeSplash

You will be able to

  • Pick the Analyze explanation that answers your question about a saved model
  • Read the dependence and extrapolation rows before trusting an explanation
  • Read an entity-embedding map by distances and neighbors, not axes

Read first

01

A saved model, explained anywhere

Read

Once you register a model version, Analyze can explain it on any dataset: the test rows, last month's rows, or one segment. Pick SHAP values for a saved model, LIME local explanations, Permutation importance or Partial dependence and choose the version under Model.

The explanation runs the model's own code, in the engine that trained it. Absent features and grids come from background dataBackground dataThe rows an explainer uses to stand in for 'absent' features or to set grids: usually a sample of the training data.: the model's training sample unless you choose These rows.

02

Which one answers you?

Predict

Predict first

Your manager asks which inputs a churn model depends on most, across all customers. Which explanation do you run first?

Permutation importanceLIMEPartial dependence
Reveal

Permutation importance. It measures model relianceModel relianceHow much a fitted model's score depends on one feature: the loss when that feature's values are scrambled.: how much the model's own score drops when one feature is shuffled. LIME explains one row, and partial dependence shows the shape of one feature's effect.

03

Read the result

Explore

On held-out Pima rows, a classification tree scores 0.708 on its own metric. Shuffling its most important feature costs 0.142, and 3 features lose more than two shuffle SDs.

Permutation importance for a saved model — learn.tree/binary_pimaRecorded · Python and R agreeRecorded 2026-11-25 · 26 values compared
R

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

Permutation importance — drop in ROC AUCWhich features does the model rely on most?
View data
FeatureHighImportanceLow
glu0.17640.14190.1074
age0.07130.05430.0374
bp0.02760.01480.0020
ped0.03750.0143−0.0089
skin0.00880.00690.0051
npreg000
bmi0.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)

FeatureImportanceSD
glu0.14190.0345
age0.05430.0169
bp0.01480.0128
ped0.01430.0232
skin0.00690.0018
npreg00
bmi−0.01030.0217
The exact R script · R 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")
))
Python

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)

FeatureImportanceSD
glu0.14190.0345
age0.05430.0169
bp0.01480.0128
ped0.01430.0232
skin0.00690.0018
npreg00
bmi−0.01030.0217
The exact Python script · Python 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 tree is the example's own model, not one of yours: Run live trains it in the Academy sandbox, once per engine, and then explains it.

Look at the SD column next to each importance. Which features would you still call important if you reran with another seed?

04

When features move together

Reflect

Every card has a row Features vary independently. It reports the largest correlation between two numeric features in the background: 0.69 here.

Shuffling one of two correlated features builds rows the model never saw, which is extrapolationExtrapolation (explanations)Asking a model about feature combinations it never saw, as shuffling or fixing a correlated feature does; answers are guesses, not patterns.. When the row warns, the remedy is Accumulated local effects, which compare predictions only within narrow bins of real data. Which pair of features in your own data would trip this row?

05

Is the average enough?

Predict

Predict first

A partial dependence curve is flat, but the single-row ICE lines cross: half rise, half fall. What does that suggest?

The feature has no effectThe effect depends on other featuresThe model is broken
Reveal

The effect depends on other features. The rising and falling rows cancel in the average. The card's One average describes the rows row measures this spread and warns when the average hides it.

06

Survival models too

Reflect

A saved survival model is explained the same way, on its risk score: higher means the event is expected sooner. Permutation importance needs each row's time and event, and scores the shuffles by the C-indexConcordance indexThe chance a survival model ranks two people correctly by who has the event first; 0.5 is guessing, 1 is perfect. (Uno's CUno's CConcordance weighted by the inverse chance of staying uncensored, so it does not drift with the censoring pattern. when the run used it), whatever metric the run chose.

On the veteran lung cancer data, a penalized Cox model reaches a C-index of 0.713 on its held-out rows, and shuffling karno costs the most.

Permutation importance for a saved model — learn.coxnet/veteran_elasticRecorded · Python and R agreeRecorded 2026-11-25 · 22 values compared
R

On 27 rows the model's C-index is 0.713 (higher is better); shuffling karno costs the most (0.27).

C-index on these rows
0.7125
Drop when karno is shuffled
0.2701

Plots

Permutation importance — drop in C-indexWhich features does the model rely on most?
View data
FeatureHighImportanceLow
karno0.37430.27010.1659
celltype0.06590.0255−0.0149
trt0.02840.0020−0.0243
prior000
age−0.0065−0.0163−0.0261

Assumptions

  • Rows have the target — 27 of 27 rows have the target.
  • Enough rows — 27 scored rows; drops this small are mostly noise.
  • Features vary independently — karno and age: |ρ| = 0.15.
  • Rows resemble the training data — 7.4% of the explained rows fall outside the background's range; those explanations extrapolate.

Permutation importance (drop in C-index)

FeatureImportanceSD
karno0.27010.1042
celltype0.02550.0404
trt0.00200.0264
prior00
age−0.01630.0098
The exact R script · R 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 fe0178483ec8351d
# Explains the saved model learn.coxnet/veteran_elastic with its own learner code (learn.coxnet 1.0.0, driver mode "explain").
# Penalized Cox regression
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method learn.coxnet 1.0.0 · spec 4754ff5f84f86a2c
# Dataset: veteran (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 <- "time"
FEATURES <- c("karno", "age", "celltype", "trt", "prior")
TASK <- "survival"
CLASSES <- c()
POSITIVE <- NULL
METRIC <- "c_index"
SEED <- 42
PARAMS <- list(
  penalty = 0.02,
  mixture = 0.5,
  tol = 1e-10,
  max_iter = 100000
)

df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/veteran.parquet", col_select = unique(c(TARGET, FEATURES, "status"))))
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(
    karno = "numeric",
    age = "numeric",
    celltype = "categorical",
    trt = "categorical",
    prior = "boolean"
  ),
  levels = list(
    celltype = c("squamous", "smallcell", "adeno", "large"),
    trt = c("standard", "test")
  ),
  impute = "median",
  scale = "standard",
  indicators = FALSE
)
target <- cs_ml_encode_target(df[[TARGET]], TASK, CLASSES, POSITIVE)
y <- target$fit
y_index <- target$index
# Signed time: +time for events, -time for censored rows.
y <- cs_ml_surv_signed(y, cs_ml_surv_event(df[["status"]], "numeric", NULL))
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
# Penalized Cox: -(1/n) partial log-likelihood (Breslow ties) + lambda [rho |b|_1 + (1 - rho)/2 |b|^2], fitted by
# the same coordinate descent in Python and R (cs_ml_coxnet_fit <-> codesplash.ml.survival.coxnet_fit).
fit_model <- function(X, y, w) cs_ml_coxnet_fit(X, y, PARAMS$penalty, PARAMS$mixture, PARAMS$tol, as.integer(PARAMS$max_iter))

# The linear predictor (risk score).
predict_model <- function(model, X) as.numeric(unname(X) %*% model)

# The Breslow baseline, from the training rows' risk scores.
survival_base <- function(model, X, y) cs_ml_surv_breslow(y, predict_model(model, X))
predict_survival <- function(model, base, X, times) cs_ml_surv_breslow_curves(base, predict_model(model, X), times)

feature_importance <- function(model, names) cs_ml_coef_importance(names, model)

save_model <- function(model, directory) {
  path <- file.path(directory, "model.rds")
  saveRDS(model, path)
  list(list(key = "model", path = path, format = "rds"))
}

load_model <- function(directory) readRDS(file.path(directory, "model.rds"))

# Risk scores and survival curves for `rows`, from a model fit on `fit_rows`.
held_out <- function(model, prep, fit_rows, rows) {
  base <- survival_base(model, cs_ml_design_apply(prep, rows_of(fit_rows)), y[fit_rows + 1L])
  X <- cs_ml_design_apply(prep, rows_of(rows))
  list(risk = predict_model(model, X), surv = predict_survival(model, base, X, SURV_TIMES))
}

# %% Explain the model
REQUEST <- jsonlite::fromJSON("{\"analyze\":{\"kind\":\"permutation\",\"method\":\"explain.permutation\",\"model\":\"learn.coxnet/veteran_elastic\",\"title\":\"Permutation importance for a saved model\",\"version\":\"1.1.1\"},\"maxRows\":1000,\"methods\":[\"permutation\"],\"modelDir\":\"model-r/out\",\"repeats\":3,\"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()) {
  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 = "Penalized Cox regression",
  engine = cs_engine_info("nanoparquet")
))
Python

On 27 rows the model's C-index is 0.713 (higher is better); shuffling karno costs the most (0.27).

C-index on these rows
0.7125
Drop when karno is shuffled
0.2701

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

Assumptions

  • Rows have the target — 27 of 27 rows have the target.
  • Enough rows — 27 scored rows; drops this small are mostly noise.
  • Features vary independently — karno and age: |ρ| = 0.15.
  • Rows resemble the training data — 7.4% of the explained rows fall outside the background's range; those explanations extrapolate.

Permutation importance (drop in C-index)

FeatureImportanceSD
karno0.27010.1042
celltype0.02550.0404
trt0.00200.0264
prior00
age−0.01630.0098
The exact Python script · Python 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 fe0178483ec8351d
# Explains the saved model learn.coxnet/veteran_elastic with its own learner code (learn.coxnet 1.0.0, driver mode "explain").
# Penalized Cox regression
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method learn.coxnet 1.0.0 · spec 4754ff5f84f86a2c
# Dataset: veteran (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 survival as cssurv
from codesplash.ml import linear as cslin

# %% Data and split plan
TARGET = "time"
FEATURES = ["karno", "age", "celltype", "trt", "prior"]
TASK = "survival"
CLASSES = []
POSITIVE = None
METRIC = "c_index"
SEED = 42
PARAMS = {
    "penalty": 0.02,
    "mixture": 0.5,
    "tol": 1e-10,
    "max_iter": 100000,
}

df = pd.read_parquet("tests/parity/fixtures/veteran.parquet", columns=list(dict.fromkeys([TARGET] + FEATURES + ["status"])))
plan = csml.read_plan("model-python/folds.parquet")  # host-written folds: identical in Python and R
design = csml.Design.for_frame(
    df,
    FEATURES,
    kinds={
        "karno": "numeric",
        "age": "numeric",
        "celltype": "categorical",
        "trt": "categorical",
        "prior": "boolean",
    },
    levels={
        "celltype": ["squamous", "smallcell", "adeno", "large"],
        "trt": ["standard", "test"],
    },
    impute="median",
    scale="standard",
    indicators=False,
)
y, y_index = csml.encode_target(df[TARGET], TASK, CLASSES, POSITIVE)
# Signed time: +time for events, −time for censored rows.
y = cssurv.signed_time(y, cssurv.event_indicator(df["status"], "numeric", None))
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
# Penalized Cox: −(1/n)·partial log-likelihood (Breslow ties) + λ·[ρ‖β‖₁ + (1 − ρ)/2·‖β‖²], fitted by the
# same coordinate descent in Python and R (codesplash.ml.survival.coxnet_fit ↔ cs_ml_coxnet_fit).
def fit_model(X, y, w):
    return cssurv.coxnet_fit(X, y, PARAMS["penalty"], PARAMS["mixture"], PARAMS["tol"], int(PARAMS["max_iter"]))


def predict_model(model, X):
    """The linear predictor (risk score)."""
    return np.asarray(X, dtype=np.float64) @ model


def survival_base(model, X, y):
    """The Breslow baseline, from the training rows' risk scores."""
    return cssurv.breslow_fit(y, predict_model(model, X))


def predict_survival(model, base, X, times):
    return cssurv.breslow_survival(base, predict_model(model, X), times)


def feature_importance(model, names):
    return cslin.coef_importance(names, model)


def save_model(model, directory):
    import joblib

    path = os.path.join(directory, "model.joblib")
    joblib.dump(model, path)
    return [{"key": "model", "path": path, "format": "joblib"}]


def load_model(directory):
    import joblib

    return joblib.load(os.path.join(directory, "model.joblib"))


def held_out(model, prep, fit_rows, rows):
    """Risk scores and survival curves for `rows`, from a model fit on `fit_rows`."""
    base = survival_base(model, prep.transform(df.iloc[fit_rows]), y[fit_rows])
    X = prep.transform(df.iloc[rows])
    return predict_model(model, X), predict_survival(model, base, X, SURV_TIMES)


# %% Explain the model
import json

from codesplash.ml import explain as csx

REQUEST = json.loads("{\"analyze\":{\"kind\":\"permutation\",\"method\":\"explain.permutation\",\"model\":\"learn.coxnet/veteran_elastic\",\"title\":\"Permutation importance for a saved model\",\"version\":\"1.1.1\"},\"maxRows\":1000,\"methods\":[\"permutation\"],\"modelDir\":\"model-python/out\",\"repeats\":3,\"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="Penalized Cox regression",
        engine=cs.engine_info("numpy", "pandas"),
    )
)

A row the model ranks riskiest can still outlive the others. What does the C-index measure instead?

07

Categories as vectors

Read

An entity embeddingEntity embeddingA learned vector for each level of a categorical variable, shaped while a network predicts the target; similar levels end up close. gives every level of a categorical variable a short vector, learned while a small network predicts the target. Levels that act alike end up close together.

Category embedding mapWhich levels of a categorical variable does the model treat as alike?
View data
PC 1PC 2levelfeaturerows
−0.85200.2910Monweekday1,436
−0.68400.0770Tueweekday1,499
−0.6460−0.0950Wedweekday1,301
−0.5400−0.1380Thuweekday1,520
−0.2430−0.4700Friweekday1,517
1.3660.1560Satweekday1,424
1.2810.4470Sunweekday1,493
0.5590−0.5520urbanstore type4,200
0.1730−0.7490suburbanstore type3,100
−0.66200.6650ruralstore type1,600
0.90100.8360outletstore type900

On the Titanic data, a network learns 8 level vectors and reaches a held-out accuracy of 0.78. Both engines start from the same weights, so Python and R draw the same map.

08

Reading the map

Predict

Predict first

On the map, first class sits far right on PC 1. What can you read from that?

Higher on PC 1 means a higher fareOnly distances and neighbors carry meaningEach axis is one category
Reveal

Only distances and neighbors. Any rotation of an embedding fits equally well, so the axes have no meaning. That first class sits far from third class is compatible with the model treating them very differently.

09

The code behind it

Read

The vectors are saved with the result as a table, so you can join them back by level and reuse them as learned featuresRepresentation learningLetting a model learn its own numeric description of the inputs (such as embeddings) instead of hand-made features..

Python
import pandas as pd

vectors = pd.read_parquet("outputs/embeddings.parquet")  # feature, level, n, d1, d2, …
cls = vectors[vectors["feature"] == "Class"].set_index("level")[["d1", "d2"]]
rows = pd.read_csv("titanic.csv").join(cls, on="Class")  # each row gets its class's vector
print(rows.head())
R
vectors <- nanoparquet::read_parquet("outputs/embeddings.parquet")
cls <- vectors[vectors$feature == "Class", c("level", "d1", "d2")]
rows <- merge(read.csv("titanic.csv"), cls, by.x = "Class", by.y = "level")
head(rows)
10

Check your understanding

Checkpoint

Check yourself

You explain a model with SHAP against These rows instead of the training sample. What changes?

Show the answer

Answer: b

SHAP splits the gap between a prediction and the background's average prediction, so a different background answers a different question.

Check yourself

A level with 4 rows sits far from all others on the embedding map. What's the safest reading?

Show the answer

Answer: b

The Enough rows per level row warns about this. Read positions only for levels with enough rows.

Check yourself

Permutation importance ranks income first. What does that show?

Show the answer

Answer: a

Importance describes one fitted model. Another equally accurate model may lean on a feature correlated with income instead.

11

Try it

In the app

Register a model from a run's Register action in Predict. Then, in Analyze, open Permutation importance for a saved model, pick the version under Model and run it in the engine the hint names. For embeddings, open the method with the Titanic data below.

12

Recap

Recap
  • The four explainers run in Analyze on any registered model version, in the engine that trained it, against the model's training sample. Survival models are explained on their risk score.
  • Read Features vary independently and Rows resemble the training data before the numbers; prefer accumulated local effects when features are correlated.
  • Entity embeddings place category levels by how they act on the target: read distances and neighbors, never axes, and ignore rare levels.

Concepts in this lesson