R/ac_trainer.R

Defines functions .full_train .advance_window .push_window advance_concept.train_incremental advance_concept.train_retrain advance_concept.train_static advance_concept train_incremental train_retrain train_static model_trainer

Documented in advance_concept model_trainer train_incremental train_retrain train_static

#' @title Model-training activity
#' @description Base class of the model-training activities: how an **existing** concept's model evolves
#'  at each labeled batch. It is a variation point of the recurrent-concept experiment line
#'  ([adp_recurrent()]) — the first full training of a concept is the shared backbone; from there, the
#'  trainer chosen for the line decides the evolution. The variants are:
#'  \describe{
#'    \item{[train_static()]}{the concept is frozen: neither its data window nor its model change.}
#'    \item{[train_retrain()]}{the data window slides with the batch and the model is retrained from
#'      scratch on the concept memory.}
#'    \item{[train_incremental()]}{the data window slides and the model is updated with the current
#'      batch only, keeping its weights and preprocessing.}
#'  }
#'  A trainer is concept-scoped: it depends only on the `concept`, the batch and the training resources
#'  (classifier, memory, pipeline), not on the model that hosts it. New variants plug in by subclassing
#'  and implementing [advance_concept()].
#' @return A `model_trainer` object.
#' @import daltoolbox
#' @export
model_trainer <- function() {
  obj <- dal_base()
  class(obj) <- append("model_trainer", class(obj))
  obj
}

#' @title Static training (frozen concept)
#' @description Training activity that never updates a concept after its first full training: the
#'  concept memory and model stay frozen. The neutral element of model evolution.
#' @return A `train_static` object.
#' @export
train_static <- function() {
  obj <- model_trainer()
  class(obj) <- append("train_static", class(obj))
  obj
}

#' @title Retraining
#' @description Training activity that, at every labeled batch, slides the concept's data window and
#'  retrains the model from scratch on the concept memory.
#' @return A `train_retrain` object.
#' @export
train_retrain <- function() {
  obj <- model_trainer()
  class(obj) <- append("train_retrain", class(obj))
  obj
}

#' @title Incremental training
#' @description Training activity that slides the concept's data window and updates the model with the
#'  current batch only, keeping its weights and preprocessing.
#' @param epochs Epochs of each incremental update. `NULL` (default) keeps the model's own `epochs`.
#' @return A `train_incremental` object.
#' @export
train_incremental <- function(epochs = NULL) {
  if (!is.null(epochs) && (!is.numeric(epochs) || length(epochs) != 1 || epochs < 1))
    stop("epochs must be NULL or a single number >= 1")
  obj <- model_trainer()
  obj$epochs <- epochs
  class(obj) <- append("train_incremental", class(obj))
  obj
}

#' @title Evolve an existing concept with a labeled batch
#' @description Generic of the training activity: given a concept that already has a model, evolve it
#'  with the current batch as the chosen [model_trainer()] prescribes. The first full training of a new
#'  concept is handled by the line's backbone, not here.
#' @param trainer A [model_trainer()] object.
#' @param concept The active [new_concept()] (with a fitted model).
#' @param x,y Features and labels of the current batch.
#' @param usable `TRUE` when the batch has enough positives to update a model.
#' @param rsrc Training resources: a list with `method`, `memory`, `preprocess`, `train_size` and
#'  `warmup_size` (see the recurrent line's internals).
#' @return `list(concept = <updated concept>, trained = <logical: whether the model changed>)`.
#' @export
advance_concept <- function(trainer, concept, x, y, usable, rsrc) {
  UseMethod("advance_concept")
}

#' @export
advance_concept.train_static <- function(trainer, concept, x, y, usable, rsrc) {
  list(concept = concept, trained = FALSE)
}

#' @export
advance_concept.train_retrain <- function(trainer, concept, x, y, usable, rsrc) {
  concept <- .advance_window(concept, x, y, rsrc)
  ft <- .full_train(concept, concept$memory, rsrc)
  concept <- ft$concept
  if (ft$trained) concept$version$model <- concept$version$model + 1
  list(concept = concept, trained = ft$trained)
}

#' @export
advance_concept.train_incremental <- function(trainer, concept, x, y, usable, rsrc) {
  concept <- .advance_window(concept, x, y, rsrc)
  if (!usable) return(list(concept = concept, trained = FALSE))
  model <- concept$model
  if (!is.null(trainer$epochs)) model$epochs <- trainer$epochs
  concept$model <- fit(model, cbind(project(concept, x), y))
  concept$version$model <- concept$version$model + 1
  list(concept = concept, trained = TRUE)
}


# =============================================================================
# Shared training helpers (used by the trainers and by the line's backbone)
# =============================================================================

#' @noRd
#' @description Appends a batch to a sliding window of at most `train_size` rows.
.push_window <- function(win, x, y, train_size) {
  win$x <- rbind(win$x, x)
  win$y <- rbind(win$y, y)
  n <- nrow(win$x)
  if (n > train_size) {
    keep <- (n - train_size + 1):n
    win$x <- win$x[keep, , drop = FALSE]
    win$y <- win$y[keep, , drop = FALSE]
  }
  win
}

#' @noRd
#' @description Slides a concept's data window by the batch and refits its memory (data version bumps).
.advance_window <- function(concept, x, y, rsrc) {
  win <- .push_window(list(x = concept$memory$X, y = concept$memory$y), x, y, rsrc$train_size)
  concept$memory <- fit(rsrc$memory, win$x, win$y)
  concept$version$data <- concept$version$data + 1
  concept
}

#' @noRd
#' @description Full training of a concept on a memory window: fit the preprocessing pipeline, balance
#'  on the projected features and fit the model. Returns `list(concept, trained)`; `trained` is `FALSE`
#'  (and the model is left unchanged) when the balanced data is below `warmup_size`.
.full_train <- function(concept, mem, rsrc) {
  concept$pipeline <- fit(rsrc$preprocess, mem$X)
  xp <- transform(concept$pipeline, mem$X)
  train <- memory_balance(rsrc$memory, xp, mem$y)   # balance on the projected (numeric) features
  if (nrow(train$X) < rsrc$warmup_size) return(list(concept = concept, trained = FALSE))
  concept$model <- fit(rsrc$method, cbind(train$X, train$y))
  list(concept = concept, trained = TRUE)
}

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.