R/LearnerClustPAM.R

#' @title Partitioning Around Medoids Clustering Learner
#'
#' @name mlr_learners_clust.pam
#' @include LearnerClust.R
#'
#' @description
#' Partitioning Around Medoids (PAM) clustering.
#' Calls [cluster::pam()] from package \CRANpkg{cluster}.
#'
#' The `k` parameter is set to 2 by default since [cluster::pam()] doesn't have a default value for the number of
#' clusters. The predict method uses [clue::cl_predict()] to compute the cluster memberships for new data.
#'
#' @section Initial parameter values:
#' - `keep.diss`:
#'   - Actual default: `n < 100`, where `n` is the number of observations.
#'   - Adjusted default: `FALSE`.
#'   - Reason for change: Avoid storing the dissimilarity matrix in the model to save memory.
#' - `keep.data`:
#'   - Actual default: `TRUE`.
#'   - Adjusted default: `FALSE`.
#'   - Reason for change: Avoid storing the training data in the model to save memory.
#'
#' @templateVar id clust.pam
#' @template learner
#'
#' @references
#' `r format_bib("reynolds2006clustering", "schubert2019faster")`
#'
#' @export
#' @template seealso_learner
#' @template example
LearnerClustPAM = R6Class(
  "LearnerClustPAM",
  inherit = LearnerClust,
  public = list(
    #' @description
    #' Creates a new instance of this [R6][R6::R6Class] class.
    initialize = function() {
      param_set = ps(
        k = p_int(1L, tags = c("train", "required")),
        metric = p_fct(c("euclidean", "manhattan"), default = "euclidean", tags = "train"),
        medoids = p_uty(
          default = NULL,
          tags = "train",
          custom_check = crate(function(x) check_integerish(x, any.missing = FALSE, null.ok = TRUE))
        ),
        nstart = p_int(1L, tags = "train"),
        stand = p_lgl(default = FALSE, tags = "train"),
        do.swap = p_lgl(default = TRUE, tags = "train"),
        keep.diss = p_lgl(tags = "train"),
        keep.data = p_lgl(default = TRUE, tags = "train"),
        pamonce = p_uty(
          default = FALSE,
          tags = "train",
          custom_check = crate(function(x) check_flag(x) %check||% check_int(x, lower = 0L, upper = 6L))
        ),
        variant = p_fct(
          c("original", "o_1", "o_2", "f_3", "f_4", "f_5", "faster"),
          default = "original",
          tags = "train"
        ),
        trace.lev = p_int(0L, default = 0L, tags = "train")
      )

      param_set$set_values(k = 2L, keep.diss = FALSE, keep.data = FALSE)

      super$initialize(
        id = "clust.pam",
        feature_types = c("logical", "integer", "numeric"),
        predict_types = "partition",
        param_set = param_set,
        properties = c("partitional", "exclusive", "complete"),
        packages = c("cluster", "clue"),
        man = "mlr3cluster::mlr_learners_clust.pam",
        label = "Partitioning Around Medoids"
      )
    }
  ),

  private = list(
    .train = function(task) {
      pv = self$param_set$get_values(tags = "train")
      if (!is.null(pv$medoids)) {
        if (length(pv$medoids) != pv$k) {
          error_config("number of `medoids` needs to match `k`!")
        }
        if (sum(pv$medoids <= task$nrow & pv$medoids >= 1L) != pv$k) {
          error_input("`medoids` need to contain valid indices from 1 to %i (number of observations)!", task$nrow)
        }
      }

      m = invoke(cluster::pam, x = task$data(), .args = pv)
      if (self$save_assignments) {
        self$assignments = m$clustering
      }
      m
    },

    .predict = function(task) {
      if (isTRUE(self$param_set$values$stand)) {
        error_config(
          "Predicting is not supported for `stand = TRUE` since `clue::cl_predict()` ignores the standardization."
        )
      }
      partition = unclass(invoke(
        clue::cl_predict,
        self$model,
        newdata = ordered_features(task, self),
        type = "class_ids"
      ))
      list(partition = partition)
    }
  )
)

#' @include zzz.R
register_learner("clust.pam", LearnerClustPAM)

Try the mlr3cluster package in your browser

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

mlr3cluster documentation built on Sept. 17, 2026, 5:09 p.m.