Concepts: testing them after training, or building them in
Ask a trained network whether it is sensitive to a human concept (TCAV), or train a network that has to predict named concepts first (a concept bottleneck). Learn what each can show, and the leaks and artifacts that fool both.
What runs in CodeSplash
- EXP007TCAV: testing with concept activation vectors Runs in CodeSplash (Experimental)
- EXP013Concept bottleneck model Runs as a notebook
- Concept test (TCAV) for a saved network Experimental
You will be able to
- Write a TCAV score from a concept direction and directional derivatives
- Explain why random concept baselines and several control sets are needed
- Describe a concept bottleneck model and a concept intervention
- Explain how soft bottlenecks leak information and what to report
Concepts instead of features
ReadFeature attributions speak in input units: pixels, columns, tokens. People think in concepts: "striped", "high blood sugar", "formal tone". Two families connect the two:
- Post hoc: take a trained network and test whether its prediction responds to a concept you define with examples. That is TCAV.
- By design: make the network predict the concepts first and the target only from them. That is a concept bottleneck model.
The first explains a model you already have; the second constrains the model you build.
TCAV
ReadTCAVTCAV (concept activation vectors)Tests whether a prediction rises along the direction that separates rows matching a concept from other rows in a hidden layer. embeds concept examples and control examples at a hidden layer , trains a linear classifier between them, and takes its normal vector as the concept activation vector . For each input of class , the directional derivative says whether moving the activation toward the concept raises the class score:
In the reference's example three directional derivatives, 2.12, −0.57 and 0.21, give a TCAV score of 0.67: two of three are positive.
Reference · EXP007 · Runs in CodeSplashTCAV: testing with concept activation vectorsSummarize how a class score changes in a learned activation-space direction associated with a user-supplied concept.Is the score real?
ReadA TCAV score of two thirds means little alone. A direction learned from random example sets also gives scores, scattered around one half. So:
- Train several concept vectors against different random control sets, and compare their scores with the scores of random-versus-random vectors.
- Report how well the linear classifier separates concept from control: a direction that barely separates them isn't a concept.
- Correct for testing many concepts and layers.
A concept classifier can also learn collection artifacts (all "striped" photos from one camera). And sensitivity isn't causation: a positive TCAV score says the prediction rises along that direction, not that the concept causes the class or is all the network represents.
TCAV in CodeSplash
ReadConcept test (TCAV) for a saved network defines a concept by a condition on a feature (such as glucose above 140) or by a set of rows, and tests it against random directions. It also puts 20 random row sets of the concept's size through the same test, and counts the network as sensitive only when the concept stands out from them too.
For glu > 140, the P(true) rises along the concept direction for 100% of the rows (random directions: 50%, Welch p = 0.0756; random row sets of the same size: 52%, control p = 0.333): no clear sensitivity to the concept.
- TCAV score, glu > 140
- 1
- Random directions
- 0.5000
- Welch p (concept vs random)
- 0.0756
- Control p (concept vs 20 random row sets)
- 0.3333
Plots
View data
| CAV | High | TCAV score | Low |
|---|---|---|---|
| Concept: glu > 140 | 1 | 1 | 1 |
| Random rows | 1.048 | 0.5000 | −0.0477 |
| Random row sets (20) | 0.8507 | 0.5250 | 0.1993 |
Assumptions
- Different from random directions — Welch p = 0.0756; the network shows no clear sensitivity to this concept.
- Stands out from random concepts — Against 20 random row sets of the same size (mean score 52%): two-sided p = 0.333; 0% of those sets pass the Welch test at 5%.
- Enough concept rows — The direction was learned from 40 concept rows.
- The layer separates the concept — Concept vs random rows are told apart with accuracy 0.92 at hidden layer 2.
- Features vary independently — skin and bmi: |ρ| = 0.69; TCAV reads the network's own layer, so related features don't distort it.
- Rows resemble the training data — 0.0% of the explained rows fall outside the background's range.
TCAV runs (concept glu > 140, hidden layer 2)
| Run | Concept CAV score | Random CAV score |
|---|---|---|
| 1 | 1 | 1 |
| 2 | 1 | 0 |
| 3 | 1 | 0 |
| 4 | 1 | 1 |
| 5 | 1 | 0 |
| 6 | 1 | 1 |
- TCAV: 100% of the explained rows' P(true) rises along the direction that separates glu > 140 rows from other training rows at hidden layer 2 (random directions: 50%; Welch p = 0.0756). A concept the network does not represent gives scores near the random ones.
The exact R script · R R version 4.5.1 (2025-06-13)
# Concept test (TCAV) for a saved network
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method explain.tcav 1.2.0 · spec 7bfee1c3e882e648
# 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\":\"tcav\",\"method\":\"explain.tcav\",\"model\":\"learn.torch_mlp/binary_pima\",\"title\":\"Concept test (TCAV) for a saved network\",\"version\":\"1.2.0\"},\"gradRows\":60,\"maxRows\":60,\"methods\":[\"tcav\"],\"modelDir\":\"model-r/out\",\"rows\":\"auto\",\"tcavControls\":20,\"tcavFeature\":\"glu\",\"tcavLayer\":2,\"tcavOp\":\"gt\",\"tcavRows\":40,\"tcavRuns\":6,\"tcavSource\":\"filter\",\"tcavValue\":\"140\"}", 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")
))
For glu > 140, the P(true) rises along the concept direction for 100% of the rows (random directions: 50%, Welch p = 0.0756; random row sets of the same size: 52%, control p = 0.333): no clear sensitivity to the concept.
- TCAV score, glu > 140
- 1
- Random directions
- 0.5000
- Welch p (concept vs random)
- 0.0756
- Control p (concept vs 20 random row sets)
- 0.3333
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Different from random directions — Welch p = 0.0756; the network shows no clear sensitivity to this concept.
- Stands out from random concepts — Against 20 random row sets of the same size (mean score 52%): two-sided p = 0.333; 0% of those sets pass the Welch test at 5%.
- Enough concept rows — The direction was learned from 40 concept rows.
- The layer separates the concept — Concept vs random rows are told apart with accuracy 0.92 at hidden layer 2.
- Features vary independently — skin and bmi: |ρ| = 0.69; TCAV reads the network's own layer, so related features don't distort it.
- Rows resemble the training data — 0.0% of the explained rows fall outside the background's range.
TCAV runs (concept glu > 140, hidden layer 2)
| Run | Concept CAV score | Random CAV score |
|---|---|---|
| 1 | 1 | 1 |
| 2 | 1 | 0 |
| 3 | 1 | 0 |
| 4 | 1 | 1 |
| 5 | 1 | 0 |
| 6 | 1 | 1 |
- TCAV: 100% of the explained rows' P(true) rises along the direction that separates glu > 140 rows from other training rows at hidden layer 2 (random directions: 50%; Welch p = 0.0756). A concept the network does not represent gives scores near the random ones.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Concept test (TCAV) for a saved network
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method explain.tcav 1.2.0 · spec 7bfee1c3e882e648
# 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\":\"tcav\",\"method\":\"explain.tcav\",\"model\":\"learn.torch_mlp/binary_pima\",\"title\":\"Concept test (TCAV) for a saved network\",\"version\":\"1.2.0\"},\"gradRows\":60,\"maxRows\":60,\"methods\":[\"tcav\"],\"modelDir\":\"model-python/out\",\"rows\":\"auto\",\"tcavControls\":20,\"tcavFeature\":\"glu\",\"tcavLayer\":2,\"tcavOp\":\"gt\",\"tcavRows\":40,\"tcavRuns\":6,\"tcavSource\":\"filter\",\"tcavValue\":\"140\"}") 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"),
)
)
When the concept rows are only held-out rows of the same data, there is no real concept, and the test should find nothing; that run is the method's built-in negative control.
For this dataset's rows, the P(true) rises along the concept direction for 0% of the rows (random directions: 37%, Welch p = 0.127; random row sets of the same size: 36%, control p = 0.19): no clear sensitivity to the concept.
- TCAV score, this dataset's rows
- 0
- Random directions
- 0.3694
- Welch p (concept vs random)
- 0.1274
- Control p (concept vs 20 random row sets)
- 0.1905
Plots
View data
| CAV | High | TCAV score | Low |
|---|---|---|---|
| Concept: this dataset's rows | 0 | 0 | 0 |
| Random rows | 0.8650 | 0.3694 | −0.1261 |
| Random row sets (20) | 0.6137 | 0.3619 | 0.1102 |
Assumptions
- Different from random directions — Welch p = 0.127; the network shows no clear sensitivity to this concept.
- Stands out from random concepts — Against 20 random row sets of the same size (mean score 36%): two-sided p = 0.19; 5% of those sets pass the Welch test at 5%.
- Enough concept rows — The direction was learned from 60 concept rows.
- The layer separates the concept — Concept vs random rows are told apart with accuracy 0.67 at hidden layer 1.
- Features vary independently — skin and bmi: |ρ| = 0.69; TCAV reads the network's own layer, so related features don't distort it.
- Rows resemble the training data — 0.0% of the explained rows fall outside the background's range.
TCAV runs (concept this dataset's rows, hidden layer 1)
| Run | Concept CAV score | Random CAV score |
|---|---|---|
| 1 | 0 | 1 |
| 2 | 0 | 0 |
| 3 | 0 | 0 |
| 4 | 0 | 0 |
| 5 | 0 | 0.2167 |
| 6 | 0 | 1 |
- TCAV: 0% of the explained rows' P(true) rises along the direction that separates this dataset's rows rows from other training rows at hidden layer 1 (random directions: 37%; Welch p = 0.127). A concept the network does not represent gives scores near the random ones.
The exact R script · R R version 4.5.1 (2025-06-13)
# Concept test (TCAV) for a saved network
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method explain.tcav 1.2.0 · spec 3e66225d2e03f1ea
# 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\":\"tcav\",\"method\":\"explain.tcav\",\"model\":\"learn.torch_mlp/binary_pima\",\"title\":\"Concept test (TCAV) for a saved network\",\"version\":\"1.2.0\"},\"gradRows\":60,\"maxRows\":60,\"methods\":[\"tcav\"],\"modelDir\":\"model-r/out\",\"rows\":\"auto\",\"tcavControls\":20,\"tcavLayer\":1,\"tcavOp\":\"auto\",\"tcavRows\":60,\"tcavRuns\":6,\"tcavSource\":\"rows\"}", 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")
))
For this dataset's rows, the P(true) rises along the concept direction for 0% of the rows (random directions: 37%, Welch p = 0.127; random row sets of the same size: 36%, control p = 0.19): no clear sensitivity to the concept.
- TCAV score, this dataset's rows
- 0
- Random directions
- 0.3694
- Welch p (concept vs random)
- 0.1274
- Control p (concept vs 20 random row sets)
- 0.1905
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Different from random directions — Welch p = 0.127; the network shows no clear sensitivity to this concept.
- Stands out from random concepts — Against 20 random row sets of the same size (mean score 36%): two-sided p = 0.19; 5% of those sets pass the Welch test at 5%.
- Enough concept rows — The direction was learned from 60 concept rows.
- The layer separates the concept — Concept vs random rows are told apart with accuracy 0.67 at hidden layer 1.
- Features vary independently — skin and bmi: |ρ| = 0.69; TCAV reads the network's own layer, so related features don't distort it.
- Rows resemble the training data — 0.0% of the explained rows fall outside the background's range.
TCAV runs (concept this dataset's rows, hidden layer 1)
| Run | Concept CAV score | Random CAV score |
|---|---|---|
| 1 | 0 | 1 |
| 2 | 0 | 0 |
| 3 | 0 | 0 |
| 4 | 0 | 0 |
| 5 | 0 | 0.2167 |
| 6 | 0 | 1 |
- TCAV: 0% of the explained rows' P(true) rises along the direction that separates this dataset's rows rows from other training rows at hidden layer 1 (random directions: 37%; Welch p = 0.127). A concept the network does not represent gives scores near the random ones.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Concept test (TCAV) for a saved network
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method explain.tcav 1.2.0 · spec 3e66225d2e03f1ea
# 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\":\"tcav\",\"method\":\"explain.tcav\",\"model\":\"learn.torch_mlp/binary_pima\",\"title\":\"Concept test (TCAV) for a saved network\",\"version\":\"1.2.0\"},\"gradRows\":60,\"maxRows\":60,\"methods\":[\"tcav\"],\"modelDir\":\"model-python/out\",\"rows\":\"auto\",\"tcavControls\":20,\"tcavLayer\":1,\"tcavOp\":\"auto\",\"tcavRows\":60,\"tcavRuns\":6,\"tcavSource\":\"rows\"}") 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"),
)
)
Concept bottleneck models
ReadA concept bottleneck modelConcept bottleneck modelA network that first predicts named concepts, then predicts the target from those concepts alone, so you can inspect and edit them. has two parts: predicts concept values (trained on concept labels), and predicts the target from alone:
Because every prediction passes through named concepts, an expert can intervene: correct a wrong concept and watch the prediction change. In the reference's example, setting one concept from its predicted value to 1 moves the output probability from 0.40 to 0.77.
Reference · EXP013 · Runs as a notebookConcept bottleneck modelPredict explicit concepts before predicting the final task target, enabling controlled edits to intermediate concept values inside the model.Predict: the leaky bottleneck
PredictPredict first
A jointly trained bottleneck model passes concept probabilities (not 0/1 values) to its task head, and it predicts the target better than its concepts should allow. Could it be using information beyond the concepts?
Reveal
Yes. Soft scores can encode task information in their exact values, a leak the concept labels never described. Then interventions on concepts behave oddly and the "explanation" overstates how much the named concepts decide. Report per-concept accuracy, intervention curves, and compare hard with soft bottlenecks.
Where they stand in CodeSplash
Read| Entry | In CodeSplash |
|---|---|
| TCAV (EXP007) | Runs in CodeSplash: Concept test (TCAV) for a saved network in Analyze and the Explain tab, for dense torch networks, with a condition or a row set as the concept; image concept sets wait for image collections |
| Concept bottleneck model (EXP013) | Runs as a notebook: the reference's program (a concept intervention on a small head) is verified in Python and R; there's no bottleneck learner |
Check your understanding
CheckpointCheck yourself
What does a TCAV score measure?
Show the answer
Answer: b
It is a directional-sensitivity summary at one layer. Its meaning depends on the concept examples, the controls and the layer.
Check yourself
Why compare a concept's TCAV scores with scores from random-versus-random directions?
Show the answer
Answer: b
Several control sets give a distribution under "no concept". Without it, a score of 0.7 can't be told from chance.
Check yourself
What can you do with a concept bottleneck model that you can't do with a standard network?
Show the answer
Answer: b
Interventions are the payoff. They are edits inside the model, not interventions on the real world.
Check yourself
A bottleneck model has high task accuracy but poor accuracy on several concepts. What does that suggest?
Show the answer
Answer: b
Report per-concept performance beside task accuracy. Strong task prediction can coexist with weak concept fidelity.
Recap
Recap- TCAV: a concept direction at a hidden layer and the share of inputs whose score rises along it.
- Compare with random directions, check concept separability, correct for many tests; sensitivity isn't causation.
- Concept bottlenecks predict named concepts first, so experts can intervene.
- Soft bottlenecks leak; report per-concept accuracy and intervention curves.
Concepts in this lesson