Skip to contents

Mirrors the C# KMeans class: partitions the rows of x into k clusters, each row belonging to the cluster with the nearest centroid. Initialization is k-means++ by default.

Usage

ml_kmeans(x, k, seed = NULL, kmeans_plus_plus = TRUE, max_iterations = 1000)

Arguments

x

a numeric matrix or data frame with one row per observation, or a numeric vector for a single feature.

k

the number of clusters.

seed

integer PRNG seed. NULL (the default) uses the computer clock, so the fit is not reproducible; supply a seed for a reproducible fit.

kmeans_plus_plus

use k-means++ initialization (the default) rather than a uniform draw.

max_iterations

the iteration cap. Default 1000.

Value

a list with means (a k by ncol(x) matrix of cluster centroids), labels (a 0-based integer vector, one per row of x), and iterations.

Details

Two behaviours inherited from upstream are worth knowing:

  • labels are 0-BASED in both R and Python, matching the library's own indexing (the same choice shortest_path() made for node indices). Add 1 before using them to subset an R object.

  • With k = 1 the algorithm stops before its first update step, so the single reported "cluster mean" is a randomly chosen observation rather than the mean of x. Use mean() instead if that is what you want.

See also

ml_gaussian_mixture() for a covariance-aware generalization.

Examples

x <- cbind(c(1, 1.2, 0.8, 8, 8.3, 7.9), c(2, 2.1, 1.9, 9, 9.2, 8.8))
fit <- ml_kmeans(x, k = 2, seed = 12345)
fit$means
#>          [,1] [,2]
#> [1,] 1.000000    2
#> [2,] 8.066667    9