R/tabicl-ensemble.R

Defines functions tabicl_single_member tabicl_regressor_mean tabicl_regressor_stats tabicl_classifier_proba tabicl_member_input tabicl_member tabicl_softmax_rows tabicl_unique_filter

# Ensemble prediction engine for TabICL. Reproduces the sklearn wrappers'
# predict path: per ensemble member, preprocess (fit on train, transform
# train+test), optionally permute features and shuffle class labels, run the
# in-context forward pass, then combine across members.
#
# For classification, member logits are averaged (after undoing the class
# shuffle) and a temperature softmax is applied. For regression, the model's
# quantiles become a per-member distribution that the requested statistics are
# read off; see `tabicl_regressor_stats()` for how members are combined.
#
# NOTE on reproducibility: the sklearn `EnsembleGenerator` chooses member
# configurations (feature permutations, member ordering) with Python's
# `random.Random`, whose stream cannot be reproduced in R. The single-member
# configuration (`num_estimators = 1`: one "none" member, identity shuffles) is
# fully deterministic and matches Python exactly; multi-member ensembles here
# are a faithful reimplementation of the same algorithm, not bit-identical.

# Features with more than one unique value in the training set
# (UniqueFeatureFilter). As in sklearn, nothing is dropped from a single row.
tabicl_unique_filter <- function(x_train) {
  if (nrow(x_train) <= 1L) {
    return(rep(TRUE, ncol(x_train)))
  }
  brulee_varying_columns(x_train)
}

# Row-wise temperature softmax of a logit matrix (n, n_classes).
tabicl_softmax_rows <- function(logits, temperature = 0.9) {
  z <- logits / temperature
  z <- z - apply(z, 1, max) # column-major recycling subtracts the row max
  e <- exp(z)
  e / rowSums(e)
}

# An ensemble member: normalization method, 1-based feature permutation over the
# kept features, and a 0-based class-label pattern (identity for regression).
tabicl_member <- function(norm = "none", feat = NULL, class_shuffle = NULL) {
  list(norm = norm, feat = feat, class_shuffle = class_shuffle)
}

# Build the model input tensor for one member: preprocess (cached per norm
# method), concatenate train + test rows, permute feature columns.
tabicl_member_input <- function(member, pp_cache, xtr, xte, device) {
  nm <- member$norm
  if (is.null(pp_cache$store[[nm]])) {
    pp <- tabicl_preprocess_fit(xtr, normalization_method = nm)
    pp_cache$store[[nm]] <- list(
      tr = tabicl_preprocess_transform(pp, xtr),
      te = tabicl_preprocess_transform(pp, xte)
    )
  }
  cached <- pp_cache$store[[nm]]
  x_cat <- rbind(cached$tr, cached$te)[, member$feat, drop = FALSE]
  torch::torch_tensor(x_cat, dtype = torch::torch_float())$unsqueeze(1)$to(
    device = device
  )
}

# Class probabilities for test rows, averaging member logits. `y_train` are
# integer labels in 0..(C-1) (label-encoded). Returns an (n_test, C) matrix.
tabicl_classifier_proba <- function(
  loaded,
  x_train,
  y_train,
  x_test,
  members,
  temperature = 0.9,
  device = "cpu"
) {
  model <- loaded$model
  n_classes <- length(unique(y_train))
  keep <- tabicl_unique_filter(x_train)
  xtr <- x_train[, keep, drop = FALSE]
  xte <- x_test[, keep, drop = FALSE]
  n_train <- nrow(xtr)

  pp_cache <- new.env()
  pp_cache$store <- list()

  logit_sum <- matrix(0, nrow = nrow(xte), ncol = n_classes)
  for (member in members) {
    x_t <- tabicl_member_input(member, pp_cache, xtr, xte, device)
    shuffled <- member$class_shuffle[y_train + 1L] # apply class pattern
    y_t <- torch::torch_tensor(
      matrix(shuffled, nrow = 1),
      dtype = torch::torch_float()
    )$to(device = device)

    out <- torch::with_no_grad(
      model(x_t, y_t, return_logits = TRUE, softmax_temperature = temperature)
    )
    logits <- as.matrix(out$squeeze(1)$cpu())
    # Undo the class shuffle: column j corresponds to original class j.
    logit_sum <- logit_sum + logits[, member$class_shuffle + 1L, drop = FALSE]
  }

  avg <- logit_sum / length(members)
  proba <- tabicl_softmax_rows(avg, temperature)
  proba / rowSums(proba)
}

# Regression statistics for test rows. The regression head emits a fixed grid of
# quantiles per row; each ensemble member's grid becomes a distribution
# (`tabicl_quantile_dist()`) that the requested statistics are read off. The
# ensemble runs once regardless of how many statistics are asked for.
#
# Members are combined on the outcome's scale, with a rule per statistic:
#   * "mean"      arithmetic mean of the member means (as in the reference).
#   * "quantiles" arithmetic mean of the member quantile curves, level by level
#                 (Vincentization, as in the reference). A sum of non-decreasing
#                 sequences is non-decreasing, so the pooled curve stays
#                 monotone and needs no second crossing repair.
#   * "variance"  geometric mean of the member variances: a variance is a
#                 positive scale parameter, so members are pooled
#                 multiplicatively. Accumulated in log space.
#
# `y_train` are the raw numeric targets. Inverse-scaling is affine for locations
# (`* y_scale + y_mean`) but multiplicative for a variance (`* y_scale^2`); see
# the note in `predict.brulee_tab_icl()` on the deviation from the reference.
tabicl_regressor_stats <- function(
  loaded,
  x_train,
  y_train,
  x_test,
  members,
  output_type = "mean",
  alphas = NULL,
  device = "cpu",
  call = rlang::caller_env()
) {
  output_type <- rlang::arg_match(
    output_type,
    c("mean", "variance", "quantiles"),
    multiple = TRUE,
    call = call
  )
  if ("quantiles" %in% output_type && length(alphas) == 0L) {
    cli::cli_abort(
      "{.arg alphas} is required when {.val quantiles} is requested.",
      call = call
    )
  }

  model <- loaded$model

  # Target StandardScaler (ddof = 0), as in the sklearn regressor.
  y_mean <- mean(y_train)
  y_scale <- sqrt(mean((y_train - y_mean)^2))
  if (y_scale == 0) {
    y_scale <- 1
  }
  y_scaled <- (y_train - y_mean) / y_scale

  keep <- tabicl_unique_filter(x_train)
  xtr <- x_train[, keep, drop = FALSE]
  xte <- x_test[, keep, drop = FALSE]

  pp_cache <- new.env()
  pp_cache$store <- list()

  n_test <- nrow(xte)
  mean_sum <- numeric(n_test)
  log_var_sum <- numeric(n_test)
  quantile_sum <- matrix(0, nrow = n_test, ncol = length(alphas))

  for (member in members) {
    x_t <- tabicl_member_input(member, pp_cache, xtr, xte, device)
    y_t <- torch::torch_tensor(
      matrix(y_scaled, nrow = 1),
      dtype = torch::torch_float()
    )$to(device = device)

    quantiles <- torch::with_no_grad(model(x_t, y_t))
    # Always built, even for the mean: `tabicl_qdist_mean()` reduces the sorted
    # quantiles, and skipping the sort would change the summation order.
    dist <- tabicl_quantile_dist(quantiles)

    if ("mean" %in% output_type) {
      member_mean <- as.numeric(tabicl_qdist_mean(dist)$squeeze(1)$cpu())
      mean_sum <- mean_sum + (member_mean * y_scale + y_mean) # inverse-scale
    }
    if ("quantiles" %in% output_type) {
      member_q <- tabicl_qdist_quantiles(dist, alphas)
      member_q <- as.matrix(member_q$squeeze(1)$cpu())
      quantile_sum <- quantile_sum + (member_q * y_scale + y_mean)
    }
    if ("variance" %in% output_type) {
      # `tabicl_qdist_variance()` is the unbiased (ddof = 1) variance, matching
      # the Python `Tensor.var()` default. That is a different convention from
      # the ddof = 0 target scaler above; both are faithful ports.
      member_var <- as.numeric(tabicl_qdist_variance(dist)$squeeze(1)$cpu())
      # `pmax()` only guards a float32 round-trip yielding a tiny negative
      # value. `log(0) = -Inf` is intentional: it collapses a degenerate
      # zero-variance member to a pooled variance of zero, which is what a
      # geometric mean should do.
      log_var_sum <- log_var_sum + log(pmax(member_var, 0))
    }
  }

  n_members <- length(members)
  res <- list()
  if ("mean" %in% output_type) {
    res$mean <- mean_sum / n_members
  }
  if ("quantiles" %in% output_type) {
    res$quantiles <- quantile_sum / n_members
  }
  if ("variance" %in% output_type) {
    # Geometric mean across members. The inverse scaling is applied once, here:
    # it commutes with a geometric mean, so placement is immaterial, and this
    # keeps the loop accumulator in the model's standardized units. A variance
    # is in *squared* outcome units, so only `y_scale^2` applies and the
    # location shift drops out. The reference implementation instead pushes the
    # variance through the full location-scale inverse; brulee differs here
    # deliberately -- see `?predict.brulee_tab_icl`.
    res$variance <- exp(log_var_sum / n_members) * y_scale^2
  }
  res
}

# Mean regression prediction for test rows, averaging inverse-scaled per-member
# means. `y_train` are the raw numeric targets.
tabicl_regressor_mean <- function(
  loaded,
  x_train,
  y_train,
  x_test,
  members,
  device = "cpu"
) {
  tabicl_regressor_stats(
    loaded,
    x_train,
    y_train,
    x_test,
    members,
    output_type = "mean",
    device = device
  )$mean
}

# Deterministic single "none" member with identity feature / class shuffles --
# the configuration that matches the sklearn wrappers at num_estimators = 1.
tabicl_single_member <- function(n_features, n_classes = NULL) {
  tabicl_member(
    norm = "none",
    feat = seq_len(n_features),
    class_shuffle = if (is.null(n_classes)) NULL else seq_len(n_classes) - 1L
  )
}

Try the brulee package in your browser

Any scripts or data that you put into this service are public.

brulee documentation built on Nov. 25, 2026, 9:06 a.m.