impure functionKMeans

k-means clustering algorithm

Extends from Modelica.Icons.Function (Icon for functions).

Information

This function applies k-means clustering to n-dimentional data and returns the centroid of the clusters, the cluster labels for each sample, and the size of each cluster.

The returned length of the cluster_size vector is max(n_clusters, n_cluster_size).

Implementation

The seed for random number generation is constant. It can be changed by modifying the constant seed.

Inputs

TypeNameDefaultDescription
Real[n_samples,n_features]dataData to be clustered
Integern_clustersNumber of clusters to be generated
Integern_samplesNumber of samples
Integern_featuresNumber of features
RealrelTol1e-5Relative tolerance on cluster positions
RealabsTol1e-8Absolute tolerance on cluster positions
Integermax_iter500Maximum number of k-means iterations
Integern_init10Number of runs with randomized centroid seeds
Integern_cluster_size0Length of the cluster_size output vector

Outputs

TypeNameDefaultDescription
Real[n_clusters,n_features]centroidsCentroids of the clusters
Integer[n_samples]labelsCluster label associated with each data point
Integer[max(n_clusters, n_cluster_size)]cluster_sizeSize of the clusters

Revisions

  • March 18, 2025 by Massimo Cimmino
    Added absolute tolerance. The algorithm stops when any of the relative and absolute tolerances is satisfied. This fixes errors that occur when a centroid has a value close to zero on any of its axes. See #1985. Fixed the initial selection of centroids to avoid repeated centroids. See also #1976.
  • February 1, 2023, by Michael Wetter:
    Added impure declaration which is needed for compliance with the Modelica Language Specification, and is required by Optimica.
  • June 9, 2022 by Massimo Cimmino:
    First Implementation