K-means partitional clustering with multiple distance metrics, initialisations and empty-cluster policies. More...
#include "math_global.h"#include <random>#include <string>#include <QSharedPointer>#include <Eigen/Core>

Go to the source code of this file.
Classes | |
| class | UTILSLIB::KMeans |
| Lloyd-style K-means clustering with configurable metric, seeding and replicates. More... | |
Namespaces | |
| namespace | UTILSLIB |
| Shared utilities (I/O helpers, spectral analysis, layout management, warp algorithms). | |
Enumerations | |
| enum class | UTILSLIB::KMeansDistance { UTILSLIB::SquaredEuclidean , UTILSLIB::CityBlock , UTILSLIB::Cosine , UTILSLIB::Correlation , UTILSLIB::Hamming } |
| Distance metric for K-Means clustering. More... | |
| enum class | UTILSLIB::KMeansStart { UTILSLIB::Sample , UTILSLIB::Uniform , UTILSLIB::Cluster } |
| Initialization strategy for K-Means clustering. More... | |
| enum class | UTILSLIB::KMeansEmptyAction { UTILSLIB::Error , UTILSLIB::Drop , UTILSLIB::Singleton } |
| Action to take when a K-Means cluster becomes empty. More... | |
K-means partitional clustering with multiple distance metrics, initialisations and empty-cluster policies.
SPDX-License-Identifier: BSD-3-Clause Copyright (c) 2026 MNE-CPP Authors
Lloyd-style K-means partitions n p-dimensional samples into k clusters by alternating an assignment step (each point goes to the nearest centroid under the selected metric) with an update step (centroid ← mean of its members) until the total within-cluster distortion stops decreasing or the iteration cap is hit. Per-iteration cost is O(n*k*p), which dominates everything else in MATHLIB and makes the algorithm suitable for the cortical-patch decimation and dipole-cluster prior workflows that consume it inside INVERSELIB.
The implementation mirrors MATLAB's kmeans/ feature set: five distance metrics (squared Euclidean, city-block, cosine, correlation, Hamming) selectable via KMeansDistance, three seeding strategies (random sample, uniform within data range, subsample-then-cluster) via KMeansStart, multiple replicates with best-of selection, and three empty-cluster policies (error, drop, singleton-from-farthest-point) via KMeansEmptyAction. An optional online update phase performs single-point Lloyd moves after the batch loop converges and is enabled by default to escape shallow local minima.kmeans2 in
Reference: Lloyd (1982) "Least squares quantization in PCM"; Arthur & Vassilvitskii (2007) for the seeding intuition.
Definition in file kmeans.h.