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
| Type | Name | Default | Description |
|---|---|---|---|
| Real[n_samples,n_features] | data | Data to be clustered | |
| Integer | n_clusters | Number of clusters to be generated | |
| Integer | n_samples | Number of samples | |
| Integer | n_features | Number of features | |
| Real | relTol | 1e-5 | Relative tolerance on cluster positions |
| Real | absTol | 1e-8 | Absolute tolerance on cluster positions |
| Integer | max_iter | 500 | Maximum number of k-means iterations |
| Integer | n_init | 10 | Number of runs with randomized centroid seeds |
| Integer | n_cluster_size | 0 | Length of the cluster_size output vector |
Outputs
| Type | Name | Default | Description |
|---|---|---|---|
| Real[n_clusters,n_features] | centroids | Centroids of the clusters | |
| Integer[n_samples] | labels | Cluster label associated with each data point | |
| Integer[max(n_clusters, n_cluster_size)] | cluster_size | Size 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:
Addedimpuredeclaration which is needed for compliance with the Modelica Language Specification, and is required by Optimica. -
June 9, 2022 by Massimo Cimmino:
First Implementation