“No labels, no right answers – just data, and a machine asked to find the groups hiding in it.”
Everything in Module 2 learned from labelled examples: houses with known prices, emails already marked spam, tumours with a diagnosis. Real life rarely hands you labels. A shop has thousands of customer records but no column called “customer type”. A news site has a million articles but nobody has tagged their topics.
This is where unsupervised learning begins, and its most common job is clustering: grouping similar data points together so that points in the same group are close and points in different groups are far apart. Module 3 starts with the two classic clustering algorithms. K-means is fast, simple and everywhere. Hierarchical clustering builds a whole family tree of groups you can cut at any level.
K-means: the core idea

Imagine you are opening k delivery hubs in a city and every customer is served by the nearest hub. You put the hubs somewhere, see which customers each one serves, then move each hub to the middle of its customers. Some customers are now closer to a different hub, so you reassign them, and move the hubs again. After a few rounds the hubs stop moving. That is K-means:
- Choose k, the number of clusters, and place k centroids (cluster centres), usually on randomly chosen points.
- Assign every point to its nearest centroid.
- Move each centroid to the mean of the points assigned to it.
- Repeat steps 2 and 3 until the assignments stop changing.
Each round can only lower one number, the inertia: the total squared distance from every point to its own centroid (also called the within-cluster sum of squares, WCSS):
inertia = Σ ‖xᵢ − μ(cluster of xᵢ)‖²
Low inertia means tight, compact clusters. K-means is simply a fast way to find centroids that make it small.
Step 1: K-means from scratch
Seven points, two clusters, written out in NumPy so every step is visible:
import numpy as np
X = np.array([[1, 1], [1.5, 2], [3, 4], [5, 7], [3.5, 5], [4.5, 5], [3.5, 4.5]])
centroids = X[[0, 3]].copy() # start with 2 points as initial centroids
for step in range(1, 10):
# 1) assign every point to its nearest centroid
distances = np.linalg.norm(X[:, None] - centroids[None], axis=2)
labels = distances.argmin(axis=1)
# 2) move each centroid to the mean of its points
new_centroids = np.array([X[labels == k].mean(axis=0) for k in range(2)])
inertia = ((X - new_centroids[labels]) ** 2).sum()
print(f"step {step}: labels={labels} centroids={new_centroids.round(2).tolist()} "
f"inertia={inertia:.2f}")
if np.allclose(new_centroids, centroids):
break # nothing moved: converged
centroids = new_centroids
Output:
step 1: labels=[0 0 0 1 1 1 1] centroids=[[1.83, 2.33], [4.12, 5.38]] inertia=12.21
step 2: labels=[0 0 1 1 1 1 1] centroids=[[1.25, 1.5], [3.9, 5.1]] inertia=8.53
step 3: labels=[0 0 1 1 1 1 1] centroids=[[1.25, 1.5], [3.9, 5.1]] inertia=8.53
What’s actually happening here
We seeded the centroids at (1, 1) and (5, 7). In step 1, the point (3, 4) is slightly closer to the first centroid, so it joins cluster 0. Then both centroids move to the mean of their points. In step 2, the first centroid has moved to (1.83, 2.33), and now (3, 4) is closer to the second cluster, so it switches sides. Inertia drops from 12.21 to 8.53. In step 3 nothing changes, so the algorithm stops. The result: a small cluster around (1.25, 1.5) and a larger one around (3.9, 5.1). The line distances.argmin is the “assign” step and .mean(axis=0) is the “move” step; that is the whole algorithm.
Step 2: Choosing k with the elbow and silhouette

K-means needs you to pick k up front. Two standard checks help.
The elbow method: train K-means for a range of k and plot inertia. Inertia always falls as k grows (with k equal to the number of points it reaches zero), but it falls steeply while you are splitting real groups and slowly once you start splitting real groups into pieces. The bend, the “elbow”, is a good k.
The silhouette score measures, for each point, how much closer it is to its own cluster than to the nearest other cluster:
s = (b − a) / max(a, b)
a = average distance to points in its own cluster
b = average distance to points in the nearest other cluster
It runs from −1 to 1. Close to 1 means well separated, around 0 means sitting on a border, and negative means the point is probably in the wrong cluster. Average it over all points, and pick the k with the highest score.
Here are 300 simulated shop customers described by visits per month and average spend:
import numpy as np
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
from sklearn.preprocessing import StandardScaler
# 300 shop customers: [visits per month, average spend in Rs. '000]
rng = np.random.default_rng(0)
groups = [(2, 3, 100), (12, 4, 100), (5, 25, 60), (14, 22, 40)] # centre visits, spend, count
X = np.vstack([rng.normal([v, s], [1.5, 2.5], (n, 2)) for v, s, n in groups])
X_scaled = StandardScaler().fit_transform(X)
for k in range(2, 8):
km = KMeans(n_clusters=k, n_init=10, random_state=0).fit(X_scaled)
print(f"k={k} inertia={km.inertia_:7.1f} silhouette={silhouette_score(X_scaled, km.labels_):.3f}")
Output:
k=2 inertia= 314.7 silhouette=0.505
k=3 inertia= 126.3 silhouette=0.645
k=4 inertia= 44.0 silhouette=0.730
k=5 inertia= 38.3 silhouette=0.596
k=6 inertia= 32.9 silhouette=0.469
k=7 inertia= 28.6 silhouette=0.399
What’s actually happening here
Inertia drops from 315 to 126 to 44, then barely moves (38, 33, 29). That bend at k = 4 is the elbow. The silhouette score agrees, peaking at 0.730 for k = 4 and falling after it. On real data the two don’t always agree this neatly; then let business sense break the tie. Four customer segments that a marketing team can act on beat seven that nobody can tell apart.
Notice StandardScaler again. K-means uses Euclidean distance, so if spend were in rupees (thousands) and visits in single digits, spend would decide everything. Scale first.
Step 3: Turning clusters into segments

The algorithm returns cluster numbers. Turning them into something useful is your job:
import numpy as np
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
rng = np.random.default_rng(0)
groups = [(2, 3, 100), (12, 4, 100), (5, 25, 60), (14, 22, 40)]
X = np.vstack([rng.normal([v, s], [1.5, 2.5], (n, 2)) for v, s, n in groups])
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
km = KMeans(n_clusters=4, n_init=10, random_state=0).fit(X_scaled)
centres = scaler.inverse_transform(km.cluster_centers_) # back to real units
for i, (visits, spend) in enumerate(centres):
size = (km.labels_ == i).sum()
print(f"cluster {i}: {size:>3} customers, {visits:4.1f} visits/month, Rs. {spend:4.1f}k average spend")
Output:
cluster 0: 100 customers, 11.8 visits/month, Rs. 3.9k average spend
cluster 1: 60 customers, 4.8 visits/month, Rs. 25.5k average spend
cluster 2: 100 customers, 1.9 visits/month, Rs. 3.3k average spend
cluster 3: 40 customers, 14.1 visits/month, Rs. 21.7k average spend
What’s actually happening here
inverse_transform converts the scaled centroids back into real units so a human can read them. Now the groups have meaning: cluster 3 are big-ticket regulars (14 visits, Rs. 21.7k each time), cluster 1 occasional big spenders, cluster 0 frequent low spenders, and cluster 2 occasional low spenders. Each gets a different campaign: loyalty rewards for the regulars, reminders for the occasional big spenders, upselling for the frequent low spenders. The cluster numbers themselves are arbitrary and can change between runs; the groups are what matter.
Step 4: Bad starts and local optima
K-means always converges, but not always to the best answer. It walks downhill from wherever the centroids start, and a bad start can leave it stuck in a local optimum: for example, two centroids sharing one real group while another centroid has to cover two groups at once. Here are five single random starts against the default:
import numpy as np
from sklearn.cluster import KMeans
rng = np.random.default_rng(0)
groups = [(2, 3, 100), (12, 4, 100), (5, 25, 60), (14, 22, 40)]
X = np.vstack([rng.normal([v, s], [1.5, 2.5], (n, 2)) for v, s, n in groups])
for seed in range(5): # one random start each, no k-means++
km = KMeans(n_clusters=4, init="random", n_init=1, random_state=seed).fit(X)
print(f"random start {seed}: inertia = {km.inertia_:8.1f}")
best = KMeans(n_clusters=4, init="k-means++", n_init=10, random_state=0).fit(X)
print(f"k-means++, 10 starts: inertia = {best.inertia_:8.1f}")
Output:
random start 0: inertia = 4505.3
random start 1: inertia = 4505.5
random start 2: inertia = 4460.5
random start 3: inertia = 4460.5
random start 4: inertia = 7297.1
k-means++, 10 starts: inertia = 2479.1
What’s actually happening here
(This run skips scaling to keep the example short, so the inertia values are in raw units and not comparable with Step 2.) Every one of the five random starts got stuck in a worse solution, with inertia of 4,460 or more; seed 4 was especially unlucky. The default setup reaches 2,479. It uses two fixes, and you should always keep them on:
- k-means++ initialisation spreads the starting centroids out: each new centroid is picked with probability proportional to its squared distance from the centroids already chosen.
- Multiple restarts (
n_init=10) run the whole algorithm ten times from different starts and keep the run with the lowest inertia.
Hierarchical clustering: a family tree of groups

K-means makes you commit to k before you start. Hierarchical clustering builds every level of grouping at once. The common bottom-up version, agglomerative clustering, works like this:
- Start with every point as its own cluster.
- Find the two closest clusters and merge them.
- Repeat until everything is one cluster.
The history of those merges is drawn as a dendrogram, a tree whose branch heights show how far apart two clusters were when they merged. To get clusters, you cut the tree horizontally: a cut that crosses two vertical lines gives two clusters, a lower cut gives more. You choose k after seeing the structure, which is the method’s big advantage. The top-down alternative, divisive clustering, starts with one cluster and keeps splitting it; it is rarer in practice.
There is one decision to make: how to measure the distance between two clusters, not just two points. That choice is the linkage:
- Single linkage: the distance between the two closest points, one from each cluster. Follows chains and odd shapes, but can join groups through a thin bridge of points.
- Complete linkage: the distance between the two farthest points. Produces compact, evenly sized clusters.
- Average linkage: the mean distance over all pairs. A compromise between the two.
- Ward’s method: merges the pair that increases total within-cluster variance the least. Similar in spirit to K-means, and scikit-learn’s default.
Step 5: Watching the merges
Five numbers on a line, merged under each linkage:
import numpy as np
from scipy.cluster.hierarchy import linkage
values = [1, 2, 6, 7, 15]
points = np.array(values).reshape(-1, 1)
for method in ["single", "complete", "average", "ward"]:
Z = linkage(points, method=method)
clusters = {i: [v] for i, v in enumerate(values)} # scipy numbers new clusters n, n+1, ...
steps = []
for i, (a, b, dist, _) in enumerate(Z):
merged = clusters.pop(int(a)) + clusters.pop(int(b))
clusters[len(values) + i] = merged
steps.append(f"{merged} @ {dist:.1f}")
print(f"{method:<8}: " + " -> ".join(steps))
Output:
single : [1, 2] @ 1.0 -> [6, 7] @ 1.0 -> [1, 2, 6, 7] @ 4.0 -> [15, 1, 2, 6, 7] @ 8.0
complete: [1, 2] @ 1.0 -> [6, 7] @ 1.0 -> [1, 2, 6, 7] @ 6.0 -> [15, 1, 2, 6, 7] @ 14.0
average : [1, 2] @ 1.0 -> [6, 7] @ 1.0 -> [1, 2, 6, 7] @ 5.0 -> [15, 1, 2, 6, 7] @ 11.0
ward : [1, 2] @ 1.0 -> [6, 7] @ 1.0 -> [1, 2, 6, 7] @ 7.1 -> [15, 1, 2, 6, 7] @ 13.9
What’s actually happening here
SciPy’s linkage returns the merge history as a table; the loop just translates its cluster numbers back into the original values. All four methods merge in the same order here, but at different heights, and that is the linkage at work. Joining {1, 2} with {6, 7}: single linkage uses the closest pair (6 − 2 = 4), complete uses the farthest pair (7 − 1 = 6), and average uses the mean of all four pair distances (5, 6, 4, 5 → 5). On real data, different heights mean different merge orders and different clusters. To draw the tree, pass Z to scipy.cluster.hierarchy.dendrogram with matplotlib; to get labels for a chosen number of clusters, use fcluster or scikit-learn’s AgglomerativeClustering.
Step 6: When cluster shape matters

K-means assumes clusters are roughly round blobs of similar size around a centre. Here is data where that is false: two interlocking crescents.
from sklearn.cluster import AgglomerativeClustering, KMeans
from sklearn.datasets import make_moons
from sklearn.metrics import adjusted_rand_score
X, true_groups = make_moons(n_samples=300, noise=0.05, random_state=0) # two interlocking crescents
models = {
"k-means (k=2)": KMeans(n_clusters=2, n_init=10, random_state=0),
"hierarchical, ward": AgglomerativeClustering(n_clusters=2, linkage="ward"),
"hierarchical, single link": AgglomerativeClustering(n_clusters=2, linkage="single"),
}
for name, model in models.items():
labels = model.fit_predict(X)
print(f"{name:<27} agreement with true shapes (ARI) = {adjusted_rand_score(true_groups, labels):.3f}")
Output:
k-means (k=2) agreement with true shapes (ARI) = 0.241
hierarchical, ward agreement with true shapes (ARI) = 0.241
hierarchical, single link agreement with true shapes (ARI) = 1.000
What’s actually happening here
The adjusted Rand index (ARI) compares a clustering with known true groups: 1.0 is a perfect match, around 0 is no better than random. We only know the true groups here because the data is synthetic; in real unsupervised work you won’t have them.
K-means and Ward both cut the crescents with a straight line (ARI 0.241), because both look for compact, round clusters. Single linkage chains each point to its nearest neighbour, so it follows each crescent along its length and recovers both perfectly. The same chaining makes single linkage fragile when noise points form a bridge between groups, which is exactly the problem DBSCAN in Ep08 is designed for.
K-means vs hierarchical: when to use which
- K-means when you have a lot of data, a rough idea of k (or can test a range), and clusters that are reasonably compact: customer segmentation, grouping tweets or documents by topic vectors, compressing image colours to k shades, and as a fast first look at any dataset.
- Hierarchical clustering when the dataset is small to medium, you don’t know k, or the hierarchy itself is the answer: taxonomies (species, genes, product categories), grouping animals by habitat and behaviour, organising documents into topics and sub-topics, and exploring data before committing to a k.
Common first-time mistakes
- Not scaling features. Both methods are distance-based; the feature with the biggest units wins.
- Trusting one K-means run. Keep
n_initat 10 or more with k-means++, and setrandom_stateif you need reproducible cluster numbers. - Picking k only by the elbow. Elbows are often vague. Check silhouette scores and whether the clusters make sense to the people who will use them.
- Feeding raw categorical data to K-means. The “mean” of city names doesn’t exist. Encode carefully, or use methods built for categories, such as k-modes.
- Running hierarchical clustering on huge datasets. It needs the distance between every pair of points, so memory grows with the square of the number of rows. Fine for thousands, painful for hundreds of thousands.
- Treating cluster numbers as meaningful. Cluster 0 isn’t “first” or “best”; inspect the centroids or summary statistics to name each group.
The honest limitations
K-means assumes round clusters of similar size and density, needs k in advance, is pulled around by outliers (every point, however strange, must belong to some cluster), and works only with numeric data where averages make sense. Hierarchical clustering scales poorly, can’t undo a bad early merge, and its results depend heavily on the linkage you choose. Neither one tells you whether the clusters it finds are real rather than artefacts of the method. Clustering is exploratory: validate groups with domain knowledge, stability checks (do they survive a different sample?) and business usefulness.
Where to go next
- scikit-learn: Clustering user guide, covering K-means, agglomerative clustering, linkages and clustering metrics.
- SciPy: hierarchical clustering, covering
linkage,dendrogramandfcluster.
K-means forces every point into a cluster and needs k up front, and single linkage breaks when noise connects groups. Ep08 fixes both. DBSCAN finds clusters as dense regions of any shape, works out how many there are by itself, and labels isolated points as outliers instead of forcing them into a group. Gaussian mixture models replace hard assignments with probabilities, so a customer can be 70% “regular” and 30% “big spender”.
This post is part of the CeyTech series Machine Learning: From 0 to Machine – deep tech, no fluff. Try running the customer example without StandardScaler, or cut the dendrogram at 3 clusters, and tell me what changed.

Comments (...)
You must be signed in to join the discussion.