K-Means Constrained is a Python library that implements K-Means clustering with user-defined minimum and maximum cluster size constraints. It's based on the constrained k-means algorithm by Bradley, Bennett, & Demiriz (2000). The current version is 0.9.0, and the project maintains an active but moderate release cadence, typically releasing updates a few times a year.
pip install k-means-constrainedVerified import paths — ran on the pinned version, not inferred.
Demonstrates how to import `KMeansConstrained`, initialize it with cluster and size constraints, fit it to data, and access the resulting cluster labels and centers.
For very large datasets, consider pre-processing steps like dimensionality reduction or data sampling. Carefully choose `n_clusters`, `size_min`, and `size_max` to balance model requirements with computational feasibility.
Always set the `random_state` parameter in the `KMeansConstrained` constructor (e.g., `random_state=42`) to ensure deterministic and reproducible output across runs.
Ensure that the total number of samples (`n_samples`) can be consistently partitioned: `n_clusters * size_min <= n_samples <= n_clusters * size_max`. Adjust parameters if an error indicates an impossible configuration.
Install the package using `pip install k-means-constrained`. Ensure your import statement is `from k_means_constrained import KMeansConstrained`.
Verify that `n_clusters * size_min <= n_samples <= n_clusters * size_max`. Adjust the number of clusters, min/max sizes, or provide more data points to satisfy the constraints.
Ensure that both `size_min` and `size_max` are integer values when initializing `KMeansConstrained`.