Nothing
#' @title K-Means Clustering Learner
#'
#' @name mlr_learners_clust.kmeans
#' @include LearnerClust.R
#'
#' @description
#' K-means clustering.
#' Calls [stats::kmeans()] from package \pkg{stats}.
#'
#' The `centers` parameter is set to 2 by default since [stats::kmeans()] 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.
#'
#' @templateVar id clust.kmeans
#' @template learner
#'
#' @references
#' `r format_bib("forgy1965cluster", "hartigan1979algorithm", "lloyd1982least", "macqueen1967some")`
#'
#' @export
#' @template seealso_learner
#' @template example
LearnerClustKMeans = R6Class(
"LearnerClustKMeans",
inherit = LearnerClust,
public = list(
#' @description
#' Creates a new instance of this [R6][R6::R6Class] class.
initialize = function() {
param_set = ps(
centers = p_uty(tags = c("train", "required"), custom_check = check_centers),
iter.max = p_int(1L, default = 10L, tags = "train"),
algorithm = p_fct(
c("Hartigan-Wong", "Lloyd", "Forgy", "MacQueen"),
default = "Hartigan-Wong",
tags = "train"
),
nstart = p_int(1L, default = 1L, tags = "train"),
trace = p_lgl(default = FALSE, tags = "train")
)
param_set$set_values(centers = 2L)
super$initialize(
id = "clust.kmeans",
feature_types = c("logical", "integer", "numeric"),
predict_types = "partition",
param_set = param_set,
properties = c("partitional", "exclusive", "complete"),
packages = c("stats", "clue"),
man = "mlr3cluster::mlr_learners_clust.kmeans",
label = "K-Means"
)
}
),
private = list(
.train = function(task) {
pv = self$param_set$get_values(tags = "train")
if (!is.null(pv$nstart) && !test_int(pv$centers)) {
warning_config("`nstart` parameter is only relevant when `centers` is integer.")
}
assert_centers_param(pv$centers, task, "centers")
m = invoke(stats::kmeans, x = task$data(), .args = pv)
if (self$save_assignments) {
self$assignments = m$cluster
}
m
},
.predict = function(task) {
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.kmeans", LearnerClustKMeans)
Any scripts or data that you put into this service are public.
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.