Objective¶
K-means partitions data points into clusters by minimizing the total within-cluster squared distance:
subject to:
where if data point is assigned to cluster .
Lloyd’s Algorithm¶
Initialize: choose centroids randomly
Assignment step: assign each point to the nearest centroid
Update step: recompute each centroid as the mean of its assigned points
Repeat until assignments no longer change
Optimization Perspective: Block Coordinate Descent¶
The K-means algorithm is block coordinate descent on the objective :
Fix , optimize (assignment step)
Fix , optimize (update step)
The refitting step has a closed-form solution by setting the derivative to zero:
Convergence¶
K-means converges in finitely many steps because:
The assignment step never increases
The refitting step never increases
There are only finitely many possible assignments ()
However, the objective is non-convex, so the algorithm may converge to a local minimum. Finding the global optimum is NP-hard in general.
Initialization and Variants¶
| Variant | Description |
|---|---|
| Multiple restarts | Run K-means multiple times with random initializations; pick the solution with smallest |
| K-means++ | Smart initialization: choose first centroid randomly, then choose subsequent centroids with probability proportional to squared distance from nearest existing centroid |
| Mini-batch K-means | Update centroids using only a small random subset at each iteration (faster for large datasets) |
| K-medians | Use distance and median instead of mean (more robust to outliers) |
| K-medoids | Represent each cluster by an actual data point (more robust) |
| Fuzzy C-means | Allow soft assignments with membership weights |
Empty clusters: If no points are assigned to a cluster, reinitialize the centroid to a random data point or the point farthest from its current centroid.
Performance Evaluation¶
Internal metric — Silhouette Coefficient:
For a given data point, define:
: average distance to all other points in the same cluster
: smallest average distance to points in any other cluster
: large positive means well-clustered; near 0 means near boundary; negative means possibly wrong cluster.
External metric — Rand Index (RI):
Compare two partitions and of samples. Count over all unordered pairs:
: same cluster in both partitions
: different clusters in both partitions
: same in , different in
: different in , same in
Adjusted Rand Index (ARI): corrects RI for chance agreement.
ARI = 1 means perfect agreement; near 0 means random agreement.
Choosing K¶
We cannot simply minimize since it always decreases as increases. Common approaches:
Elbow method: plot vs. and look for an “elbow”
Silhouette score: choose with highest average silhouette coefficient
External metrics (if ground-truth labels are available)
Domain knowledge