liveBook · Manning

KMeans

As explained in Classic Computer Science Problems in Swift: Essential techniques for practicing programmers

KMeans is a book-specific generic Swift class that maintains clusters and executes the k-means clustering algorithm for types conforming to DataPoint.

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

How Classic Computer Science Problems in Swift: Essential techniques for practicing programmers covers it

How deep it goes
Details normalization, centroid initialization, assignment, recomputation, convergence, and state management without formal analysis.
Examples
Uses Point3D values and state governors represented by longitude and age.
What it assumes
Assumes Swift types, arrays, generics, distance, means, and z-score normalization.
What you can do after
Build it from scratch in Swift and run clustering with a custom DataPoint type.
How it connects
Connects k-means clustering with DataPoint, centroids, distance, z-score normalization, and convergence.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Classic Computer Science Problems in Swift: Essential techniques for practicing programmers. The section links point to the parts of the book it draws on.