R/slct_error_metrics.R

Defines functions slct_error_values init_history.slct_error_metrics update_concept.slct_error_metrics select_model.slct_error_metrics slct_error_metrics

Documented in slct_error_metrics

#' @title Error selector
#' @description Accepts a stored concept when its error on the current (labeled) batch is within a
#'  tolerance of its error on its own memory (`err_batch <= err_concept + tolerance`), and selects
#'  the accepted concept with the smallest error on the batch. The error is `1 - metric`.
#' @param tolerance Fixed additive tolerance. `NULL` (default): learned for each concept as the
#'  `tol_quantile` quantile of its error gaps (`err_batch - err_concept`) on the batches that
#'  belonged to it.
#' @param tol_quantile Quantile of the learned tolerance.
#' @param th Classification threshold. `NULL` (default): the threshold of each concept.
#' @param metric Metric object (e.g. `mt_accuracy()`).
#' @param init_blocks With `history_init = "blocks"` in the concept pool, start the learned tolerance of
#'  a new concept by leave-one-block-out: one model per block, trained on the rest of the training
#'  window. `FALSE` (default): the history starts empty.
#' @return A `slct_error_metrics` object.
#' @export
slct_error_metrics <- function(tolerance = NULL, tol_quantile = 0.8, th = NULL, metric = mt_accuracy(),
                               init_blocks = FALSE) {
  obj <- selector()
  obj$tolerance <- tolerance
  obj$tol_quantile <- tol_quantile
  obj$th <- th
  obj$metric <- metric
  obj$init_blocks <- init_blocks
  obj$limit <- learned_limit(tolerance, tol_quantile, "error_gap")
  class(obj) <- append("slct_error_metrics", class(obj))
  obj
}

#' @export
select_model.slct_error_metrics <- function(obj, concept_list, valid_indices, X, y) {
  sc <- 0
  min_err <- Inf
  for (i in valid_indices) {
    res <- slct_error_values(obj, concept_list[[i]], X, y)
    concept_list[[i]] <- res$concept
    if (is.na(res$err_concept)) next
    tol <- limit_value(obj$limit, concept_list, i)
    if (res$err_batch <= res$err_concept + tol && res$err_batch < min_err) {
      sc <- i
      min_err <- res$err_batch
    }
  }
  list(cl = concept_list, sc = sc)
}

#' @export
update_concept.slct_error_metrics <- function(obj, concept, X, y, phase = "observe", record = TRUE, ...) {
  if (phase != "observe" || !record || !is.null(obj$tolerance)) return(concept)
  res <- slct_error_values(obj, concept, X, y)
  limit_record(obj$limit, res$concept, res$err_batch - res$err_concept)
}

# Leave-one-block-out (only with init_blocks = TRUE): the training window is split into K blocks as
# in init_history.slct_psi; for each block, `fit_block` (given by the recurrent line) trains a
# stand-alone concept on the rest of the window, and the gap is its error on the block minus its error
# on the rest (the same in-sample reference as the gaps recorded online). Costs K trainings per concept.
#' @export
init_history.slct_error_metrics <- function(obj, concept, block_size, fit_block = NULL, ...) {
  if (!isTRUE(obj$init_blocks) || !is.null(obj$tolerance) || is.null(fit_block)) 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)
    cn <- fit_block(x[-idx, , drop = FALSE], y[-idx, , drop = FALSE])
    if (is.null(cn)) return(NA_real_)
    res <- slct_error_values(obj, cn, x[idx, , drop = FALSE], y[idx, , drop = FALSE])
    res$err_batch - res$err_concept
  }, numeric(1))
  limit_init(obj$limit, concept, h)
}

# Error of the concept's model on the batch and on the concept's memory. The memory result is
# cached in concept$cache$error while data, model and threshold do not change. err_concept is NA
# when the concept cannot be evaluated (no model, no memory, or the metric is undefined on the
# batch or on the memory): it is not accepted and nothing is recorded.
slct_error_values <- function(obj, concept, X, y) {
  out <- list(concept = concept, err_batch = NA_real_, err_concept = NA_real_)
  if (is.null(concept$model)) return(out)
  th <- if (is.null(obj$th)) concept$th else obj$th
  
  metric_on <- function(x, target) {
    pred <- predict(concept$model, project(concept, x))[, 2] > th
    truth <- if (is.factor(target)) as.character(target) == "TRUE" else target
    m <- evaluate(obj$metric, pred, truth)
    if (is.null(m) || is.na(m)) NA_real_ else as.numeric(m)
  }
  
  m_batch <- metric_on(X, y[, 1])
  if (is.na(m_batch)) return(out)
  out$err_batch <- 1 - m_batch
  
  v <- concept$version
  st <- concept$cache$error
  if (!is.null(st) && st$data_v == v$data && st$model_v == v$model && st$th == th) {
    m_concept <- st$result
  } else {
    if (NROW(concept$memory$X) == 0) return(out)
    m_concept <- metric_on(concept$memory$X, concept$memory$y[, 1])
    if (is.na(m_concept)) return(out)
    out$concept$cache$error <- list(result = m_concept, data_v = v$data, model_v = v$model, th = th)
  }
  out$err_concept <- 1 - m_concept
  out
}

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.