Sub topic 1
Clustering with k-means
Prerequisites
This chapter assumes basic Python and NumPy, feature matrices with rows as samples, and familiarity with Euclidean distance, means, and supervised versus unsupervised learning.
What clustering is and where k-means fits
Clustering is an unsupervised learning task. The data has no target labels, so the algorithm looks for groups based on similarity. In contrast, classification learns from examples whose correct classes are already known.
K-means expects you to choose a number, k, for the groups. It represents each group with a centroid, which is the mean position of all points assigned to that group. The algorithm repeatedly assigns points to centroids and moves the centroids.
Distance and centroids
For two vectors, Euclidean distance is the straight-line distance:
\(d(x, c) = \sqrt{\sumj (xj-c_j)^2}\)
K-means usually assigns a point to the centroid with the smallest Euclidean distance. A centroid is not required to be an actual data point. It can be any coordinate produced by averaging the assigned points.
For example, points (1, 1) and (3, 5) have centroid (2, 3). Distance determines assignment; the mean determines the updated centroid.
| Term | Meaning |
|---|---|
| Point | One sample represented by features |
| Centroid | Mean location of a cluster |
| `k` | Requested number of clusters |
What k-means minimizes: inertia
K-means minimizes inertia, also called within-cluster sum of squares:
\[ \text{inertia} = \sumi \lVert xi-c{\elli}\rVert^2 \]
Here, \(xi\) is a point, \(c{\elli}\) is its assigned centroid, and \(\elli\) is its cluster. Lower inertia means points lie closer to their assigned centroids. Increasing k cannot increase inertia, so inertia alone does not determine the best k.
Exercise
Why can inertia alone encourage choosing too many clusters?
Show answer
Adding clusters gives points more centroids to approach, so inertia usually decreases even when the extra clusters are not useful.