KMeans groups data points by repeatedly assigning each point to its nearest centroid and moving each centroid to the mean of its assigned points. The process stops at convergence or a maximum iteration count. section 6.2
A KMeans instance manages the clustering state:
- Accepts a generic DataPoint type, a point collection, and the desired number of clusters k. section 6.2
- Normalizes every dimension with z-scores and creates a random centroid for each cluster. section 6.2
- Clears clusters, assigns points using centroid distance, recomputes coordinate-wise means, and checks whether centroids moved. section 6.2
public final class KMeans<PointType: DataPoint> {
public final class Cluster {
var points: [PointType] = [PointType]()
var centroid: PointType
init(centroid: PointType) {
self.centroid = centroid
}
}
The nested Cluster type stores a centroid and the points assigned to it, while KMeans exposes the collection-level algorithm. section 6.2
Clustering governors
Represent each Governor with longitude and age, then run KMeans<Governor>(k: 2, points: governors). One observed cluster grouped several western states with relatively old governors. Because initialization is random, repeat runs and inspect whether the resulting clusters are meaningful; the grouping indicates correlation, not a conclusive explanation. section 6.3
