Learning path: Find Structure Without Labels: Clustering, PCA and Recommenders · Step 1 of 6
K-Means Clustering: Find Groups in Data With No Labels
How k-means finds groups without labels: the assign-update loop worked by hand on eight homes, then KMeans on 2,600 customers, bad random starts, k-means++ and why you scale first.
What you will learn
- Explain centroids, clusters and the assign-update loop
- Run the loop by hand in NumPy and read inertia
- Cluster 2,600 customers with KMeans and plot the groups
- Use k-means++, n_init and scaling to avoid bad clusters
Before you start
- Basic Python and pandas
- Feature Scaling: StandardScaler and MinMaxScaler
So far every model we trained had an answer column to learn from. This time there are no labels at all. We give the computer a table of customers and ask it to find the groups by itself. That's clustering, and k-means is the most popular way to do it.
Where do we open the pizza shops?
Imagine a small town with eight homes, A to H. We want to open two pizza shops, and every home should be close to one of them, because nobody wants a cold pizza. Each home simply orders from its nearest shop.
- The homes are our data points.
- The shops are the centroids, the middle of each group.
- The homes of one shop form a cluster.
- k is how many shops we open. Here, k = 2.
The computer doesn't know the good spots, so it starts with a guess and improves it in rounds.
Assign, then update
We drop shop 1 on home A (1, 2) and shop 2 on home D (3, 2). Then one round has two steps:
- Assign: every home joins its nearest shop. A, B and C go to shop 1; D, E, F, G and H go to shop 2.
- Update: each shop moves to the average position of its own homes. Shop 2 moves to (6.8, 5.8), the average of D, E, F, G and H.
Now repeat. Shop 2 moved far away, so home D is now nearer to shop 1, and D switches. Both shops move to the middle of their new homes. In round 3 nobody switches, so no shop moves, and that's the signal to stop.
Inertia: one score for the whole grouping
How do we know the groups got better? For each home, square the distance to its own shop, then add all eight squares. That sum is called inertia. A small inertia means every home is close to its own shop, and the loop keeps pushing it down: 44.27 after round 1, 10.25 after round 2.
The loop in code
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
homes = pd.DataFrame({
"home": list("ABCDEFGH"),
"x": [1, 2, 1, 3, 7, 8, 7, 9],
"y": [2, 1, 3, 2, 6, 6, 8, 7]})
H = homes[["x", "y"]].to_numpy(dtype=float)
shops = np.array([[1.0, 2.0], [3.0, 2.0]])
for rnd in range(1, 5):
gap = H[:, None] - shops
dist = np.sqrt((gap ** 2).sum(axis=2))
group = dist.argmin(axis=1)
new = np.array([H[group == k].mean(axis=0)
for k in range(2)])
inertia = ((H - new[group]) ** 2).sum()
print(rnd, "".join(map(str, group)),
new.round(2).tolist(),
round(inertia, 2))
if np.allclose(new, shops):
break
shops = new
1 00011111 [[1.33, 2.0], [6.8, 5.8]] 44.27
2 00001111 [[1.75, 2.0], [7.75, 6.75]] 10.25
3 00001111 [[1.75, 2.0], [7.75, 6.75]] 10.25
dist holds the distance from every home to both shops, and argmin picks the nearest one. That's assign. mean moves each shop to the middle of its homes. That's update. The group string shows home D (the fourth digit) switching from shop 2 to shop 1 in round 2. Round 3 is identical, so the loop breaks.
Let's check the 10.25 by hand:
homes["sq"] = ((H - shops[group]) ** 2).sum(axis=1)
print(homes["sq"].tolist())
print(homes["sq"].sum())
[0.5625, 1.0625, 1.5625, 1.5625, 1.125, 0.625, 2.125, 1.625]
10.25
Eight squared distances, added up, give exactly the inertia.
Customers with no label
Now real data. Each customer has an Instagram visit score (how often they visit our page) and a spending rank from 0 to 100.
df = pd.read_csv("customers.csv")
df.head()
User ID Instagram visit score Spending_rank(0 to 100)
0 0 63 24.050708
1 1 61 25.223290
2 2 104 18.528245
3 3 82 86.890232
4 4 14 31.492397
print(df.shape)
(2600, 3)
2,600 customers, and no label column. Nobody tells us who belongs where.
K-means on all the customers
X = df.iloc[:, 1:]
km = KMeans(n_clusters=4, init="k-means++",
n_init=10, random_state=42)
df["cluster"] = km.fit_predict(X)
print(km.cluster_centers_.round(1))
print(np.bincount(df["cluster"]))
print("inertia:", round(km.inertia_))
[[83.2 19.9]
[39.4 65.1]
[79.6 85. ]
[27.3 24.3]]
[1027 400 600 573]
inertia: 440249
X is the two number columns (we skip User ID). fit_predict runs the whole assign-update loop and gives every customer a cluster number, which we store in a new column. The output shows the four centroids, how many customers landed in each cluster, and the inertia: 440,249.
plt.scatter(X.iloc[:, 0], X.iloc[:, 1],
c=df["cluster"], s=6)
plt.scatter(km.cluster_centers_[:, 0],
km.cluster_centers_[:, 1],
c="red", marker="X", s=200)
plt.xlabel("Instagram visit score")
plt.ylabel("Spending rank")
plt.show()

Every dot is a customer, coloured by its cluster. For now we picked k = 4 just by looking at the data. The next article, Choosing k, shows a better way.
A bad start can get stuck
Why did we write init="k-means++" and n_init=10? Because the answer depends on where the shops start. Here are four purely random starts, one try each, with different seeds:
for seed in [42, 43, 44, 45]:
m = KMeans(n_clusters=4, init="random",
n_init=1, random_state=seed).fit(X)
print("random, seed", seed, round(m.inertia_))
m = KMeans(n_clusters=4, init="k-means++",
n_init=10, random_state=42).fit(X)
print("k-means++, n_init=10", round(m.inertia_))
random, seed 42 673132
random, seed 43 673105
random, seed 44 673132
random, seed 45 440249
k-means++, n_init=10 440249
Seeds 42, 43 and 44 get stuck near 673,000. Only seed 45 finds 440,249. The loop only ever moves shops to a nearby better spot, so a bad start can trap it.
- k-means++ spreads the first centroids far apart, so the start is already sensible.
- n_init=10 runs ten starts and keeps the one with the lowest inertia.
Together they give 440,249 every time.
Scale first, then cluster
K-means only looks at distance. If one column is in years and another in dollars, the dollars win. Six people, three in their twenties and three around sixty:
people = pd.DataFrame({
"name": ["Ann", "Ben", "Cara", "Dan", "Eve", "Finn"],
"age": [22, 25, 24, 61, 58, 63],
"income": [30000, 34000, 32000, 31000, 33000, 35000]})
P = people[["age", "income"]]
Ps = StandardScaler().fit_transform(P)
people["raw"] = KMeans(n_clusters=2, n_init=10,
random_state=42).fit_predict(P)
people["scaled"] = KMeans(n_clusters=2, n_init=10,
random_state=42).fit_predict(Ps)
people
name age income raw scaled
0 Ann 22 30000 0 1
1 Ben 25 34000 1 1
2 Cara 24 32000 0 1
3 Dan 61 31000 0 0
4 Eve 58 33000 1 0
5 Finn 63 35000 1 0
On the raw numbers, Ann, Cara and Dan end up together: that's purely by income, and the ages are mixed. After scaling, the groups are Ann, Ben and Cara against Dan, Eve and Finn: young versus older. A gap of 1,000 dollars beats a gap of 40 years until both columns are on the same scale. See Feature Scaling for how StandardScaler works.
Our customer columns both run from 0 to about 100, so we didn't need to scale them.
Common mistakes
- Clustering columns with different units without scaling. The biggest numbers decide the groups.
- Trusting a single random start. Keep
init="k-means++"andn_initabove 1. - Reading the cluster numbers as an order. Cluster 2 isn't "more" than cluster 0; the numbers are just names.
- Feeding an ID column into
X.User IDis not a measurement, so we dropped it.
Quick recap
| Idea | What it means | In our example |
|---|---|---|
| Centroid | The middle of a group | Shops at (1.75, 2) and (7.75, 6.75) |
| Assign | Every point joins the nearest centroid | dist.argmin(axis=1) |
| Update | Move each centroid to the mean of its points | Shop 2 to (6.8, 5.8) in round 1 |
| Inertia | Sum of squared distances, smaller is tighter | 44.27, then 10.25; customers 440,249 |
| k-means++, n_init | Good starts, several tries | Avoids the stuck 673,132 |
| Scale first | When units differ | Age vs income |
Try it yourself
Run the customers with n_clusters=3, then n_clusters=5. Write down the inertia each time. What happens to it?
The notebook and the dataset are in the StudyEasy AI Community, free to join.
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)Related articles
Choosing k for K-Means: the Elbow Method and the Silhouette Score
K-means always returns exactly k groups, even when k is wrong. Use the elbow plot and the silhouette score to pick k for 2,600 customers, then describe each group in plain words.
Hierarchical Clustering and DBSCAN: Dendrograms, Linkage, eps and Noise
Two more ways to find groups: agglomerative clustering builds a family tree of merges (the dendrogram), and DBSCAN grows clusters from crowds and leaves loners out as noise. Shown on eight homes, 2,600 customers and two moons.
Dimensionality Reduction with PCA: 13 Columns Down to 2
PCA squeezes many columns into a few new ones and keeps most of the information. Reduce 178 wines from 13 columns to 2, see why scaling comes first, pick the number of components and use PCA in a pipeline.
Association Rules and Market Basket Analysis: Support, Confidence, Lift and Apriori
Which items are bought together? Work out support, confidence and lift by hand on eight baskets, then let Apriori in mlxtend find 240 rules in 14,963 real grocery baskets.