TabNet: a network that picks columns step by step
TabNet reads a table row in a few decision steps, each through a sparse mask over the columns. Compute a sparsemax mask and the reuse prior by hand, read TabNet's masks on penguins, and see why masks aren't causes.
What runs in CodeSplash
- SPE001TabNet Runs in CodeSplash (Experimental)
- TabNet (attentive feature selection) Experimental
You will be able to
- Compute a sparsemax mask and say why it puts exact zeros on some columns
- Explain how the prior scale γ limits reusing a column across steps
- Read TabNet's average masks and mask density from a run
- Say why a mask shows what the network read, not what causes the outcome
Why a table needs its own network
ReadImages have neighboring pixels and text has word order. A table has neither: its columns mix units, scales and categories, and their order means nothing. Plain multilayer networks often lose to boosted trees on tables for that reason.
TabNetTabNetA network that reads a row in a few steps, each choosing a sparse mask over the columns; the masks show what it used. borrows one habit from trees: look at a few columns at a time. It reads each row in a small number of decision steps. At every step an attentive transformerAttentive transformerTabNet's step that scores the columns, scales them by a prior of what is still unused, and picks a sparse mask. chooses a sparse mask over the columns, a feature transformer processes the masked row, and each step adds its part to the prediction.
Reference · SPE001 · Runs in CodeSplashTabNetTabNet learns sequential, example-dependent feature selection for tabular prediction. It combines a neural predictor with sparse feature masks, allowing inspection of which columns contribute at each decision step;Sparsemax puts real zeros
ReadSoftmax turns scores into weights that are all above zero. SparsemaxSparsemaxLike softmax, turns scores into weights that sum to 1, but sets small scores to exactly zero. projects the scores onto the probability simplex instead, so low scores get exactly zero and the rest still sum to 1:
In the reference's example, four columns score . Sparsemax gives the first two 0.7 and 0.3, and the last two exactly 0. Softmax would have given every column some weight.
The prior limits reuse
ReadAfter each step TabNet updates a prior scale for every column, . A column used heavily now gets a smaller prior, so the next step is less likely to pick it again.
With , the example's prior becomes 0.6, 1.0, 1.3 and 1.3. The two unused columns now lead. A larger lets a column be reused; forbids reusing a fully used column.
import numpy as np
def sparsemax(z):
zs = np.sort(z)[::-1]; cs = np.cumsum(zs); k = np.arange(1, len(z) + 1)
kk = k[1 + k * zs > cs][-1]; tau = (cs[kk - 1] - 1) / kk
return np.maximum(z - tau, 0)
mask = sparsemax(np.array([1.2, .8, -.5, .1]))
print(mask, np.ones(4) * (1.3 - mask)) # mask, next priorsparsemax <- function(z) {
zs <- sort(z, decreasing = TRUE); cs <- cumsum(zs); k <- seq_along(z)
kk <- max(k[1 + k * zs > cs]); tau <- (cs[kk] - 1) / kk
pmax(z - tau, 0)
}
mask <- sparsemax(c(1.2, .8, -.5, .1))
print(list(mask = mask, prior = rep(1, 4) * (1.3 - mask)))TabNet's masks on penguins
ExploreTabNet (attentive feature selection): cross-validated log loss 0.116 ± 0.084 over 3 folds; log loss on the locked test set 0.125 (n = 69).
- CV log loss
- 0.1163
- SD across folds
- 0.0836
- Test log loss
- 0.1253
Plots
View data
| Column | Share of mask weight |
|---|---|
| flipper_len | 0.2647 |
| island=Dream | 0.1429 |
| bill_len | 0.1362 |
| bill_dep | 0.1317 |
| body_mass | 0.0946 |
| island=Torgersen | 0.0915 |
| island=Biscoe | 0.0826 |
| sex=female | 0.0558 |
| sex=male | 0 |
View data
| Network | Epoch | Training loss |
|---|---|---|
| TabNet | 1 | 1.423 |
| TabNet | 2 | 1.252 |
| TabNet | 3 | 1.066 |
| TabNet | 4 | 0.9852 |
| TabNet | 5 | 0.9233 |
| TabNet | 6 | 0.8673 |
| TabNet | 7 | 0.8154 |
| TabNet | 8 | 0.7620 |
| TabNet | 9 | 0.7151 |
| TabNet | 10 | 0.6601 |
| TabNet | 11 | 0.5914 |
| TabNet | 12 | 0.5198 |
| TabNet | 13 | 0.4622 |
| TabNet | 14 | 0.4026 |
| TabNet | 15 | 0.3743 |
| TabNet | 16 | 0.3096 |
| TabNet | 17 | 0.3092 |
| TabNet | 18 | 0.2256 |
| TabNet | 19 | 0.2703 |
| TabNet | 20 | 0.1870 |
| TabNet | 21 | 0.1713 |
| TabNet | 22 | 0.1319 |
| TabNet | 23 | 0.1277 |
| TabNet | 24 | 0.1128 |
| TabNet | 25 | 0.0927 |
| TabNet | 26 | 0.0930 |
| TabNet | 27 | 0.0699 |
| TabNet | 28 | 0.1188 |
| TabNet | 29 | 0.0629 |
| TabNet | 30 | 0.0935 |
| TabNet | 31 | 0.1022 |
| TabNet | 32 | 0.0513 |
| TabNet | 33 | 0.0472 |
| TabNet | 34 | 0.1016 |
| TabNet | 35 | 0.0379 |
| TabNet | 36 | 0.1005 |
| TabNet | 37 | 0.0690 |
| TabNet | 38 | 0.0883 |
| TabNet | 39 | 0.0644 |
| TabNet | 40 | 0.0458 |
Cross-validation
| Fold | Repeat | n | log loss | accuracy | balanced accuracy | F1 |
|---|---|---|---|---|---|---|
| 1 | 1 | 92 | 0.1435 | 0.9674 | 0.9736 | 0.9650 |
| 2 | 1 | 92 | 0.0226 | 1 | 1 | 1 |
| 3 | 1 | 91 | 0.1829 | 0.9560 | 0.9649 | 0.9486 |
Attention masks by step
| Column | Share of mask weight | Step 1 mean mask | Step 2 mean mask | Step 3 mean mask |
|---|---|---|---|---|
| flipper_len | 0.2647 | 0.1683 | 0.3610 | 0.1162 |
| island=Dream | 0.1429 | 0.0003 | 0.0221 | 0.3287 |
| bill_len | 0.1362 | 0.1267 | 0.1228 | 0.2033 |
| bill_dep | 0.1317 | 0.0957 | 0.1322 | 0.1405 |
| body_mass | 0.0946 | 0.2271 | 0.0808 | 0.0525 |
| island=Torgersen | 0.0915 | 0.1133 | 0.1456 | 0.0920 |
| island=Biscoe | 0.0826 | 0.1409 | 0.1114 | 0.0669 |
| sex=female | 0.0558 | 0.1276 | 0.0241 | 0 |
| sex=male | 0 | 0 | 0 | 0 |
Training curves
| Network | Epoch | Training loss | Validation loss |
|---|---|---|---|
| TabNet | 1 | 1.423 | — |
| TabNet | 2 | 1.252 | — |
| TabNet | 3 | 1.066 | — |
| TabNet | 4 | 0.9852 | — |
| TabNet | 5 | 0.9233 | — |
| TabNet | 6 | 0.8673 | — |
| TabNet | 7 | 0.8154 | — |
| TabNet | 8 | 0.7620 | — |
| TabNet | 9 | 0.7151 | — |
| TabNet | 10 | 0.6601 | — |
| TabNet | 11 | 0.5914 | — |
| TabNet | 12 | 0.5198 | — |
| TabNet | 13 | 0.4622 | — |
| TabNet | 14 | 0.4026 | — |
| TabNet | 15 | 0.3743 | — |
| TabNet | 16 | 0.3096 | — |
| TabNet | 17 | 0.3092 | — |
| TabNet | 18 | 0.2256 | — |
| TabNet | 19 | 0.2703 | — |
| TabNet | 20 | 0.1870 | — |
| TabNet | 21 | 0.1713 | — |
| TabNet | 22 | 0.1319 | — |
| TabNet | 23 | 0.1277 | — |
| TabNet | 24 | 0.1128 | — |
| TabNet | 25 | 0.0927 | — |
| TabNet | 26 | 0.0930 | — |
| TabNet | 27 | 0.0699 | — |
| TabNet | 28 | 0.1188 | — |
| TabNet | 29 | 0.0629 | — |
| TabNet | 30 | 0.0935 | — |
| TabNet | 31 | 0.1022 | — |
| TabNet | 32 | 0.0513 | — |
| TabNet | 33 | 0.0472 | — |
| TabNet | 34 | 0.1016 | — |
| TabNet | 35 | 0.0379 | — |
| TabNet | 36 | 0.1005 | — |
| TabNet | 37 | 0.0690 | — |
| TabNet | 38 | 0.0883 | — |
| TabNet | 39 | 0.0644 | — |
| TabNet | 40 | 0.0458 | — |
The exact R script · R R version 4.5.1 (2025-06-13)
# TabNet (attentive feature selection)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method learn.tabnet 1.0.6 · spec 75cefba923f23490
# Dataset: ml_penguins (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 is built by codesplashr's cs_deep_fit_tabnet twin.
# %% Data and split plan
TARGET <- "species"
FEATURES <- c("island", "bill_len", "bill_dep", "flipper_len", "body_mass", "sex")
TASK <- "multiclass"
CLASSES <- c("Adelie", "Chinstrap", "Gentoo")
POSITIVE <- NULL
METRIC <- "log_loss"
SEED <- 42
PARAMS <- list(
n_d = 4,
n_a = 4,
n_steps = 3,
gamma = 1.3,
n_shared = 1,
n_independent = 1,
lambda_sparse = 0.001,
virtual_batch_size = 64,
epochs = 40,
learning_rate = 0.02,
batch_size = NULL,
weight_decay = 0,
early_stopping = 0,
validation_fraction = 0.1,
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_penguins.parquet", col_select = unique(c(TARGET, FEATURES))))
plan <- cs_ml_read_plan("target/academy-parity/run-8142/learn.tabnet/multiclass_penguins/folds.parquet") # host-written folds: identical in Python and R
design <- cs_ml_design(
df, FEATURES,
kinds = list(
island = "categorical",
bill_len = "numeric",
bill_dep = "numeric",
flipper_len = "numeric",
body_mass = "numeric",
sex = "categorical"
),
levels = list(
island = c("Biscoe", "Dream", "Torgersen"),
sex = c("female", "male")
),
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("target/academy-parity/run-8142/learn.tabnet/multiclass_penguins/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]
RESAMPLE <- "none"
if (RESAMPLE != "none" && TASK == "regression") {
warnings <- c(warnings, list("Resampling applies to classification only — ignored for this regression target."))
}
resampled <- NULL # the final model's resampling summary
notes <- list()
# A fit's design matrix, targets and weights: training rows only, resampled when asked
# (cs_ml_resample — the same rows in Python, from the shared random stream).
training_set <- function(X, rows, fold_id, repeat_) {
yy <- y[rows + 1L]
ww <- sample_weights(rows)
if (RESAMPLE == "none" || TASK == "regression") return(list(X = X, y = yy, w = ww))
r <- cs_ml_resample(X, yy, ww, RESAMPLE, ratio = 1, k = as.integer(5),
seed = cs_ml_resample_seed(SEED, fold_id, repeat_))
if (fold_id == 0) resampled <<- r$info
r
}
fit_on <- function(s) fit_model(s$X, s$y, s$w)
# %% Model
# Training options, live progress and checkpoints (twin: codesplash.deep.trainer.configure).
cs_deep_trainer_configure(list(
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 = "target/academy-parity/run-8142/learn.tabnet/multiclass_penguins/out-r")
.deep_folds <- length(if (0 > 0) utils::head(plan$folds, 0) else plan$folds)
.deep_training_set <- training_set
# Tell the trainer which fit comes next (cross-validation fold i, or the final model), then build the
# training set as _ml_learn does.
training_set <- function(X, rows, fold_id, repeat_) {
cs_deep_trainer_set_fold(as.integer(fold_id), .deep_folds, if (fold_id > 0) "cv" else "final")
.deep_training_set(X, rows, fold_id, repeat_)
}
# TabNet on torch for R (float64, one thread): n_steps decision steps, each choosing a sparse (sparsemax)
# mask over the design columns and reading the masked row; the masks explain which columns each
# prediction used. Ghost batch norm while training, the training rows' population statistics for
# predictions. Initial weights, batches and early-stopping rows come from the shared random stream, so
# Python's torch trains the same network.
fit_model <- function(X, y, w) {
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)
}
fit <- cs_deep_fit_tabnet(
unname(X), target, w, TASK, o,
n_d = as.integer(PARAMS$n_d),
n_a = as.integer(PARAMS$n_a),
n_steps = as.integer(PARAMS$n_steps),
gamma = PARAMS$gamma,
n_shared = as.integer(PARAMS$n_shared),
n_independent = as.integer(PARAMS$n_independent),
lambda_sparse = PARAMS$lambda_sparse,
virtual_batch_size = as.integer(PARAMS$virtual_batch_size),
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
)
fit$mu <- mu
fit$sd <- sd
# Which columns the masks chose, over the training rows (population statistics).
fit$explain <- cs_deep_tabnet_explain(fit, unname(X))
fit
}
predict_model <- function(model, X) {
p <- cs_deep_tabnet_predict(model, unname(X), TASK)
if (TASK == "regression") model$mu + model$sd * p else p
}
feature_importance <- function(model, names) NULL
save_model <- function(model, directory) {
path <- file.path(directory, "model.rds")
saveRDS(model, path) # plain numeric weights, batch-norm statistics, the architecture and 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"))
# %% Cross-validation
folds <- if (0 > 0) utils::head(plan$folds, 0) else plan$folds
progress <- cs_progress("Cross-validating", total = length(folds))
for (i in seq_along(folds)) {
fold <- folds[[i]]
prep <- cs_ml_design_fit(design, rows_of(fold$train))
model <- fit_on(training_set(cs_ml_design_apply(prep, rows_of(fold$train)), fold$train, fold$id, fold$repeat_))
cs_ml_add(run, fold$id, fold$repeat_, "valid", fold$valid, y, y_index,
predict_model(model, cs_ml_design_apply(prep, rows_of(fold$valid))))
cs_progress_update(progress, i, sprintf("Fold %d of %d", i, length(folds)))
}
cs_ml_lap(run, "cv_seconds")
# %% Final model
artifacts <- list()
importance <- NULL
prep <- cs_ml_design_fit(design, rows_of(plan$train))
names_ <- cs_ml_design_names(prep)
if (TRUE) {
model <- fit_on(training_set(cs_ml_design_apply(prep, rows_of(plan$train)), plan$train, 0L, 0L))
if (!is.null(resampled)) {
warnings <- c(warnings, as.list(resampled$notes))
notes <- c(notes, list(cs_ml_resample_describe(resampled)))
}
if (length(plan$test)) {
cs_ml_add(run, 0L, 0L, "test", plan$test, y, y_index,
predict_model(model, cs_ml_design_apply(prep, rows_of(plan$test))))
}
importance <- feature_importance(model, names_)
artifacts[[length(artifacts) + 1L]] <- list(
key = "design", path = cs_ml_save_json(cs_ml_design_json(prep), file.path(out, "design.json")), format = "json"
)
artifacts <- c(artifacts, save_model(model, out))
cs_ml_lap(run, "final_seconds")
}
artifacts[[length(artifacts) + 1L]] <- list(key = "predictions", path = cs_ml_write(run, out), format = "parquet")
cs_progress_done(progress)
# %% Result
cs_publish(cs_deep_extend_tabnet(cs_ml_result(
run,
title = "TabNet (attentive feature selection)",
engine = cs_engine_info("torch", "codesplashr", "nanoparquet"),
n_features = length(names_),
n_train = length(plan$train),
n_test = length(plan$test),
params = PARAMS,
features = names_,
importance = importance,
artifacts = artifacts,
warnings = warnings,
notes = notes
), model, names_))
TabNet (attentive feature selection): cross-validated log loss 0.116 ± 0.084 over 3 folds; log loss on the locked test set 0.125 (n = 69).
- CV log loss
- 0.1163
- SD across folds
- 0.0836
- Test log loss
- 0.1253
To keep this page light, the plots are shown once, under the R tab.
Cross-validation
| Fold | Repeat | n | log loss | accuracy | balanced accuracy | F1 |
|---|---|---|---|---|---|---|
| 1 | 1 | 92 | 0.1435 | 0.9674 | 0.9736 | 0.9650 |
| 2 | 1 | 92 | 0.0226 | 1 | 1 | 1 |
| 3 | 1 | 91 | 0.1829 | 0.9560 | 0.9649 | 0.9486 |
Attention masks by step
| Column | Share of mask weight | Step 1 mean mask | Step 2 mean mask | Step 3 mean mask |
|---|---|---|---|---|
| flipper_len | 0.2647 | 0.1683 | 0.3610 | 0.1162 |
| island=Dream | 0.1429 | 0.0003 | 0.0221 | 0.3287 |
| bill_len | 0.1362 | 0.1267 | 0.1228 | 0.2033 |
| bill_dep | 0.1317 | 0.0957 | 0.1322 | 0.1405 |
| body_mass | 0.0946 | 0.2271 | 0.0808 | 0.0525 |
| island=Torgersen | 0.0915 | 0.1133 | 0.1456 | 0.0920 |
| island=Biscoe | 0.0826 | 0.1409 | 0.1114 | 0.0669 |
| sex=female | 0.0558 | 0.1276 | 0.0241 | 0 |
| sex=male | 0 | 0 | 0 | 0 |
Training curves
| Network | Epoch | Training loss | Validation loss |
|---|---|---|---|
| TabNet | 1 | 1.423 | — |
| TabNet | 2 | 1.252 | — |
| TabNet | 3 | 1.066 | — |
| TabNet | 4 | 0.9852 | — |
| TabNet | 5 | 0.9233 | — |
| TabNet | 6 | 0.8673 | — |
| TabNet | 7 | 0.8154 | — |
| TabNet | 8 | 0.7620 | — |
| TabNet | 9 | 0.7151 | — |
| TabNet | 10 | 0.6601 | — |
| TabNet | 11 | 0.5914 | — |
| TabNet | 12 | 0.5198 | — |
| TabNet | 13 | 0.4622 | — |
| TabNet | 14 | 0.4026 | — |
| TabNet | 15 | 0.3743 | — |
| TabNet | 16 | 0.3096 | — |
| TabNet | 17 | 0.3092 | — |
| TabNet | 18 | 0.2256 | — |
| TabNet | 19 | 0.2703 | — |
| TabNet | 20 | 0.1870 | — |
| TabNet | 21 | 0.1713 | — |
| TabNet | 22 | 0.1319 | — |
| TabNet | 23 | 0.1277 | — |
| TabNet | 24 | 0.1128 | — |
| TabNet | 25 | 0.0927 | — |
| TabNet | 26 | 0.0930 | — |
| TabNet | 27 | 0.0699 | — |
| TabNet | 28 | 0.1188 | — |
| TabNet | 29 | 0.0629 | — |
| TabNet | 30 | 0.0935 | — |
| TabNet | 31 | 0.1022 | — |
| TabNet | 32 | 0.0513 | — |
| TabNet | 33 | 0.0472 | — |
| TabNet | 34 | 0.1016 | — |
| TabNet | 35 | 0.0379 | — |
| TabNet | 36 | 0.1005 | — |
| TabNet | 37 | 0.0690 | — |
| TabNet | 38 | 0.0883 | — |
| TabNet | 39 | 0.0644 | — |
| TabNet | 40 | 0.0458 | — |
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# TabNet (attentive feature selection)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method learn.tabnet 1.0.6 · spec 75cefba923f23490
# Dataset: ml_penguins (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
from codesplash.deep import tabnet as deeptabnet # twin of codesplashr::cs_deep_fit_tabnet (shared weights, Adam written out)
# %% Data and split plan
TARGET = "species"
FEATURES = ["island", "bill_len", "bill_dep", "flipper_len", "body_mass", "sex"]
TASK = "multiclass"
CLASSES = ["Adelie", "Chinstrap", "Gentoo"]
POSITIVE = None
METRIC = "log_loss"
SEED = 42
PARAMS = {
"n_d": 4,
"n_a": 4,
"n_steps": 3,
"gamma": 1.3,
"n_shared": 1,
"n_independent": 1,
"lambda_sparse": 0.001,
"virtual_batch_size": 64,
"epochs": 40,
"learning_rate": 0.02,
"batch_size": None,
"weight_decay": 0,
"early_stopping": 0,
"validation_fraction": 0.1,
"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_penguins.parquet", columns=list(dict.fromkeys([TARGET] + FEATURES)))
plan = csml.read_plan("target/academy-parity/run-8142/learn.tabnet/multiclass_penguins/folds.parquet") # host-written folds: identical in Python and R
design = csml.Design.for_frame(
df,
FEATURES,
kinds={
"island": "categorical",
"bill_len": "numeric",
"bill_dep": "numeric",
"flipper_len": "numeric",
"body_mass": "numeric",
"sex": "categorical",
},
levels={
"island": ["Biscoe", "Dream", "Torgersen"],
"sex": ["female", "male"],
},
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("target/academy-parity/run-8142/learn.tabnet/multiclass_penguins/out-python")
warnings = []
def sample_weights(rows):
return None if weights is None else weights[rows]
RESAMPLE = "none"
if RESAMPLE != "none" and TASK == "regression":
warnings.append("Resampling applies to classification only — ignored for this regression target.")
resampled = None # the final model's resampling summary
notes = []
def training_set(X, rows, fold_id, repeat):
"""A fit's design matrix, targets and weights: training rows only, resampled when asked
(codesplash.ml.resample — the same rows in R, from the shared random stream)."""
yy, ww = y[rows], sample_weights(rows)
if RESAMPLE == "none" or TASK == "regression":
return X, yy, ww
from codesplash.ml import resample as csres
X2, y2, w2, info = csres.resample(
X, yy, ww, RESAMPLE, ratio=1, k=5, seed=csres.resample_seed(SEED, fold_id, repeat)
)
if fold_id == 0:
global resampled
resampled = info
return X2, y2, w2
# %% Model
from codesplash.deep import trainer as deep_trainer # training options, live progress, checkpoints (twin: cs_deep_trainer_*)
deep_trainer.configure(
{
"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="target/academy-parity/run-8142/learn.tabnet/multiclass_penguins/out-python",
)
_DEEP_FOLDS = len(plan.folds[: 0] if 0 else plan.folds)
_deep_training_set = training_set
def training_set(X, rows, fold_id, repeat):
"""Tell the trainer which fit comes next (cross-validation fold i, or the final model), then build
the training set as _ml_learn does."""
deep_trainer.set_fold(int(fold_id), _DEEP_FOLDS, "cv" if fold_id else "final")
return _deep_training_set(X, rows, fold_id, repeat)
# TabNet on PyTorch (float64, one thread): n_steps decision steps, each choosing a sparse (sparsemax) mask
# over the design columns and reading the masked row; the masks explain which columns each prediction
# used. Ghost batch norm while training, the training rows' population statistics for predictions.
# Initial weights, batches and early-stopping rows come from the shared random stream, so R's torch
# trains the same network.
def fit_model(X, y, w):
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)
fit = deeptabnet.fit_tabnet(
X, target, w, TASK, o,
n_d=int(PARAMS["n_d"]),
n_a=int(PARAMS["n_a"]),
n_steps=int(PARAMS["n_steps"]),
gamma=PARAMS["gamma"],
n_shared=int(PARAMS["n_shared"]),
n_independent=int(PARAMS["n_independent"]),
lambda_sparse=PARAMS["lambda_sparse"],
virtual_batch_size=int(PARAMS["virtual_batch_size"]),
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,
)
fit.update({"mu": mu, "sd": sd})
# Which columns the masks chose, over the training rows (population statistics).
fit["explain"] = deeptabnet.tabnet_explain(fit, X)
return fit
def predict_model(model, X):
p = deeptabnet.tabnet_predict(model, X, TASK)
if TASK == "regression":
return model["mu"] + model["sd"] * p
return p
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, batch-norm statistics, the architecture and 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"))
# %% Cross-validation
folds = plan.folds[: 0] if 0 else plan.folds
progress = cs.progress("Cross-validating", total=len(folds))
for i, fold in enumerate(folds):
prep = design.fit(df.iloc[fold.train])
model = fit_model(*training_set(prep.transform(df.iloc[fold.train]), fold.train, fold.id, fold.repeat))
run.add(fold.id, fold.repeat, "valid", fold.valid, y, y_index, predict_model(model, prep.transform(df.iloc[fold.valid])))
progress.update(i + 1, f"Fold {i + 1} of {len(folds)}")
run.lap("cv_seconds")
# %% Final model
artifacts = []
importance = None
prep = design.fit(df.iloc[plan.train])
names = prep.names
if True:
model = fit_model(*training_set(prep.transform(df.iloc[plan.train]), plan.train, 0, 0))
if resampled is not None:
from codesplash.ml import resample as csres
warnings.extend(resampled["notes"])
notes.append(csres.describe(resampled))
if len(plan.test):
run.add(0, 0, "test", plan.test, y, y_index, predict_model(model, prep.transform(df.iloc[plan.test])))
importance = feature_importance(model, names)
artifacts.append({"key": "design", "path": csml.save_json(prep.to_json(), os.path.join(out, "design.json")), "format": "json"})
artifacts.extend(save_model(model, out))
run.lap("final_seconds")
artifacts.append({"key": "predictions", "path": run.write(out), "format": "parquet"})
progress.done()
# %% Result
cs.publish(
deeptabnet.extend_tabnet(run.result(
title="TabNet (attentive feature selection)",
engine=cs.engine_info("torch", "codesplash", "numpy", "pandas"),
n_features=len(names),
n_train=len(plan.train),
n_test=len(plan.test),
params=PARAMS,
features=names,
importance=importance,
artifacts=artifacts,
warnings=warnings,
notes=notes,
), model, names)
)
Three decision steps on the penguin measurements reach a cross-validated accuracy of 97.4%. The Mask density, the share of mask weights above zero, is 23.9%: each step reads a few columns.
The average mask weight is highest for flipper length (0.265) and zero for one sex indicator. That says where the network looked. It doesn't say flipper length causes species, and among correlated columns the mask can swap from one to another between seeds.
Small tables make it wobble
PredictPredict first
TabNet with early stopping is fitted to the air-quality table, which has fewer than a hundred training rows. Its cross-validated R² for ozone is 0.63. What do you expect on the held-out test rows?
Reveal
Much lower: −0.01, no better than predicting the mean. The best epoch was 2, so training stopped almost at once. On tables this small, a run-to-run and fold-to-fold spread this wide is common for TabNet. Compare it with a linear model and boosted trees on the same folds.
TabNet (attentive feature selection): cross-validated RMSE 20.661 ± 5.090 over 3 folds; RMSE on the locked test set 22.980 (n = 23).
- CV RMSE
- 20.661
- SD across folds
- 5.090
- Test RMSE
- 22.980
Plots
View data
| Column | Share of mask weight |
|---|---|
| Temp | 0.4632 |
| solar radiation | 0.3625 |
| Wind | 0.1743 |
View data
| Network | Epoch | Training loss | Validation loss |
|---|---|---|---|
| TabNet | 1 | 0.9668 | 0.2850 |
| TabNet | 2 | 0.7333 | 0.2396 |
| TabNet | 3 | 0.5531 | 0.2817 |
| TabNet | 4 | 0.4458 | 0.2929 |
| TabNet | 5 | 0.3285 | 0.3081 |
| TabNet | 6 | 0.2821 | 0.3573 |
| TabNet | 7 | 0.2337 | 0.3483 |
| TabNet | 8 | 0.2187 | 0.3368 |
| TabNet | 9 | 0.1815 | 0.2711 |
| TabNet | 10 | 0.1652 | 0.2501 |
Cross-validation
| Fold | Repeat | n | RMSE | MAE | R² | MAPE |
|---|---|---|---|---|---|---|
| 1 | 1 | 31 | 26.398 | 18.701 | 0.5727 | 0.6081 |
| 2 | 1 | 31 | 16.687 | 12.378 | 0.6413 | 1.132 |
| 3 | 1 | 31 | 18.897 | 13.120 | 0.6871 | 0.3511 |
Attention masks by step
| Column | Share of mask weight | Step 1 mean mask | Step 2 mean mask |
|---|---|---|---|
| Temp | 0.4632 | 0.3396 | 0.3639 |
| solar radiation | 0.3625 | 0.4369 | 0.4062 |
| Wind | 0.1743 | 0.2235 | 0.2299 |
Training curves
| Network | Epoch | Training loss | Validation loss |
|---|---|---|---|
| TabNet | 1 | 0.9668 | 0.2850 |
| TabNet | 2 | 0.7333 | 0.2396 |
| TabNet | 3 | 0.5531 | 0.2817 |
| TabNet | 4 | 0.4458 | 0.2929 |
| TabNet | 5 | 0.3285 | 0.3081 |
| TabNet | 6 | 0.2821 | 0.3573 |
| TabNet | 7 | 0.2337 | 0.3483 |
| TabNet | 8 | 0.2187 | 0.3368 |
| TabNet | 9 | 0.1815 | 0.2711 |
| TabNet | 10 | 0.1652 | 0.2501 |
The exact R script · R R version 4.5.1 (2025-06-13)
# TabNet (attentive feature selection)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method learn.tabnet 1.0.6 · spec fa83fcfe71721de7
# Dataset: ml_airquality (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 is built by codesplashr's cs_deep_fit_tabnet twin.
# %% Data and split plan
TARGET <- "Ozone"
FEATURES <- c("solar radiation", "Wind", "Temp")
TASK <- "regression"
CLASSES <- c()
POSITIVE <- NULL
METRIC <- "rmse"
SEED <- 42
PARAMS <- list(
n_d = 4,
n_a = 4,
n_steps = 2,
gamma = 1.5,
n_shared = 2,
n_independent = 2,
lambda_sparse = 0.01,
virtual_batch_size = 128,
epochs = 40,
learning_rate = 0.02,
batch_size = NULL,
weight_decay = 0,
early_stopping = 8,
validation_fraction = 0.2,
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_airquality.parquet", col_select = unique(c(TARGET, FEATURES))))
plan <- cs_ml_read_plan("target/academy-parity/run-8142/learn.tabnet/regression_airquality/folds.parquet") # host-written folds: identical in Python and R
design <- cs_ml_design(
df, FEATURES,
kinds = list(
`solar radiation` = "numeric",
Wind = "numeric",
Temp = "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("target/academy-parity/run-8142/learn.tabnet/regression_airquality/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]
RESAMPLE <- "none"
if (RESAMPLE != "none" && TASK == "regression") {
warnings <- c(warnings, list("Resampling applies to classification only — ignored for this regression target."))
}
resampled <- NULL # the final model's resampling summary
notes <- list()
# A fit's design matrix, targets and weights: training rows only, resampled when asked
# (cs_ml_resample — the same rows in Python, from the shared random stream).
training_set <- function(X, rows, fold_id, repeat_) {
yy <- y[rows + 1L]
ww <- sample_weights(rows)
if (RESAMPLE == "none" || TASK == "regression") return(list(X = X, y = yy, w = ww))
r <- cs_ml_resample(X, yy, ww, RESAMPLE, ratio = 1, k = as.integer(5),
seed = cs_ml_resample_seed(SEED, fold_id, repeat_))
if (fold_id == 0) resampled <<- r$info
r
}
fit_on <- function(s) fit_model(s$X, s$y, s$w)
# %% Model
# Training options, live progress and checkpoints (twin: codesplash.deep.trainer.configure).
cs_deep_trainer_configure(list(
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 = "target/academy-parity/run-8142/learn.tabnet/regression_airquality/out-r")
.deep_folds <- length(if (0 > 0) utils::head(plan$folds, 0) else plan$folds)
.deep_training_set <- training_set
# Tell the trainer which fit comes next (cross-validation fold i, or the final model), then build the
# training set as _ml_learn does.
training_set <- function(X, rows, fold_id, repeat_) {
cs_deep_trainer_set_fold(as.integer(fold_id), .deep_folds, if (fold_id > 0) "cv" else "final")
.deep_training_set(X, rows, fold_id, repeat_)
}
# TabNet on torch for R (float64, one thread): n_steps decision steps, each choosing a sparse (sparsemax)
# mask over the design columns and reading the masked row; the masks explain which columns each
# prediction used. Ghost batch norm while training, the training rows' population statistics for
# predictions. Initial weights, batches and early-stopping rows come from the shared random stream, so
# Python's torch trains the same network.
fit_model <- function(X, y, w) {
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)
}
fit <- cs_deep_fit_tabnet(
unname(X), target, w, TASK, o,
n_d = as.integer(PARAMS$n_d),
n_a = as.integer(PARAMS$n_a),
n_steps = as.integer(PARAMS$n_steps),
gamma = PARAMS$gamma,
n_shared = as.integer(PARAMS$n_shared),
n_independent = as.integer(PARAMS$n_independent),
lambda_sparse = PARAMS$lambda_sparse,
virtual_batch_size = as.integer(PARAMS$virtual_batch_size),
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
)
fit$mu <- mu
fit$sd <- sd
# Which columns the masks chose, over the training rows (population statistics).
fit$explain <- cs_deep_tabnet_explain(fit, unname(X))
fit
}
predict_model <- function(model, X) {
p <- cs_deep_tabnet_predict(model, unname(X), TASK)
if (TASK == "regression") model$mu + model$sd * p else p
}
feature_importance <- function(model, names) NULL
save_model <- function(model, directory) {
path <- file.path(directory, "model.rds")
saveRDS(model, path) # plain numeric weights, batch-norm statistics, the architecture and 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"))
# %% Cross-validation
folds <- if (0 > 0) utils::head(plan$folds, 0) else plan$folds
progress <- cs_progress("Cross-validating", total = length(folds))
for (i in seq_along(folds)) {
fold <- folds[[i]]
prep <- cs_ml_design_fit(design, rows_of(fold$train))
model <- fit_on(training_set(cs_ml_design_apply(prep, rows_of(fold$train)), fold$train, fold$id, fold$repeat_))
cs_ml_add(run, fold$id, fold$repeat_, "valid", fold$valid, y, y_index,
predict_model(model, cs_ml_design_apply(prep, rows_of(fold$valid))))
cs_progress_update(progress, i, sprintf("Fold %d of %d", i, length(folds)))
}
cs_ml_lap(run, "cv_seconds")
# %% Final model
artifacts <- list()
importance <- NULL
prep <- cs_ml_design_fit(design, rows_of(plan$train))
names_ <- cs_ml_design_names(prep)
if (TRUE) {
model <- fit_on(training_set(cs_ml_design_apply(prep, rows_of(plan$train)), plan$train, 0L, 0L))
if (!is.null(resampled)) {
warnings <- c(warnings, as.list(resampled$notes))
notes <- c(notes, list(cs_ml_resample_describe(resampled)))
}
if (length(plan$test)) {
cs_ml_add(run, 0L, 0L, "test", plan$test, y, y_index,
predict_model(model, cs_ml_design_apply(prep, rows_of(plan$test))))
}
importance <- feature_importance(model, names_)
artifacts[[length(artifacts) + 1L]] <- list(
key = "design", path = cs_ml_save_json(cs_ml_design_json(prep), file.path(out, "design.json")), format = "json"
)
artifacts <- c(artifacts, save_model(model, out))
cs_ml_lap(run, "final_seconds")
}
artifacts[[length(artifacts) + 1L]] <- list(key = "predictions", path = cs_ml_write(run, out), format = "parquet")
cs_progress_done(progress)
# %% Result
cs_publish(cs_deep_extend_tabnet(cs_ml_result(
run,
title = "TabNet (attentive feature selection)",
engine = cs_engine_info("torch", "codesplashr", "nanoparquet"),
n_features = length(names_),
n_train = length(plan$train),
n_test = length(plan$test),
params = PARAMS,
features = names_,
importance = importance,
artifacts = artifacts,
warnings = warnings,
notes = notes
), model, names_))
TabNet (attentive feature selection): cross-validated RMSE 20.661 ± 5.090 over 3 folds; RMSE on the locked test set 22.980 (n = 23).
- CV RMSE
- 20.661
- SD across folds
- 5.090
- Test RMSE
- 22.980
To keep this page light, the plots are shown once, under the R tab.
Cross-validation
| Fold | Repeat | n | RMSE | MAE | R² | MAPE |
|---|---|---|---|---|---|---|
| 1 | 1 | 31 | 26.398 | 18.701 | 0.5727 | 0.6081 |
| 2 | 1 | 31 | 16.687 | 12.378 | 0.6413 | 1.132 |
| 3 | 1 | 31 | 18.897 | 13.120 | 0.6871 | 0.3511 |
Attention masks by step
| Column | Share of mask weight | Step 1 mean mask | Step 2 mean mask |
|---|---|---|---|
| Temp | 0.4632 | 0.3396 | 0.3639 |
| solar radiation | 0.3625 | 0.4369 | 0.4062 |
| Wind | 0.1743 | 0.2235 | 0.2299 |
Training curves
| Network | Epoch | Training loss | Validation loss |
|---|---|---|---|
| TabNet | 1 | 0.9668 | 0.2850 |
| TabNet | 2 | 0.7333 | 0.2396 |
| TabNet | 3 | 0.5531 | 0.2817 |
| TabNet | 4 | 0.4458 | 0.2929 |
| TabNet | 5 | 0.3285 | 0.3081 |
| TabNet | 6 | 0.2821 | 0.3573 |
| TabNet | 7 | 0.2337 | 0.3483 |
| TabNet | 8 | 0.2187 | 0.3368 |
| TabNet | 9 | 0.1815 | 0.2711 |
| TabNet | 10 | 0.1652 | 0.2501 |
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# TabNet (attentive feature selection)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method learn.tabnet 1.0.6 · spec fa83fcfe71721de7
# Dataset: ml_airquality (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
from codesplash.deep import tabnet as deeptabnet # twin of codesplashr::cs_deep_fit_tabnet (shared weights, Adam written out)
# %% Data and split plan
TARGET = "Ozone"
FEATURES = ["solar radiation", "Wind", "Temp"]
TASK = "regression"
CLASSES = []
POSITIVE = None
METRIC = "rmse"
SEED = 42
PARAMS = {
"n_d": 4,
"n_a": 4,
"n_steps": 2,
"gamma": 1.5,
"n_shared": 2,
"n_independent": 2,
"lambda_sparse": 0.01,
"virtual_batch_size": 128,
"epochs": 40,
"learning_rate": 0.02,
"batch_size": None,
"weight_decay": 0,
"early_stopping": 8,
"validation_fraction": 0.2,
"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_airquality.parquet", columns=list(dict.fromkeys([TARGET] + FEATURES)))
plan = csml.read_plan("target/academy-parity/run-8142/learn.tabnet/regression_airquality/folds.parquet") # host-written folds: identical in Python and R
design = csml.Design.for_frame(
df,
FEATURES,
kinds={
"solar radiation": "numeric",
"Wind": "numeric",
"Temp": "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("target/academy-parity/run-8142/learn.tabnet/regression_airquality/out-python")
warnings = []
def sample_weights(rows):
return None if weights is None else weights[rows]
RESAMPLE = "none"
if RESAMPLE != "none" and TASK == "regression":
warnings.append("Resampling applies to classification only — ignored for this regression target.")
resampled = None # the final model's resampling summary
notes = []
def training_set(X, rows, fold_id, repeat):
"""A fit's design matrix, targets and weights: training rows only, resampled when asked
(codesplash.ml.resample — the same rows in R, from the shared random stream)."""
yy, ww = y[rows], sample_weights(rows)
if RESAMPLE == "none" or TASK == "regression":
return X, yy, ww
from codesplash.ml import resample as csres
X2, y2, w2, info = csres.resample(
X, yy, ww, RESAMPLE, ratio=1, k=5, seed=csres.resample_seed(SEED, fold_id, repeat)
)
if fold_id == 0:
global resampled
resampled = info
return X2, y2, w2
# %% Model
from codesplash.deep import trainer as deep_trainer # training options, live progress, checkpoints (twin: cs_deep_trainer_*)
deep_trainer.configure(
{
"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="target/academy-parity/run-8142/learn.tabnet/regression_airquality/out-python",
)
_DEEP_FOLDS = len(plan.folds[: 0] if 0 else plan.folds)
_deep_training_set = training_set
def training_set(X, rows, fold_id, repeat):
"""Tell the trainer which fit comes next (cross-validation fold i, or the final model), then build
the training set as _ml_learn does."""
deep_trainer.set_fold(int(fold_id), _DEEP_FOLDS, "cv" if fold_id else "final")
return _deep_training_set(X, rows, fold_id, repeat)
# TabNet on PyTorch (float64, one thread): n_steps decision steps, each choosing a sparse (sparsemax) mask
# over the design columns and reading the masked row; the masks explain which columns each prediction
# used. Ghost batch norm while training, the training rows' population statistics for predictions.
# Initial weights, batches and early-stopping rows come from the shared random stream, so R's torch
# trains the same network.
def fit_model(X, y, w):
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)
fit = deeptabnet.fit_tabnet(
X, target, w, TASK, o,
n_d=int(PARAMS["n_d"]),
n_a=int(PARAMS["n_a"]),
n_steps=int(PARAMS["n_steps"]),
gamma=PARAMS["gamma"],
n_shared=int(PARAMS["n_shared"]),
n_independent=int(PARAMS["n_independent"]),
lambda_sparse=PARAMS["lambda_sparse"],
virtual_batch_size=int(PARAMS["virtual_batch_size"]),
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,
)
fit.update({"mu": mu, "sd": sd})
# Which columns the masks chose, over the training rows (population statistics).
fit["explain"] = deeptabnet.tabnet_explain(fit, X)
return fit
def predict_model(model, X):
p = deeptabnet.tabnet_predict(model, X, TASK)
if TASK == "regression":
return model["mu"] + model["sd"] * p
return p
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, batch-norm statistics, the architecture and 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"))
# %% Cross-validation
folds = plan.folds[: 0] if 0 else plan.folds
progress = cs.progress("Cross-validating", total=len(folds))
for i, fold in enumerate(folds):
prep = design.fit(df.iloc[fold.train])
model = fit_model(*training_set(prep.transform(df.iloc[fold.train]), fold.train, fold.id, fold.repeat))
run.add(fold.id, fold.repeat, "valid", fold.valid, y, y_index, predict_model(model, prep.transform(df.iloc[fold.valid])))
progress.update(i + 1, f"Fold {i + 1} of {len(folds)}")
run.lap("cv_seconds")
# %% Final model
artifacts = []
importance = None
prep = design.fit(df.iloc[plan.train])
names = prep.names
if True:
model = fit_model(*training_set(prep.transform(df.iloc[plan.train]), plan.train, 0, 0))
if resampled is not None:
from codesplash.ml import resample as csres
warnings.extend(resampled["notes"])
notes.append(csres.describe(resampled))
if len(plan.test):
run.add(0, 0, "test", plan.test, y, y_index, predict_model(model, prep.transform(df.iloc[plan.test])))
importance = feature_importance(model, names)
artifacts.append({"key": "design", "path": csml.save_json(prep.to_json(), os.path.join(out, "design.json")), "format": "json"})
artifacts.extend(save_model(model, out))
run.lap("final_seconds")
artifacts.append({"key": "predictions", "path": run.write(out), "format": "parquet"})
progress.done()
# %% Result
cs.publish(
deeptabnet.extend_tabnet(run.result(
title="TabNet (attentive feature selection)",
engine=cs.engine_info("torch", "codesplash", "numpy", "pandas"),
n_features=len(names),
n_train=len(plan.train),
n_test=len(plan.test),
params=PARAMS,
features=names,
importance=importance,
artifacts=artifacts,
warnings=warnings,
notes=notes,
), model, names)
)
What runs here
ReadCheck: TabNet
CheckpointCheck yourself
How does sparsemax differ from softmax as a column mask?
Show the answer
Answer: b
Sparsemax projects the scores onto the simplex: weights still sum to 1, but low scores land on exactly zero.
Check yourself
In TabNet's prior update , what happens to a column that the current step used with weight 1 when ?
Show the answer
Answer: a
. Larger allows reuse; forces later steps to look elsewhere.
Check yourself
TabNet's average mask is largest for one column. What can you say?
Show the answer
Answer: b
Masks describe the fitted network's behavior. They are not causal effects, and they can move between correlated columns from seed to seed.
Check yourself
What does a low Mask density tell you?
Show the answer
Answer: a
Mask density is the share of mask weights above zero. Sparsemax and the sparsity penalty push it down.
Check yourself
You want to claim TabNet suits your table. What comparison supports the claim?
Show the answer
Answer: b
The reference asks for the same splits, the same tuning budget and simple baselines. Deep tabular models often tie or lose to boosted trees.
Recap
Recap- TabNet reads a row in a few steps, each through a sparse column mask.
- Sparsemax gives exact zeros; the prior scale γ limits reusing a column.
- Masks show what the network read, not causes, and can swap between correlated columns.
- On small tables TabNet can wobble: compare it with simple baselines on the same folds.
Concepts in this lesson