K-means clustering (source code)

= K-means clustering
{title2=$\min_{C_1,\ldots,C_K}\sum_{k=1}^K\sum_{i\in C_k}\|x_i-m_k\|^2$}
{wiki}

For a prescribed number of groups, minimize within-cluster squared Euclidean distances. At fixed assignments, differentiating the objective gives the mean as the optimal centroid. At fixed centroids, assigning each point to a nearest centroid minimizes its contribution. Alternating these steps cannot increase the objective but can converge to a local optimum, so multiple starts are useful. Empty clusters and ties need an explicit handling rule. The method favors roughly spherical groups and depends on variable scaling.