R/slct_ae.R

Defines functions init_history.slct_ae slct_ae_marker slct_ae_input slct_ae_state update_concept.slct_ae select_model.slct_ae slct_ae

Documented in slct_ae

#' @title Autoencoder selector
#' @description Each stored concept has an autoencoder trained on its memory (in the concept's
#'  one-hot and normalized space). A concept is accepted when the PSI between the reconstruction
#'  errors of its autoencoder on the current batch and on its memory is within its limit; the
#'  accepted concept with the smallest PSI is selected. With an incremental trainer
#'  ([train_incremental()]), the autoencoder of the active concept is updated with every batch it
#'  receives.
#' @param encoding_size Number of units of the encoding layer.
#' @param ae_class Autoencoder constructor (e.g. `daltoolboxdp::autoenc_ed`).
#' @param batch_size Batch size of the autoencoder training.
#' @param num_epochs Epochs of a full autoencoder training.
#' @param num_epochs_incremental Epochs of each incremental update. `NULL` uses `num_epochs`.
#' @param learning_rate Learning rate of the autoencoder.
#' @param max_psi Fixed PSI limit. `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 n_tiles Number of quantile bins of the PSI.
#' @param init_blocks With `history_init = "blocks"` in the concept pool, start the learned limit of a new
#'  concept by leave-one-block-out: one autoencoder per block, trained on the rest of the training
#'  window. `FALSE` (default): the history starts empty.
#' @return A `slct_ae` object.
#' @export
slct_ae <- function(encoding_size, ae_class = daltoolboxdp::autoenc_ed, batch_size = 32,
                    num_epochs = 1000, num_epochs_incremental = 100, learning_rate = 0.001,
                    max_psi = NULL, tol_quantile = 0.8, n_tiles = 10, init_blocks = FALSE) {
  obj <- selector()
  obj$encoding_size <- encoding_size
  obj$ae_class <- ae_class
  obj$batch_size <- batch_size
  obj$num_epochs <- num_epochs
  obj$num_epochs_incremental <- num_epochs_incremental
  obj$learning_rate <- learning_rate
  obj$max_psi <- max_psi
  obj$tol_quantile <- tol_quantile
  obj$n_tiles <- n_tiles
  obj$init_blocks <- init_blocks
  obj$limit <- learned_limit(max_psi, tol_quantile, "slct_ae")
  class(obj) <- append("slct_ae", class(obj))
  obj
}

#' @export
select_model.slct_ae <- function(obj, concept_list, valid_indices, X, y) {
  sc <- 0
  min_psi <- Inf
  for (i in valid_indices) {
    concept <- concept_list[[i]]
    st <- concept$cache$slct_ae
    # The reference markers are recomputed when the concept's data changed since the last time.
    if (is.null(st) || !isTRUE(st$data_v == concept$version$data)) {
      if (NROW(concept$memory$X) == 0 || is.null(concept$pipeline)) next
      reusable <- !is.null(st$ae_model) && identical(st$pipeline, concept$pipeline)
      st <- slct_ae_state(obj, concept, if (reusable) st)
      concept_list[[i]]$cache$slct_ae <- st
    }
    psi <- slct_psi_numerical(slct_ae_marker(st$ae_model, slct_ae_input(st$pipeline, X)),
                              st$ref_row, obj$n_tiles)
    limit <- limit_value(obj$limit, concept_list, i)
    if (!is.na(psi) && psi <= limit && psi < min_psi) {
      sc <- i
      min_psi <- psi
    }
  }
  list(cl = concept_list, sc = sc)
}

#' @export
update_concept.slct_ae <- function(obj, concept, X, y, phase = "observe", record = TRUE,
                                   trainer = train_incremental(), ...) {
  st <- concept$cache$slct_ae
  
  if (phase == "observe") {
    if (!is.null(obj$max_psi) || is.null(concept$model) || NROW(concept$memory$X) == 0) return(concept)
    if (is.null(st$ae_model)) {
      st <- slct_ae_state(obj, concept)
      concept$cache$slct_ae <- st
    }
    if (!record) return(concept)
    # Computed in the autoencoder's own input space (after a retrain the concept's pipeline is newer).
    x_ref <- slct_ae_input(st$pipeline, concept$memory$X)
    x_new <- slct_ae_input(st$pipeline, X)
    psi <- slct_psi_numerical(slct_ae_marker(st$ae_model, x_new), slct_ae_marker(st$ae_model, x_ref), obj$n_tiles)
    return(limit_record(obj$limit, concept, psi))
  }

  # phase "adapt": only incremental training keeps the autoencoder input space.
  if (!inherits(trainer, "train_incremental") || is.null(st$ae_model) ||
      !identical(st$pipeline, concept$pipeline)) return(concept)
  x_new <- slct_ae_input(st$pipeline, X)
  ae_model <- st$ae_model
  epochs <- if (is.null(obj$num_epochs_incremental)) obj$num_epochs else obj$num_epochs_incremental
  ae_model$epochs <- ae_model$num_epochs <- epochs
  st$ae_model <- fit(ae_model, x_new)
  st$data_v <- NA   # reference markers are recomputed at the next selection
  concept$cache$slct_ae <- st
  concept
}

# Autoencoder state of a concept: the autoencoder (`reuse$ae_model` when its input space is
# unchanged, otherwise a new one trained on the concept's memory) and its reference markers.
slct_ae_state <- function(obj, concept, reuse = NULL) {
  x_ref <- slct_ae_input(concept$pipeline, concept$memory$X)
  ae_model <- if (!is.null(reuse) && identical(reuse$feat_names, names(x_ref))) reuse$ae_model else
    fit(obj$ae_class(input_size = ncol(x_ref), encoding_size = obj$encoding_size,
                     batch_size = obj$batch_size, num_epochs = obj$num_epochs,
                     learning_rate = obj$learning_rate), x_ref)
  list(ae_model = ae_model, feat_names = names(x_ref), ref_row = slct_ae_marker(ae_model, x_ref),
       data_v = concept$version$data, pipeline = concept$pipeline)
}

# Autoencoder input: the concept's fitted preprocessing pipeline applied to `X`, coerced to numeric.
slct_ae_input <- function(pipeline, X) {
  x <- as.data.frame(transform(pipeline, X))
  x[] <- lapply(x, as.numeric)
  x[is.na(x)] <- 0
  x
}

# Marker of each row: mean absolute reconstruction error (encoder-decoder) or mean absolute
# encoding (encoder only).
slct_ae_marker <- function(ae_model, x) {
  out <- as.matrix(transform(ae_model, x))
  if (inherits(ae_model, c("autoenc_ed", "autoenc_variational_ed"))) return(rowMeans(abs(out - as.matrix(x))))
  if (inherits(ae_model, c("autoenc_e", "autoenc_variational_e"))) return(rowMeans(abs(out)))
  stop("Unsupported autoencoder class in slct_ae.")
}
# Leave-one-block-out (only with init_blocks = TRUE): as in init_history.slct_psi, but each block is
# compared with the rest through an autoencoder trained on the rest (K autoencoders per new concept).
# `fit_block` (given by the recurrent line) builds a stand-alone concept on the rest with the steps of
# a new concept (memory, one-hot, balancing, normalization, model, threshold): the block never enters
# the one-hot or the normalization of its autoencoder, so nothing of the block leaks into its own score.
# Without `fit_block`, the concept's own
# preprocessing is used (fitted on the whole window, block included).
#' @export
init_history.slct_ae <- function(obj, concept, block_size, fit_block = NULL, ...) {
  if (!isTRUE(obj$init_blocks) || !is.null(obj$max_psi) || is.null(concept$model)) return(concept)
  x <- concept$memory$X
  y <- concept$memory$y
  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)
    rest <- if (is.null(fit_block)) {
      r <- concept
      r$memory$X <- x[-idx, , drop = FALSE]
      r
    } else fit_block(x[-idx, , drop = FALSE], y[-idx, , drop = FALSE])
    if (is.null(rest)) return(NA_real_)
    st <- slct_ae_state(obj, rest)
    slct_psi_numerical(slct_ae_marker(st$ae_model, slct_ae_input(st$pipeline, x[idx, , drop = FALSE])),
                       st$ref_row, obj$n_tiles)
  }, numeric(1))
  limit_init(obj$limit, concept, h)
}

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.