Skip to content

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.

Advanced ~14 min8 steps

What runs in CodeSplash

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

Read first

01

Why a table needs its own network

Read

Images 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;
02

Sparsemax puts real zeros

Read

Softmax 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:

Mi=sparsemax⁡(Pi−1⊙hi(ai−1)).M_i = \operatorname{sparsemax}\big(P_{i-1} \odot h_i(a_{i-1})\big).

In the reference's example, four columns score 1.2,0.8,−0.5,0.11.2, 0.8, -0.5, 0.1. Sparsemax gives the first two 0.7 and 0.3, and the last two exactly 0. Softmax would have given every column some weight.

03

The prior limits reuse

Read

After each step TabNet updates a prior scale for every column, Pi=Pi−1⊙(γ−Mi)P_i = P_{i-1} \odot (\gamma - M_i). A column used heavily now gets a smaller prior, so the next step is less likely to pick it again.

With γ=1.3\gamma = 1.3, the example's prior becomes 0.6, 1.0, 1.3 and 1.3. The two unused columns now lead. A larger γ\gamma lets a column be reused; γ=1\gamma = 1 forbids reusing a fully used column.

Python
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 prior
R
sparsemax <- 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)))
04

TabNet's masks on penguins

Explore
TabNet (attentive feature selection)Recorded · Python and R agreeRecorded 2026-11-25 · 42 values compared · largest relative difference 5.1e-8
R

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

Plots

Columns the attention masks choseWhich features does the model rely on most?
View data
ColumnShare of mask weight
flipper_len0.2647
island=Dream0.1429
bill_len0.1362
bill_dep0.1317
body_mass0.0946
island=Torgersen0.0915
island=Biscoe0.0826
sex=female0.0558
sex=male0
Training curves (final model)Is the network still learning, and when did it start to overfit?
View data
NetworkEpochTraining loss
TabNet11.423
TabNet21.252
TabNet31.066
TabNet40.9852
TabNet50.9233
TabNet60.8673
TabNet70.8154
TabNet80.7620
TabNet90.7151
TabNet100.6601
TabNet110.5914
TabNet120.5198
TabNet130.4622
TabNet140.4026
TabNet150.3743
TabNet160.3096
TabNet170.3092
TabNet180.2256
TabNet190.2703
TabNet200.1870
TabNet210.1713
TabNet220.1319
TabNet230.1277
TabNet240.1128
TabNet250.0927
TabNet260.0930
TabNet270.0699
TabNet280.1188
TabNet290.0629
TabNet300.0935
TabNet310.1022
TabNet320.0513
TabNet330.0472
TabNet340.1016
TabNet350.0379
TabNet360.1005
TabNet370.0690
TabNet380.0883
TabNet390.0644
TabNet400.0458

Cross-validation

FoldRepeatnlog lossaccuracybalanced accuracyF1
11920.14350.96740.97360.9650
21920.0226111
31910.18290.95600.96490.9486

Attention masks by step

ColumnShare of mask weightStep 1 mean maskStep 2 mean maskStep 3 mean mask
flipper_len0.26470.16830.36100.1162
island=Dream0.14290.00030.02210.3287
bill_len0.13620.12670.12280.2033
bill_dep0.13170.09570.13220.1405
body_mass0.09460.22710.08080.0525
island=Torgersen0.09150.11330.14560.0920
island=Biscoe0.08260.14090.11140.0669
sex=female0.05580.12760.02410
sex=male0000

Training curves

NetworkEpochTraining lossValidation loss
TabNet11.423—
TabNet21.252—
TabNet31.066—
TabNet40.9852—
TabNet50.9233—
TabNet60.8673—
TabNet70.8154—
TabNet80.7620—
TabNet90.7151—
TabNet100.6601—
TabNet110.5914—
TabNet120.5198—
TabNet130.4622—
TabNet140.4026—
TabNet150.3743—
TabNet160.3096—
TabNet170.3092—
TabNet180.2256—
TabNet190.2703—
TabNet200.1870—
TabNet210.1713—
TabNet220.1319—
TabNet230.1277—
TabNet240.1128—
TabNet250.0927—
TabNet260.0930—
TabNet270.0699—
TabNet280.1188—
TabNet290.0629—
TabNet300.0935—
TabNet310.1022—
TabNet320.0513—
TabNet330.0472—
TabNet340.1016—
TabNet350.0379—
TabNet360.1005—
TabNet370.0690—
TabNet380.0883—
TabNet390.0644—
TabNet400.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_))
Python

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

FoldRepeatnlog lossaccuracybalanced accuracyF1
11920.14350.96740.97360.9650
21920.0226111
31910.18290.95600.96490.9486

Attention masks by step

ColumnShare of mask weightStep 1 mean maskStep 2 mean maskStep 3 mean mask
flipper_len0.26470.16830.36100.1162
island=Dream0.14290.00030.02210.3287
bill_len0.13620.12670.12280.2033
bill_dep0.13170.09570.13220.1405
body_mass0.09460.22710.08080.0525
island=Torgersen0.09150.11330.14560.0920
island=Biscoe0.08260.14090.11140.0669
sex=female0.05580.12760.02410
sex=male0000

Training curves

NetworkEpochTraining lossValidation loss
TabNet11.423—
TabNet21.252—
TabNet31.066—
TabNet40.9852—
TabNet50.9233—
TabNet60.8673—
TabNet70.8154—
TabNet80.7620—
TabNet90.7151—
TabNet100.6601—
TabNet110.5914—
TabNet120.5198—
TabNet130.4622—
TabNet140.4026—
TabNet150.3743—
TabNet160.3096—
TabNet170.3092—
TabNet180.2256—
TabNet190.2703—
TabNet200.1870—
TabNet210.1713—
TabNet220.1319—
TabNet230.1277—
TabNet240.1128—
TabNet250.0927—
TabNet260.0930—
TabNet270.0699—
TabNet280.1188—
TabNet290.0629—
TabNet300.0935—
TabNet310.1022—
TabNet320.0513—
TabNet330.0472—
TabNet340.1016—
TabNet350.0379—
TabNet360.1005—
TabNet370.0690—
TabNet380.0883—
TabNet390.0644—
TabNet400.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.

05

Small tables make it wobble

Predict

Predict 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?

About the same as the cross-validated R²Much lower than the cross-validated R²
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)Recorded · Python and R agreeRecorded 2026-11-25 · 27 values compared
R

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

Columns the attention masks choseWhich features does the model rely on most?
View data
ColumnShare of mask weight
Temp0.4632
solar radiation0.3625
Wind0.1743
Training curves (final model)Is the network still learning, and when did it start to overfit?
View data
NetworkEpochTraining lossValidation loss
TabNet10.96680.2850
TabNet20.73330.2396
TabNet30.55310.2817
TabNet40.44580.2929
TabNet50.32850.3081
TabNet60.28210.3573
TabNet70.23370.3483
TabNet80.21870.3368
TabNet90.18150.2711
TabNet100.16520.2501

Cross-validation

FoldRepeatnRMSEMAER²MAPE
113126.39818.7010.57270.6081
213116.68712.3780.64131.132
313118.89713.1200.68710.3511

Attention masks by step

ColumnShare of mask weightStep 1 mean maskStep 2 mean mask
Temp0.46320.33960.3639
solar radiation0.36250.43690.4062
Wind0.17430.22350.2299

Training curves

NetworkEpochTraining lossValidation loss
TabNet10.96680.2850
TabNet20.73330.2396
TabNet30.55310.2817
TabNet40.44580.2929
TabNet50.32850.3081
TabNet60.28210.3573
TabNet70.23370.3483
TabNet80.21870.3368
TabNet90.18150.2711
TabNet100.16520.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_))
Python

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

FoldRepeatnRMSEMAER²MAPE
113126.39818.7010.57270.6081
213116.68712.3780.64131.132
313118.89713.1200.68710.3511

Attention masks by step

ColumnShare of mask weightStep 1 mean maskStep 2 mean mask
Temp0.46320.33960.3639
solar radiation0.36250.43690.4062
Wind0.17430.22350.2299

Training curves

NetworkEpochTraining lossValidation loss
TabNet10.96680.2850
TabNet20.73330.2396
TabNet30.55310.2817
TabNet40.44580.2929
TabNet50.32850.3081
TabNet60.28210.3573
TabNet70.23370.3483
TabNet80.21870.3368
TabNet90.18150.2711
TabNet100.16520.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)
)
06

What runs here

Read
07

Check: TabNet

Checkpoint

Check 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 Pi=Pi−1⊙(γ−Mi)P_i = P_{i-1} \odot (\gamma - M_i), what happens to a column that the current step used with weight 1 when γ=1\gamma = 1?

Show the answer

Answer: a

1−1=01 - 1 = 0. Larger γ\gamma allows reuse; γ=1\gamma = 1 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.

08

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