R/memory_oversampling.R

Defines functions memory_balance.memory_oversampling memory_oversampling

Documented in memory_oversampling

#' @title Memory with oversampling (SMOTE)
#' @description The training data is the observed data plus synthetic rows of the minority class
#'  generated with the SMOTE family until both classes have the same size, through
#'  [daltoolbox::bal_oversampling()]. It receives the one-hot encoded data, so categorical features
#'  are interpolated as dummy columns. Needs two classes and at least two rows of the minority class;
#'  otherwise the training data is the observed data.
#' @return A `memory_oversampling` object.
#' @export
memory_oversampling <- function() {
  obj <- memory_manager()
  class(obj) <- append("memory_oversampling", class(obj))
  obj
}

#' @export
memory_balance.memory_oversampling <- function(obj, X, y) {
  y_factor <- factor(y[, 1])
  counts <- table(y_factor)
  if (length(counts) != 2 || min(counts) < 2) return(list(X = X, y = y))

  yname <- names(y)[1]
  data <- as.data.frame(X)
  data[[yname]] <- y_factor
  k <- max(1L, min(5L, min(counts) - 1L))
  balanced <- transform(daltoolbox::bal_oversampling(yname, method = "smote", k = k), data)

  y_train <- data.frame(factor(balanced[[yname]], levels = levels(y_factor)))
  names(y_train) <- yname
  list(X = balanced[, setdiff(names(balanced), yname), drop = FALSE], y = y_train)
}

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.