R/smotenc_impl.R

Defines functions smotenc_data smotenc_impl smotenc

Documented in smotenc

#' SMOTENC Algorithm
#'
#' SMOTENC generates new examples of the minority class using nearest neighbors
#' of these cases, and can handle categorical variables
#'
#' @inheritParams step_smotenc
#' @param df data.frame or tibble. Must have 1 factor variable and remaining
#'  numeric variables.
#' @param var Character, name of variable containing factor variable.
#' @param k An integer. Number of nearest neighbor that are used
#'  to generate the new examples of the minority class.
#'
#' @return A data.frame or tibble, depending on type of `df`.
#' @export
#'
#' @template details-smotenc
#'
#' @details
#' Columns can be numeric and categorical with no missing data.
#'
#' @references Chawla, N. V., Bowyer, K. W., Hall, L. O., and Kegelmeyer,
#'  W. P. (2002). Smote: Synthetic minority over-sampling technique.
#'  Journal of Artificial Intelligence Research, 16:321-357.
#'
#'  Gower, J. C. (1971). A general coefficient of similarity and some of
#'  its properties. Biometrics 27(4):857-871. (For the distance metric used)
#'
#' @seealso [step_smotenc()] for step function of this method
#' @family Direct Implementations
#'
#' @examples
#' circle_numeric <- circle_example[, c("x", "y", "class")]
#'
#' res <- smotenc(circle_numeric, var = "class")
#'
#' res <- smotenc(circle_numeric, var = "class", k = 10)
#'
#' res <- smotenc(circle_numeric, var = "class", over_ratio = 0.8)
smotenc <- function(df, var, k = 5, over_ratio = 1) {
  check_data_frame(df)
  check_var(var, df)
  check_number_whole(k, min = 1)
  check_ratio(over_ratio)

  check_na(select(df, -all_of(var)))

  smotenc_impl(df, var, k, over_ratio)
}


# Splits data and appends new minority instances
smotenc_impl <- function(df, var, k, over_ratio, call = caller_env()) {
  df[[var]] <- as.factor(df[[var]])
  # split data into list names by classes
  data <- split(df, df[[var]])
  counts <- table(drop_unused_levels(df[[var]]))
  # How many samples do we want in total, per class?
  ratio_target <- round(over_target(counts, over_ratio, call = call))
  # How many classes do we need to upsample (account for 2+ classes!)
  # Get the indices of those classes
  which_upsample <- which(counts < ratio_target)
  # For each minorty class, determine how many more samples are needed
  samples_needed <- ratio_target[which_upsample] - counts[which_upsample]
  # Just saving the names of those classes
  min_names <- names(samples_needed)

  # Create a list to save all the new minority classes
  out_dfs <- list()

  # Loop through all the minorty classes, this will only loop once if there is only one minorit class
  for (i in seq_along(samples_needed)) {
    # Extract the minority dataframe
    minority <- data[[min_names[i]]]

    # Ensure that we have more minority instances than desired neighbors
    if (nrow(minority) <= k) {
      cli::cli_abort(
        c(
          "The minority class {.val {min_names[i]}} does not have enough observations to perform SMOTENC.",
          i = "{nrow(minority)} observation{?s} {?was/were} found, but {k + 1} {?is/are} needed."
        ),
        call = call
      )
    }

    # Run the smote algorithm (minority data, # of neighbors, # of sampeles needed)
    out_df <- smotenc_data(minority, k = k, n_samples = samples_needed[i])
    out_dfs[[i]] <- out_df
  }

  # Bind all of the synthesized minority classes together
  final <- rbind(df, do.call(rbind, out_dfs))
  # Make sure the levels are correct for every categorial variable (needed?)
  final[[var]] <- factor(final[[var]], levels = levels(df[[var]]))
  rownames(final) <- NULL
  final
}

# Uses nearest-neighbors and interpolation to generate new instances
smotenc_data <- function(
  data,
  k,
  n_samples,
  smotenc_ids = seq_len(nrow(data))
) {
  # Turning integer values into doubles
  integer_cols <- vapply(data, is.integer, FUN.VALUE = logical(1))
  if (any(integer_cols)) {
    for (col in names(integer_cols)[integer_cols]) {
      data[[col]] <- as.double(data[[col]])
    }
  }

  numeric_cols <- vapply(data, is.numeric, FUN.VALUE = logical(1))

  # Runs a nearest neighbor search
  # outputs a matrix, each row is a minority instance and each column is a nearest neighbor
  # k is +1 because the sample is always a nearest neighbor to itself
  ids <- withCallingHandlers(
    t(gower::gower_topn(x = data, y = data, n = k + 1, nthread = 1)$index),
    warning = function(w) {
      if (
        grepl(
          "skipping variable with zero or non-finite range",
          conditionMessage(w)
        )
      ) {
        invokeRestart("muffleWarning")
      }
    }
  )
  # Drop each observation from its own neighbor list (by row index, so exact
  # duplicates are handled correctly)
  ids <- drop_self_neighbor(ids)

  # shuffles minority indicies and repeats that shuffling until the desired number of samples is reached
  indexes <- rep(sample(smotenc_ids), length.out = n_samples)
  # tabulates how many times each minority instance is used
  index_len <- tabulate(indexes, NROW(data))

  # Initialize matrix for newly generated samples
  out <- data[rep(smotenc_ids, length.out = n_samples), ]

  # For each new sample pick a random nearest neighbor to interpoate with (1 to k)
  sampleids <- sample.int(k, n_samples, TRUE)
  # pick distance along parameterized line between current sample and chosen nearest neighbor
  runif_ids <- stats::runif(n_samples)

  out_numeric <- as.matrix(out[numeric_cols])
  out_factors <- as.matrix(out[!numeric_cols])

  data_numeric <- as.matrix(data[numeric_cols])
  data_factors <- as.matrix(data[!numeric_cols])

  iii <- 0
  for (row_num in smotenc_ids) {
    # List indices from 1:n where n is the number of times that sample is used to generate a new sample
    # iii shifts 1:n to fill in the rows of out (e.g. 1:3, 4:6, 7:8, etc.)
    index_selection <- iii + seq_len(index_len[row_num])
    # self already removed by drop_self_neighbor()
    id_knn <- ids[row_num, ]

    # need a total of index_len[row_num] new samples
    # calculates Xnew = X1 + t*(X1-Xnn)
    dif <- data_numeric[id_knn[sampleids[index_selection]], ] -
      data_numeric[rep(row_num, index_len[row_num]), ]
    gap <- dif * runif_ids[index_selection]
    out_numeric[index_selection, ] <- data_numeric[
      rep(row_num, index_len[row_num]),
    ] +
      gap

    # Replace categories with the most frequent among the seed's k neighbors
    cat_to_upgrade <- data_factors[id_knn, , drop = FALSE]

    cat_modes <- apply(cat_to_upgrade, 2, Mode)

    cat_replacement <- matrix(
      rep(cat_modes, length(index_selection)),
      nrow = length(index_selection),
      byrow = TRUE
    )

    out_factors[index_selection, ] <- cat_replacement

    iii <- iii + index_len[row_num]
  }
  vec_cbind(out_numeric, out_factors)[names(data)]
}

Try the themis package in your browser

Any scripts or data that you put into this service are public.

themis documentation built on Aug. 2, 2026, 9:07 a.m.