Lessons › Chapter 7: Unsupervised learning
k-means clustering
Here are 24 customers placed by how they shop. Nobody has told us any groups. Can the computer find natural clusters on its own?
Watch it move. This lesson is interactive on Gradient Lab: every step is an animated scene you can replay.
Start the interactive lessonStep by step
Who are our customers?
Marketing asks for customer groups. Nobody has labels for that; the groups have to be discovered.
Points with no labels
Here are 24 customers placed by how they shop. Nobody has told us any groups. Can the computer find natural clusters on its own?
Drop k random centers
Pick how many groups you want (k = 3) and drop 3 centers at random spots. These first guesses are usually bad, and that’s fine.
Each point joins its nearest center
Every point takes the color of the center it’s closest to. Some groupings look wrong. The centers are in the wrong places.
Centers move to the middle
Each center moves to the average position of its points: its centroid. Then points re-pick their nearest center. Watch the colors fix themselves.
Repeat until nothing changes
Repeat the two moves until no point switches group. A few rounds later, three clean groups appear: k-means has found the structure.
In real life: customer segments
Shops group customers by how often they visit and how much they spend, without any labels. The groups get names afterwards, like “bargain hunters” or “weekly regulars”, and each gets different offers.
Quick check: In k-means, where does each center move to?
- The middle (average) of its points (correct)
- The farthest point in its group
- A new random spot
Each center moves to the mean of the points assigned to it; that’s where “means” in k-means comes from.
Pseudocode
k = 3
centers = pick 3 random spots
repeat until nothing changes:
each point joins its nearest center
each center moves to the middle of its points
groups = the final assignment
Key terms
- cluster
- A group of points that are close to each other.
- centroid
- The center of a cluster: the average position of its points.
Build it: Find customer segments with k-means (30 min, runs in your browser)
See the project