R/slct_psi.R

Defines functions slct_psi_mean slct_psi_categorical slct_psi_numerical slct_psi_symmetric slct_psi_rank init_history.slct_psi update_concept.slct_psi select_model.slct_psi slct_psi

Documented in slct_psi

#' @title PSI selector
#' @description Accepts a stored concept when the mean PSI over the features between the current
#'  batch and the concept's memory is within its limit, and selects the accepted concept with the
#'  smallest PSI (or PSI/limit ratio, see `rank_by`). No accepted concept: a new one is created.
#' @param max_psi Fixed PSI limit for every concept (e.g. 0.25). `NULL` (default): learned for each
#'  concept as the `tol_quantile` quantile of the PSI of the batches that belonged to it.
#' @param tol_quantile Quantile of the learned limit.
#' @param numerical_cols Names of the numerical features. `NULL`: every numeric column; the other
#'  columns are treated as categorical.
#' @param n_tiles Number of quantile bins of the numerical PSI.
#' @param rank_by Order of the accepted concepts: `"psi"` (smallest PSI) or `"ratio"` (smallest
#'  PSI/limit, ties broken by the PSI). Both coincide with a fixed `max_psi`.
#' @return A `slct_psi` object.
#' @importFrom graphics hist
#' @export
slct_psi <- function(max_psi = NULL, tol_quantile = 0.8, numerical_cols = NULL, n_tiles = 10,
                     rank_by = c("psi", "ratio")) {
  obj <- selector()
  obj$max_psi <- max_psi
  obj$tol_quantile <- tol_quantile
  obj$numerical_cols <- numerical_cols
  obj$n_tiles <- n_tiles
  obj$rank_by <- match.arg(rank_by)
  obj$limit <- learned_limit(max_psi, tol_quantile, "slct_psi")
  class(obj) <- append("slct_psi", class(obj))
  obj
}

#' @export
select_model.slct_psi <- function(obj, concept_list, valid_indices, X, y) {
  approved <- slct_psi_rank(obj, concept_list, valid_indices, X)
  list(cl = concept_list, sc = if (length(approved) > 0) approved[1] else 0)
}

#' @export
update_concept.slct_psi <- function(obj, concept, X, y, phase = "observe", record = TRUE, ...) {
  if (phase != "observe" || !record || !is.null(obj$max_psi)) return(concept)
  limit_record(obj$limit, concept, slct_psi_mean(X, concept$memory$X, obj$numerical_cols, obj$n_tiles))
}

# Leave-one-block-out: the training window is split into K contiguous blocks of `block_size` rows
# (the remainder stays at the start, only in the "rest"), and each block is compared with the rest.
#' @export
init_history.slct_psi <- function(obj, concept, block_size, ...) {
  if (!is.null(obj$max_psi)) return(concept)
  x <- concept$memory$X
  K <- NROW(x) %/% block_size
  if (K < 2) return(concept)
  offset <- NROW(x) - K * block_size
  h <- vapply(seq_len(K), function(k) {
    idx <- offset + ((k - 1) * block_size + 1):(k * block_size)
    slct_psi_mean(x[idx, , drop = FALSE], x[-idx, , drop = FALSE], obj$numerical_cols, obj$n_tiles)
  }, numeric(1))
  limit_init(obj$limit, concept, h)
}

# Accepted concepts (PSI within the limit), in the order given by `rank_by`.
slct_psi_rank <- function(obj, concept_list, valid_indices, X) {
  idx <- integer(); psi <- numeric(); ratio <- numeric()
  for (i in valid_indices) {
    p <- slct_psi_mean(X, concept_list[[i]]$memory$X, obj$numerical_cols, obj$n_tiles)
    if (is.na(p)) next
    limit <- limit_value(obj$limit, concept_list, i)
    if (p > limit) next
    idx <- c(idx, i)
    psi <- c(psi, p)
    ratio <- c(ratio, if (limit > 0) p / limit else 0)
  }
  idx[if (obj$rank_by == "ratio") order(ratio, psi) else order(psi)]
}


# =============================================================================
# PSI (also used by evt_redundant, slct_ae and the REMIND check)
# =============================================================================

# Symmetric PSI between two distributions, with additive smoothing.
slct_psi_symmetric <- function(p, q, pseudo = 0.005) {
  p <- (p + pseudo) / (sum(p) + length(p) * pseudo)
  q <- (q + pseudo) / (sum(q) + length(q) * pseudo)
  sum((p - q) * log(p / q))
}

# PSI of a numerical variable; bins from the quantiles of both samples together.
slct_psi_numerical <- function(x_batch, x_concept, n_tiles) {
  x_all <- c(x_batch, x_concept)
  x_all <- x_all[!is.na(x_all)]
  if (length(x_all) < 2) return(0)
  
  breaks <- sort(unique(as.numeric(quantile(x_all, seq(0, 1, by = 1 / n_tiles), type = 7))))
  if (length(breaks) == 1) breaks <- breaks + c(-1e-6, 1e-6)
  
  dist <- function(x) {
    x <- x[x >= min(breaks) & x <= max(breaks)]
    if (length(x) == 0) return(numeric(length(breaks) - 1))
    h <- hist(x, breaks, plot = FALSE, include.lowest = TRUE)
    h$counts / sum(h$counts)
  }
  slct_psi_symmetric(dist(x_batch), dist(x_concept))
}

# PSI of a categorical variable (frequency of each level).
slct_psi_categorical <- function(x_batch, x_concept) {
  levels <- unique(c(x_batch, x_concept))
  levels <- levels[!is.na(levels)]
  if (length(levels) == 0) return(0)
  freq <- function(x) as.numeric(table(factor(x, levels = levels))) / sum(!is.na(x))
  slct_psi_symmetric(freq(x_batch), freq(x_concept))
}

# Mean PSI over the features shared by the batch and the concept's data. NA when the concept has
# no data or no feature in common with the batch.
slct_psi_mean <- function(X, x_concept, numerical_cols, n_tiles) {
  if (NROW(x_concept) == 0) return(NA_real_)
  if (is.null(numerical_cols)) numerical_cols <- names(X)[sapply(X, is.numeric)]
  cols <- intersect(names(X), names(x_concept))
  if (length(cols) == 0) return(NA_real_)
  mean(vapply(cols, function(col) {
    if (col %in% numerical_cols) slct_psi_numerical(X[[col]], x_concept[[col]], n_tiles)
    else slct_psi_categorical(X[[col]], x_concept[[col]])
  }, numeric(1)))
}

Try the heimdall package in your browser

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

heimdall documentation built on Dec. 2, 2026, 5:08 p.m.