k-Means Clustering
Splits data into k groups by alternating two steps: assign each point to its nearest center, then move each center to the middle of its points.
Also k-means · Lloyd's algorithm
MacQueen, 1967 (Lloyd's algorithm, 1957)
Drop k flags on a playground. Every kid runs to the closest flag. Then move each flag to the middle of its crowd. Kids switch flags if another is now closer. Repeat until nobody moves.
Where it fits
+All relationships as a list
Is a kind of / part of
Evolved into
Try it
How it works
k-means needs one number from you: k, how many groups you want. Then:
- Initialize: place k centers, for example on k random data points.
- Assign: each point joins the cluster of its nearest center.
- Update: move each center to the average position of its points.
- Repeat steps 2 and 3 until assignments stop changing.
Each round can only lower the total squared distance from points to their centers, so the algorithm always stops. But it may stop in a poor arrangement if the starting centers were unlucky. The usual fixes: run it several times and keep the best, or use k-means++, which spreads the initial centers out.
To choose k, people often plot the total distance for k = 1, 2, 3… and look for the “elbow” where adding clusters stops helping much.
The math
k-means minimizes the within-cluster sum of squares over assignments with centroids :
Everyday use cases
- Case 01
Supermarket customer types
Group shoppers by basket size, visit frequency and spend into a handful of segments.
- Case 02
Color quantization
Reduce an image to 16 colors by clustering its pixel colors.
Strengths, weaknesses and when to use it
Strengths
- Simple, fast and scales to large datasets.
- Easy to explain and visualize.
Weaknesses
- You must choose k in advance.
- Assumes roughly round, similarly sized clusters.
- Different starting centers can give different results.
When to use itFor a quick segmentation of numeric data into a known or guessable number of groups.
Check yourself
- Q01
What are the two alternating steps of k-means?
Show answer
B: Assign points to the nearest center, then move centers to the mean of their points
- Q02
Which shape of cluster does k-means handle worst?
Show answer
B: Two interlocking crescent moons