ml_kmeans
ml_kmeans(x, k, seed=None, kmeans_plus_plus=True, max_iterations=1000)k-means clustering.
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.
Two behaviours inherited from upstream are worth knowing:
labelsare 0-BASED in both Python and R, matching the library’s own indexing (the same choice :func:shortest_pathmade for node indices).- 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.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| x | array_like | A 2-D array with one row per observation, or a 1-D array for a single feature. | required |
| k | int | The number of clusters. | required |
| seed | int | PRNG seed. None (the default) uses the computer clock, so the fit is not reproducible; supply a seed for a reproducible fit. |
None |
| kmeans_plus_plus | bool | Use k-means++ initialization rather than a uniform draw. | True |
| max_iterations | int | The iteration cap. | 1000 |
Returns
| Name | Type | Description |
|---|---|---|
| dict | means (a k by x.shape[1] array of centroids), labels (a 0-based integer array, one per row of x), and iterations. |
Examples
>>> from corehydropy import ml_kmeans
>>> x = [[1, 2], [1.2, 2.1], [0.8, 1.9], [8, 9], [8.3, 9.2], [7.9, 8.8]]
>>> fit = ml_kmeans(x, k=2, seed=12345)
>>> fit["means"].shape
(2, 2)