UNSUPERVISED LEARNING · 9 MIN
Clustering with k-Means
k-means groups unlabelled points into k clusters around moving centres.
PIXEL explains
- Pick k starting centres.
- Assign every point to its nearest centre, then move each centre to the mean of its points.
- Repeat until the centres stop moving.
Real world: Grouping customers by spending so each group gets its own offer.
Code
pts = [1, 2, 3, 10, 11, 12]
c = [1, 2]
for _ in range(5):
groups = [[], []]
for p in pts:
groups[0 if abs(p - c[0]) <= abs(p - c[1]) else 1].append(p)
c = [sum(g) / len(g) for g in groups]
print(c)Output ›
[2.0, 11.0]Try it in the online compiler →Checkpoint quiz
k-means needs labelled data?