R/ac_remind.R

Defines functions project.concept project remind_threshold remind_fit_concept remind_train .train_rsrc remind_manage remind_drift predict.adp_recurrent fit.adp_recurrent new_concept adp_recurrent

Documented in adp_recurrent new_concept predict.adp_recurrent project

#' @title Recurrent-concept adaptive model
#' @description Drift-adaptive classifier with concept management (the model formerly named REMIND).
#'  A concept holds a model, its
#'  preprocessors (one-hot and normalization), a data memory and a decision threshold.
#'  At every labeled batch, `fit()` runs the drift detector, lets the concept_pool keep, reuse or create
#'  a concept, and trains the active concept. `predict()` answers with the active concept or, with
#'  `check`, with the concept chosen from the batch features alone.
#'
#'  A batch is usable when at least 1% of its rows are positive. A drift on a non-usable batch
#'  postpones the adaptation: the batch only enters the data windows.
#' @param method Classifier used by every concept (e.g. `torch_cla_mlp`).
#' @param drift_method Drift detector.
#' @param model_manager Concept concept_pool: `concept_pool()` stores and reuses concepts;
#'  `concept_pool_inactive()` never reuses them (every drift creates a new concept).
#' @param memory Memory prototype: stores the data window of each concept and balances the
#'  training data of every full training (first training and retrain).
#' @param trainer Training activity: how a concept's model evolves after its first (full) training
#'  (a variation point of the line). A [model_trainer()] object: [train_static()] (default; frozen),
#'  [train_retrain()] (retrained from scratch on the concept memory at every batch) or
#'  [train_incremental()] (updated with the current batch only, keeping weights and preprocessing).
#' @param train_size Number of rows needed to train a new concept. It is also the size of the
#'  sliding windows: the buffer of recent rows and the memory of each concept.
#' @param th Decision threshold. `NULL` (default): each concept uses the threshold in
#'  \{0.05, ..., 0.95\} with the highest F1 on its own memory, recomputed when its model or data
#'  change. A number fixes the threshold for every concept.
#' @param check `NULL` (default) disables the check. A `slct_psi()` object enables it: `predict()`
#'  picks, from the batch features only, the concept with the smallest ratio between its PSI and its
#'  limit; `fit()` records the PSI of each labeled batch in the check history of the active concept.
#'  The limit is the fixed `max_psi` of the object or, when `NULL`, learned from the check history
#'  (quantile `tol_quantile`). Uses also the `n_tiles` and `numerical_cols` of the object.
#' @param warmup_size Minimum number of rows to train a model, to run the drift detector and to
#'  apply the check.
#' @param record_policy Recording activity: which labeled batches enter the learned limits (an optional
#'  activity of the line). A [record_policy()] object: [rec_stable()] (default; a batch flagged by a
#'  real detector does not record, but a passive detector never blocks it) or [rec_always()] (neutral;
#'  every batch that reaches the concept pool records, used in the experiments).
#' @param check_rank How the check picks the concept (a variation point of the line). A
#'  [concept_ranker()] object: [rank_ratio()] (default; smallest PSI/limit) or [rank_psi()] (smallest
#'  PSI). Both pick a concept even above its limit (no new concept at predict time).
#' @param rare_policy Admission activity for labeled batches with < 1% positives (an optional activity
#'  of the line). A [rare_policy()] object: [rare_keep()] (default, neutral; the batch is used and only
#'  the drift adaptation is postponed) or [rare_drop()] (the batch is ignored).
#' @param preprocess Preprocessing of each concept: a [trans_pipeline()] (or any fitted-able
#'  `dal_transform`) applied to the features before the model. `NULL` (default) uses
#'  `trans_pipeline(list(one_hot(), zscore()))` (one-hot encoding then z-score normalization). Pass
#'  another sequence to change or drop steps.
#' @param verbose If `TRUE`, prints drift messages.
#' @return A `adp_recurrent` object. After each `fit()` it exposes `drifted`, `trained`, `postponed`,
#'  `dropped`, `act_concept` and the times `time_drifter`, `time_adaptation`, `time_training`,
#'  `time_threshold` and `total_time`.
#' @examples
#' \dontrun{
#' library(daltoolboxdp)
#' model <- adp_recurrent(
#'  method = torch_cla_mlp("class", c("FALSE", "TRUE"), input_size = 10, hidden_sizes = 32L),
#'  drift_method = dfr_passive(),
#'  model_manager = concept_pool(slct_psi(n_tiles = 5), evt_least_used(), n_slots = 20),
#'  memory = memory_undersampling(),
#'  trainer = train_incremental(epochs = 5),
#'  train_size = 5000,
#'  check = slct_psi(n_tiles = 5, tol_quantile = 0.8)
#' )
#' }
#' @import daltoolbox
#' @import stats
#' @export
adp_recurrent <- function(method, drift_method, model_manager = concept_pool_inactive(),
                   memory = memory_basic(),
                   trainer = train_static(),
                   train_size, th = NULL, check = NULL,
                   warmup_size = 100, rare_policy = rare_keep(),
                   record_policy = rec_stable(), check_rank = rank_ratio(),
                   preprocess = NULL, verbose = FALSE) {
  stopifnot(is.numeric(train_size), length(train_size) == 1, train_size > 0)
  if (!inherits(trainer, "model_trainer"))
    stop("trainer must be a model_trainer() object (train_static/train_retrain/train_incremental)")
  if (!inherits(rare_policy, "rare_policy"))
    stop("rare_policy must be a rare_policy() object (rare_keep/rare_drop)")
  if (!inherits(record_policy, "record_policy"))
    stop("record_policy must be a record_policy() object (rec_always/rec_stable)")
  if (!inherits(check_rank, "concept_ranker"))
    stop("check_rank must be a concept_ranker() object (rank_ratio/rank_psi)")
  if (!is.null(check) && !inherits(check, "slct_psi"))
    stop("check must be NULL or a slct_psi() object")

  obj <- drift_workflow(drift_method, warmup_size, verbose)
  obj$method <- method
  obj$model_manager <- model_manager
  obj$memory <- memory
  obj$trainer <- trainer
  obj$train_size <- as.integer(train_size)
  obj$th <- th
  if (!is.null(check)) check$limit$key <- "check_psi"   # own history, independent of the selector
  obj$check <- check
  obj$rare_policy <- rare_policy
  obj$record_policy <- record_policy
  obj$rank_check <- check_rank   # named rank_check (not check_*): avoids $check partial matching
  obj$preprocess <- if (is.null(preprocess)) trans_pipeline(list(one_hot(), zscore())) else preprocess

  obj$buffer <- list(x = NULL, y = NULL)   # most recent rows, used to train new concepts
  obj$n_created <- 0L
  obj$act_concept <- new_concept(memory)
  obj$fallback_concept <- NULL             # answers predict() while a new concept has no model

  obj$trained <- obj$postponed <- obj$dropped <- FALSE
  obj$time_drifter <- obj$time_adaptation <- obj$time_training <- obj$time_threshold <-
    obj$total_time <- NA_real_
  
  class(obj) <- c("adp_recurrent", class(obj))
  obj
}

#' @title Concept
#' @description A concept learned for one regime, created empty and filled at training. It holds the
#'  `model`, its fitted preprocessing `pipeline`, the data `memory` window, the decision threshold
#'  `th`, the learned limits (`history`) and the selectors' state (`cache`). `uid` is assigned at the
#'  first training, `slot` is the pool slot it came from (0 = new) and `version` tracks data/model
#'  changes. Projected into the model's input space with [project()].
#' @param memory A [memory_manager()] prototype for the concept's data window.
#' @return A `concept` object.
#' @export
new_concept <- function(memory) {
  structure(list(model = NULL, uid = NA_integer_, memory = memory, qty = 0, slot = 0,
                 pipeline = NULL, history = list(), cache = list(),
                 version = list(data = 0, model = 0), th = 0.5, th_version = NULL),
            class = "concept")
}


# =============================================================================
# fit and predict
# =============================================================================

#' @export
fit.adp_recurrent <- function(obj, x, y, ...) {
  start <- proc.time()[["elapsed"]]
  obj$time_drifter <- obj$time_adaptation <- obj$time_training <- obj$time_threshold <- NA_real_
  obj$drifted <- obj$trained <- obj$postponed <- obj$dropped <- FALSE
  
  target <- y[, 1]
  if (is.factor(target)) target <- as.logical(target)
  usable <- mean(target) >= 0.01
  
  # Batch with < 1% positives: set aside without a model; discarded by the admission policy.
  dropped <- rare_dropped(obj$rare_policy, usable)
  if (!usable && (is.null(obj$act_concept$model) || dropped)) {
    obj$postponed <- TRUE
    obj$dropped <- dropped
    obj$total_time <- proc.time()[["elapsed"]] - start
    return(obj)
  }
  
  # 1. Drift detection
  obj <- remind_drift(obj, x, y)
  
  # 2. Concept management (keep, reuse or create)
  t0 <- proc.time()[["elapsed"]]
  if (obj$drifted && !usable) {
    if (obj$verbose) message("REMIND: drift on a batch with < 1% positives, adaptation postponed")
    obj$postponed <- TRUE
  } else {
    if (obj$drifted && obj$verbose) message("REMIND detected a drift")
    obj <- remind_manage(obj, x, y)
  }
  obj$time_adaptation <- proc.time()[["elapsed"]] - t0
  
  # 3. Training and decision threshold
  obj <- remind_train(obj, x, y, usable)
  t0 <- proc.time()[["elapsed"]]
  obj$act_concept <- remind_threshold(obj, obj$act_concept)
  obj$time_threshold <- proc.time()[["elapsed"]] - t0
  
  # 4. Check history: the concept chosen with the labels records the PSI of the batch.
  if (!is.null(obj$check) && !obj$postponed && !is.null(obj$act_concept$model))
    obj$act_concept <- update_concept(obj$check, obj$act_concept, x, y)
  
  obj$total_time <- proc.time()[["elapsed"]] - start
  obj
}

#' @title Predict with REMIND
#' @param object A `adp_recurrent` object.
#' @param data Batch of features.
#' @param ... Not used.
#' @param type `"prob"` (default): class probabilities. `"class"`: logical vector with the
#'  positive-class decision, using the threshold of the concept that answers.
#' @return Predictions with the attributes `concept_uid` (concept that answered) and `check_ratio`
#'  (its PSI/limit ratio when chosen by the check, `NA` otherwise).
#' @export
predict.adp_recurrent <- function(object, data, type = c("prob", "class"), ...) {
  type <- match.arg(type)
  concept <- object$act_concept
  ratio <- NA_real_
  
  # Check: among the active and the stored concepts, the one with the smallest PSI/limit ratio
  # answers. Nothing is changed in the object; fit() applies the decision when the labels arrive.
  if (!is.null(object$check) && nrow(data) >= object$warmup_size) {
    chk <- object$check
    stored <- Filter(function(cn) !is.null(cn$model), object$model_manager$concept_storage)
    cands <- c(if (!is.null(concept$model)) list(concept), stored)
    cands <- cands[!duplicated(vapply(cands, function(cn) as.integer(cn$uid), integer(1)))]
    no_history <- is.null(chk$max_psi) &&
      all(vapply(cands, function(cn) limit_empty(chk$limit, cn), logical(1)))
    
    vals <- vapply(seq_along(cands), function(i) {
      psi <- slct_psi_mean(data, cands[[i]]$memory$X, chk$numerical_cols, chk$n_tiles)
      if (is.na(psi)) return(c(Inf, Inf))
      if (no_history) return(c(psi, 0))   # start of the stream: no evidence against the active concept
      limit <- limit_value(chk$limit, cands, i)
      c(psi, if (limit > 0) psi / limit else if (psi == 0) 0 else Inf)
    }, numeric(2))
    ratios <- vals[2, ]
    crit <- rank_criterion(object$rank_check, vals[1, ], ratios)
    
    if (any(is.finite(crit))) {
      best <- which.min(crit)
      concept <- cands[[best]]
      ratio <- ratios[best]
    }
  }
  
  if (is.null(concept$model) && !is.null(object$fallback_concept$model))
    concept <- object$fallback_concept
  
  if (is.null(concept$model)) {
    if (type == "class") {
      out <- rep(FALSE, nrow(data))
    } else {
      levels <- object$method$slevels
      out <- as.data.frame(matrix(FALSE, nrow = nrow(data), ncol = length(levels)))
      names(out) <- levels
    }
    attr(out, "concept_uid") <- NA_integer_
    attr(out, "check_ratio") <- NA_real_
    return(out)
  }
  
  prob <- predict(concept$model, project(concept, data))
  out <- if (type == "prob") prob else prob[, 2] > concept$th
  attr(out, "concept_uid") <- as.integer(concept$uid)
  attr(out, "check_ratio") <- ratio
  out
}


# =============================================================================
# Steps of fit
# =============================================================================

#' @noRd
#' @description Feeds the drift detector with the input its family expects (errors, a univariate
#'  summary or the normalized features). Runs only when the active concept has a model and enough
#'  data.
remind_drift <- function(obj, x, y) {
  concept <- obj$act_concept
  if (is.null(concept$model) || NROW(concept$memory$X) < obj$warmup_size) return(obj)
  
  start <- proc.time()[["elapsed"]]
  ctx <- list(features = project(concept, x), model = concept$model, y = y, th = concept$th)
  res <- drift_step(obj$drift_method, ctx)
  obj$drift_method <- res$drift_method
  obj$time_drifter <- proc.time()[["elapsed"]] - start
  if (res$drifted) obj$drifted <- TRUE
  obj
}

#' @noRd
#' @description Called at every batch. On drift, stores the active concept and asks the concept_pool for
#'  a stored concept similar to the batch (or starts a new one). Before and after this decision,
#'  the concept_pool updates the learned limits of the active concept (see `history_order` in
#'  `concept_pool()`). With `rec_stable()`, a batch flagged by a real detector never enters these
#'  histories; with `rec_always()`, every batch that reaches the concept_pool does.
remind_manage <- function(obj, x, y) {
  record <- record_limits(obj$record_policy, obj$drifted, obj$drift_method)
  
  obj$act_concept <- update_concept(obj$model_manager, obj$act_concept, x, y, stage = "before",
                                    record = record, trainer = obj$trainer)

  if (obj$drifted) {
    previous <- obj$act_concept
    obj$model_manager <- add_concept(obj$model_manager, previous)
    res <- check_concept(obj$model_manager, x, y)
    obj$model_manager <- res$mm
    obj$act_concept <- if (is.null(res$sc)) new_concept(obj$memory) else res$sc
    if (is.null(obj$act_concept$model) && !is.null(previous$model))
      obj$fallback_concept <- previous
  }
  
  obj$act_concept <- update_concept(obj$model_manager, obj$act_concept, x, y, stage = "after",
                                    record = record, trainer = obj$trainer)
  obj
}

#' @noRd
#' @description Training resources of the active line, the context the training activities need:
#'  classifier, memory prototype, preprocessing pipeline and the window/warmup sizes.
.train_rsrc <- function(obj) {
  list(method = obj$method, memory = obj$memory, preprocess = obj$preprocess,
       train_size = obj$train_size, warmup_size = obj$warmup_size)
}

#' @noRd
#' @description Updates the data windows and the model of the active concept. A new concept (no model)
#'  gets the shared first full training on the buffer; an existing concept evolves as the line's
#'  training activity (`obj$trainer`: static / retrain / incremental) prescribes.
remind_train <- function(obj, x, y, usable) {
  concept <- obj$act_concept
  rsrc <- .train_rsrc(obj)

  # Buffer and batch count advance on every batch, for every line.
  obj$buffer <- .push_window(obj$buffer, x, y, obj$train_size)
  concept$qty <- concept$qty + 1
  obj$act_concept <- concept

  # Existing concept: the training activity (variation point) decides how it evolves.
  if (!is.null(concept$model)) {
    start <- proc.time()[["elapsed"]]
    res <- advance_concept(obj$trainer, concept, x, y, usable, rsrc)
    obj$act_concept <- res$concept
    if (res$trained) {
      obj$trained <- TRUE
      obj$fallback_concept <- NULL
      obj$time_training <- proc.time()[["elapsed"]] - start
    }
    return(obj)
  }

  # New concept: shared first full training (backbone of every line).
  if (NROW(obj$buffer$x) < obj$train_size) return(obj)
  if (identical(obj$model_manager$history_init, "blocks") && obj$train_size < 2 * NROW(x))
    stop("history_init = 'blocks' requires train_size >= 2 x batch size")
  start <- proc.time()[["elapsed"]]
  mem <- fit(obj$memory, obj$buffer$x, obj$buffer$y)
  ft <- .full_train(concept, mem, rsrc)
  if (!ft$trained) return(obj)
  concept <- ft$concept
  concept$memory <- mem
  concept$history <- list()
  concept$cache <- list()
  # fit_block: called by slct_error_metrics and slct_ae (init_blocks = TRUE); the PSI selectors ignore it.
  concept <- init_history(obj$model_manager, concept, NROW(x),
                          fit_block = function(xt, yt) remind_fit_concept(obj, xt, yt))
  if (!is.null(obj$check) && identical(obj$model_manager$history_init, "blocks"))
    concept <- init_history(obj$check, concept, NROW(x))
  concept$version <- list(data = 0, model = 0)
  obj$n_created <- obj$n_created + 1L
  concept$uid <- obj$n_created
  obj$fallback_concept <- NULL
  obj$act_concept <- concept
  obj$trained <- TRUE
  obj$time_training <- proc.time()[["elapsed"]] - start
  obj
}

#' @noRd
#' @description Trains a stand-alone concept on (x, y) with the same steps as a new concept in
#'  `remind_train()` (via [.full_train()]) plus the decision threshold. Used only by the
#'  leave-one-block-out start of the error tolerance (`slct_error_metrics(init_blocks = TRUE)`).
#'  NULL when the balanced data has fewer rows than `warmup_size`.
remind_fit_concept <- function(obj, x, y) {
  concept <- new_concept(obj$memory)
  concept$memory <- fit(obj$memory, x, y)
  ft <- .full_train(concept, concept$memory, .train_rsrc(obj))
  if (!ft$trained) return(NULL)
  remind_threshold(obj, ft$concept)
}

#' @noRd
#' @description Sets the decision threshold of a concept. Fixed `obj$th` when given; otherwise the
#'  threshold in {0.05, ..., 0.95} with the highest F1 of the concept's model on its memory. The
#'  F1-optimal threshold depends on the model: it is half the attainable F1 for calibrated
#'  probabilities (Lipton et al., 2014) and rises when the model is trained on rebalanced data,
#'  which multiplies the odds by (1 - pi) / pi (Elkan, 2001). Recomputed only when the concept's
#'  model or data change (`version`).
remind_threshold <- function(obj, concept) {
  if (!is.null(obj$th)) {
    concept$th <- obj$th
    return(concept)
  }
  if (is.null(concept$model) || identical(concept$th_version, concept$version)) return(concept)
  
  d <- concept$memory
  truth <- as.logical(d$y[, 1])
  if (!any(truth, na.rm = TRUE)) return(concept)
  
  score <- predict(concept$model, project(concept, d$X))[, 2]
  grid <- seq(0.05, 0.95, by = 0.05)
  f1 <- sapply(grid, function(t) 2 * sum(score > t & truth) / (sum(score > t) + sum(truth)))
  concept$th <- grid[which.max(f1)]
  concept$th_version <- concept$version
  concept
}


# =============================================================================
# Preprocessing
# =============================================================================

#' @title Project a batch through a concept
#' @description Projects a batch into a concept's model input space with the concept's fitted
#'  preprocessing pipeline (one-hot encoding then normalization, by default). Shared by the model, the
#'  drift detector and the selectors, so none of them reaches into the concept's internals.
#' @param concept A [new_concept()] object with a fitted `pipeline`.
#' @param data Batch of features.
#' @param ... Not used.
#' @return The projected batch.
#' @export
project <- function(concept, data, ...) {
  UseMethod("project")
}

#' @export
project.concept <- function(concept, data, ...) {
  transform(concept$pipeline, data)
}

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.