Lesson 6.1 · 8 min read · about 50 min to master at a very slow pace
K-means Clustering
K-means finds K groups in unlabelled data by alternating two simple steps. What clustering is for, the algorithm in four steps, what it minimises, and how it differs from K-nearest neighbours.
Clustering
So far every model had a label to predict. Clustering has no labels: it partitions observations into groups so that points in the same cluster are similar and points in different clusters are different. Typical uses: customer segmentation, grouping patients with similar profiles, compressing data into prototypes, exploratory analysis.
Because there's no "right answer" column, there's no test-set accuracy. Quality is judged by internal measures (how tight the clusters are) and by usefulness.
The algorithm (Lloyd's algorithm)
Input: data and the number of clusters . is the centroid (mean) of cluster .
- Initialise: pick starting centroids, e.g. random data points (or the smarter k-means++).
- Assignment step: assign every point to its nearest centroid: .
- Update step: move each centroid to the mean of its assigned points: .
- Repeat steps 2–3 until the assignments stop changing.
Two alternating guesses
Step 2 asks "given where the centres are, who belongs to whom?" Step 3 asks "given who belongs to whom, where is the best centre?" Each step can only improve the objective, so the process settles down.
What it minimises
Within-cluster sum of squares (WCSS, inertia)
The total squared distance from each point to its own cluster's centre.
It's a squared-error loss with no labels: each point's "target" is its own centroid. The algorithm finds a local minimum of , not necessarily the global one (6.3).
K-means vs K-nearest neighbours
| K-means | K-nearest neighbours | |
|---|---|---|
| Learning type | Unsupervised (no labels) | Supervised (labels needed) |
| Task | Clustering | Regression or classification |
| What is | Number of clusters | Number of neighbours used to predict |
| Output | Cluster assignments + centroids | Predicted value or class |
Wrong tool
"K-means is used to predict whether a patient will be readmitted." If labels exist and prediction is the goal, use supervised learning. Clusters can be useful features, but they aren't predictions.
Cheatsheet
K-means
K-means objective
K-means vs K-NN
Check your understanding
Score 75% or more to master this lesson and earn XP. Answer first, then check.