R/LearnerClustAffinityPropagation.R

#' @title Affinity Propagation Clustering Learner
#'
#' @name mlr_learners_clust.ap
#' @include LearnerClust.R
#'
#' @description
#' Affinity Propagation clustering.
#' Calls [apcluster::apcluster()] from package \CRANpkg{apcluster}.
#'
#' Note that [apcluster::apcluster()] doesn't have a default for the similarity function. The predict method computes
#' the closest cluster exemplar to find the cluster memberships for new data.
#' The code is taken from
#' [StackOverflow](https://stackoverflow.com/questions/34932692/using-the-apcluster-package-in-r-it-is-possible-to-score-unclustered-data-poi)
#' answer by the `apcluster` package maintainer.
#'
#' The similarity `s` can be a function, e.g. `apcluster::negDistMat(r = 2)`, or the name of a function such as
#' `"negDistMat"`.
#'
#' @section Initial parameter values:
#' - `includeSim`:
#'   - Actual default: `TRUE`.
#'   - Adjusted default: `FALSE`.
#'   - Reason for change: Avoid storing the n x n similarity matrix in the model.
#'
#' @templateVar id clust.ap
#' @template learner
#'
#' @references
#' `r format_bib("bodenhofer2011apcluster", "frey2007clustering")`
#'
#' @export
#' @template seealso_learner
#' @template simple_example
LearnerClustAP = R6Class(
  "LearnerClustAP",
  inherit = LearnerClust,
  public = list(
    #' @description
    #' Creates a new instance of this [R6][R6::R6Class] class.
    initialize = function() {
      param_set = ps(
        s = p_uty(
          tags = c("train", "required"),
          custom_check = crate(function(x) check_function(x) %check||% check_string(x))
        ),
        p = p_uty(default = NA_real_, tags = "train", custom_check = check_numeric),
        q = p_dbl(0, 1, default = NA_real_, special_vals = list(NA_real_), tags = "train"),
        maxits = p_int(1L, default = 1000L, tags = "train"),
        convits = p_int(1L, default = 100L, tags = "train"),
        lam = p_dbl(0.5, 1, default = 0.9, tags = "train"),
        includeSim = p_lgl(default = TRUE, tags = "train"),
        details = p_lgl(default = FALSE, tags = "train"),
        nonoise = p_lgl(default = FALSE, tags = "train"),
        seed = p_int(default = NA_integer_, special_vals = list(NA_integer_), tags = "train")
      )

      param_set$set_values(includeSim = FALSE)

      super$initialize(
        id = "clust.ap",
        feature_types = c("logical", "integer", "numeric"),
        predict_types = "partition",
        param_set = param_set,
        properties = c("partitional", "exclusive", "complete"),
        packages = "apcluster",
        man = "mlr3cluster::mlr_learners_clust.ap",
        label = "Affinity Propagation"
      )
    }
  ),

  private = list(
    .train = function(task) {
      pv = self$param_set$get_values(tags = "train")
      data = as_numeric_matrix(task$data())
      m = invoke(apcluster::apcluster, x = data, .args = pv)
      # add data points corresponding to exemplars
      exemplars = m@exemplars
      setattr(m, "exemplar_data", data[exemplars, , drop = FALSE])

      if (self$save_assignments) {
        self$assignments = apcluster::labels(m, type = "enum")
      }
      m
    },

    .predict = function(task) {
      pv = self$param_set$get_values(tags = "train")
      sim_fun = pv$s
      if (is.character(sim_fun)) {
        ns = asNamespace("apcluster")
        sim_fun = if (exists(sim_fun, envir = ns, mode = "function", inherits = FALSE)) {
          get(sim_fun, envir = ns, mode = "function")
        } else {
          match.fun(sim_fun)
        }
      }
      exemplar_data = attr(self$model, "exemplar_data")

      data = as_numeric_matrix(ordered_features(task, self))
      sim_mat = sim_fun(
        rbind(exemplar_data, data),
        sel = seq_row(data) + nrow(exemplar_data)
      )[seq_row(exemplar_data), , drop = FALSE]
      partition = max.col(t(sim_mat), ties.method = "first")
      list(partition = partition)
    }
  )
)

#' @include zzz.R
register_learner("clust.ap", LearnerClustAP)

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.