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.
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:
labelsare 0-BASED in both R and Python, matching the library's own indexing (the same choiceshortest_path()made for node indices). Add 1 before using them to subset an R object.With
k = 1the algorithm stops before its first update step, so the single reported "cluster mean" is a randomly chosen observation rather than the mean ofx. Usemean()instead if that is what you want.
See also
ml_gaussian_mixture() for a covariance-aware generalization.