Most data comes without labels. Nobody has marked which customers are bargain hunters or which songs belong together. Clustering finds those groups on its own, and k-means is the simplest way to do it. It’s just two steps, repeated until nothing changes, and you can run them by hand below.
Two steps, over and over#
You choose how many groups you want. That’s the k. K-means drops k centres onto the data, at random to begin with, and then repeats two steps:
- Assign: every point joins the group of its nearest centre.
- Move: every centre moves to the average position of the points in its group. That’s the “means” in k-means.
When an assign step changes nothing, it stops. Press Step and watch each half happen: the lines show who joined whom, and the dashed trails show where each centre moved.
Usually it takes only a handful of rounds. Each round can only make the groups tighter, which is why it always settles. The figure tracks that tightness as spread: the total squared distance from every point to its centre. Lower is tighter. (In scikit-learn it’s called inertia_.)
Settled isn’t the same as right#
Predict first
Press “Tricky start”: two centres begin inside the same blob, one between the other two. Then press Run. What happens?
The fix is cheap: run k-means several times from different starts and keep the tightest result. Libraries do this for you, and they also use a smarter way to place the first centres, called k-means++, which spreads them apart so that bad starts like this one are rare.
How many groups?#
K-means will happily find 2 groups or 20. It never tells you how many there really are. One common check is the elbow method: run it for k = 1, 2, 3… and plot the spread each time.
Spread always falls as k grows (with one group per point it would be zero), so “lowest” can’t be the rule. Look for the elbow, where adding a group stops paying off. Here it’s plainly at 3: going from 2 to 3 groups cuts the spread by three quarters, and 4 barely helps. Real data is rarely this tidy, so the elbow is a hint, not a verdict. The silhouette score is a second opinion worth asking for, and in the end the right k is the one whose groups make sense for your problem.
The mistake almost everyone makes once#
K-means measures plain distance, so every column of your data counts in its own units. That’s a problem when the units are wildly different.
Predict first
Sixty customers: half are students around 20, half are retirees in their sixties. You run k-means with k = 2 on age (in years) and income (in dollars). What will the two groups mostly reflect?
StandardScaler does.On raw numbers k-means draws its line through income and ignores the most obvious difference in the data. Standardised, every column gets an equal say and the students and retirees separate cleanly. Scale your features before clustering, every time.
In code#
With scikit-learn, scaling, clustering and the elbow check take a few lines:
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
X_scaled = StandardScaler().fit_transform(X) # every column: average 0, spread 1
for k in range(1, 9): # the elbow check
km = KMeans(n_clusters=k, n_init="auto", random_state=42).fit(X_scaled)
print(k, round(km.inertia_, 1))
km = KMeans(n_clusters=3, n_init="auto", random_state=42)
labels = km.fit_predict(X_scaled) # a group number for every rowKMeans uses k-means++ starts by default. Then the real work begins: look at a few rows from each group and give the group a name. If you can’t, the clusters may not mean much.
What to remember
- K-means repeats two steps: assign every point to its nearest centre, then move every centre to the average of its points.
- It always settles, but not always on the best answer, so run it from several starts (libraries do this for you).
- You choose k, so use the elbow method as a hint, and always scale your features first.