Concept Explanation
Supervised learning needs a correct answer for every row. Most real data does not have one. You have 50,000 customers and no column saying which segment each belongs to — nobody ever labelled them.
Unsupervised learning finds structure in X with no y at all. There is no accuracy score, because there is nothing to be accurate against. You are asking the data to organise itself, then judging whether the organisation is useful.
Two families cover most practical work:
| Family | Question | Workhorse |
|---|---|---|
| Clustering | "Which rows belong together?" | K-Means, DBSCAN, hierarchical |
| Dimensionality reduction | "Can I describe this with fewer numbers?" | PCA, t-SNE, UMAP |
K-Means: The One to Learn First
K-Means partitions your data into exactly k groups by repeating two steps until nothing moves:
- Assign every point to the nearest centroid.
- Move each centroid to the mean of its assigned points.
from sklearn.cluster import KMeans
km = KMeans(n_clusters=4, n_init=10, random_state=42).fit(X)
km.labels_ # cluster id per row
km.cluster_centers_ # the k centroids
km.inertia_ # total squared distance to assigned centroids
Its assumptions matter, because they are also its failure modes: clusters are spherical, similar in size, and you must know k in advance. Feed it two crescent moons and it will slice straight through both.
Choosing k
You have two standard tools, and they disagree often enough that you should run both.
The elbow method plots inertia_ against k. Inertia always falls as k rises (at k = n it reaches zero), so you look for the bend where extra clusters stop paying for themselves.
The silhouette score measures, for each point, how much closer it is to its own cluster than to the next nearest, averaged over all points:
| Silhouette | Reading |
|---|---|
| ~1.0 | Dense, well-separated clusters |
| ~0.5 | Reasonable structure |
| ~0.0 | Points sit on the boundary — clusters overlap |
| Negative | Points are likely in the wrong cluster |
Unlike inertia, silhouette has a genuine maximum, which makes it the more decisive of the two.
DBSCAN: When You Do Not Know k
DBSCAN groups by density instead of distance to a centre. It finds however many clusters exist, handles arbitrary shapes, and — uniquely — labels outliers as -1 rather than forcing them into a group.
from sklearn.cluster import DBSCAN
db = DBSCAN(eps=0.4, min_samples=8).fit(X)
The price is two parameters that need tuning: eps (neighbourhood radius) and min_samples (how many neighbours make a dense region). Set eps too small and everything is noise; too large and everything is one cluster.
PCA: Fewer Columns, Same Information
PCA finds new axes ordered by how much variance they capture, then lets you keep only the first few. Two uses:
- Visualisation: squeeze 30 features into 2 so you can plot them.
- Compression: keep 95% of the variance with a third of the columns, which speeds up everything downstream.
from sklearn.decomposition import PCA
pca = PCA(n_components=0.95) # keep enough components for 95% of variance
X_small = pca.fit_transform(X_scaled)
Scaling is mandatory for both K-Means and PCA. Both are driven by variance and distance, so a column measured in thousands will simply outvote a column measured in units.
Code Example #1 (Basic)
Cluster, then check whether the clustering means anything.
import numpy as np
from sklearn.datasets import make_blobs
from sklearn.preprocessing import StandardScaler
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
# 4 true groups -- but we will pretend we do not know that
X, y_true = make_blobs(n_samples=600, centers=4, cluster_std=1.1, random_state=42)
X = StandardScaler().fit_transform(X)
print(f"{'k':>3} {'inertia':>10} {'silhouette':>11}")
for k in range(2, 9):
km = KMeans(n_clusters=k, n_init=10, random_state=42).fit(X)
sil = silhouette_score(X, km.labels_)
print(f"{k:>3} {km.inertia_:>10.1f} {sil:>11.3f}")
# The silhouette peak is the recommendation
best_k = max(range(2, 9),
key=lambda k: silhouette_score(
X, KMeans(n_clusters=k, n_init=10, random_state=42).fit_predict(X)))
print(f"\nBest k by silhouette: {best_k}")
km = KMeans(n_clusters=best_k, n_init=10, random_state=42).fit(X)
sizes = np.bincount(km.labels_)
print("Cluster sizes:", sizes)
print("Centroids:\n", km.cluster_centers_.round(2))
n_init=10 runs the algorithm ten times from different random starts and keeps the best. K-Means can converge to a poor local optimum, so a single start is a gamble.
Code Example #2 (Intermediate)
Customer segmentation: PCA for the picture, K-Means for the groups, DBSCAN for the shapes K-Means cannot see.
import numpy as np
import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.cluster import KMeans, DBSCAN
from sklearn.metrics import silhouette_score
from sklearn.datasets import make_moons
rng = np.random.default_rng(3)
# --- Build a plausible customer table with three hidden segments ---
def segment(n, spend, freq, tenure, recency):
return pd.DataFrame({
"monthly_spend": rng.normal(spend, spend * 0.18, n).clip(1).round(2),
"orders_per_month": rng.normal(freq, freq * 0.25, n).clip(0.1).round(2),
"tenure_months": rng.normal(tenure, 8, n).clip(1).round(0),
"days_since_order": rng.normal(recency, recency * 0.3, n).clip(0).round(0),
})
df = pd.concat([
segment(400, 28, 1.2, 14, 45), # occasional
segment(260, 145, 6.0, 38, 6), # loyal
segment(140, 640, 2.1, 9, 20), # big-ticket
], ignore_index=True)
features = list(df.columns)
X = StandardScaler().fit_transform(df[features])
# --- PCA: how many dimensions do we actually need? ---
pca_full = PCA().fit(X)
cum = np.cumsum(pca_full.explained_variance_ratio_)
print("Cumulative variance by component:", cum.round(3))
print(f"Components for 95% variance: {np.searchsorted(cum, 0.95) + 1} of {len(features)}\n")
X_2d = PCA(n_components=2).fit_transform(X) # for plotting only
# --- K-Means, with k chosen by silhouette ---
scores = {k: silhouette_score(X, KMeans(k, n_init=10, random_state=1).fit_predict(X))
for k in range(2, 7)}
best_k = max(scores, key=scores.get)
print("silhouette by k:", {k: round(v, 3) for k, v in scores.items()})
print(f"chosen k = {best_k}\n")
df["segment"] = KMeans(best_k, n_init=10, random_state=1).fit_predict(X)
# --- Profile the segments: this is the step that creates business value ---
profile = df.groupby("segment").agg(
customers=("monthly_spend", "size"),
avg_spend=("monthly_spend", "mean"),
avg_orders=("orders_per_month", "mean"),
avg_tenure=("tenure_months", "mean"),
avg_recency=("days_since_order", "mean"),
).round(1)
print(profile.to_string())
print()
# --- DBSCAN on a shape K-Means cannot handle ---
moons, _ = make_moons(n_samples=400, noise=0.06, random_state=0)
moons = StandardScaler().fit_transform(moons)
km_labels = KMeans(2, n_init=10, random_state=0).fit_predict(moons)
db_labels = DBSCAN(eps=0.3, min_samples=6).fit_predict(moons)
n_db = len(set(db_labels) - {-1})
print("Two interleaved crescents:")
print(f" KMeans silhouette: {silhouette_score(moons, km_labels):.3f} (cuts straight through both)")
print(f" DBSCAN found {n_db} clusters, {(db_labels == -1).sum()} points marked as noise")
The profile table is the actual deliverable. segment=2 on its own is meaningless to a marketing team; "382 customers averaging £640 a month who order twice and then go quiet" is something they can act on. Clustering produces labels; you produce the interpretation.
Common Mistakes
- Not scaling first: with
salaryin tens of thousands andagein tens, K-Means clusters on salary alone and ignores everything else. - Trusting the elbow blindly: inertia falls monotonically, so there is often no clear bend. Cross-check with silhouette.
- Assuming clusters are real: K-Means will happily split uniform random noise into 5 tidy groups. Always ask whether the silhouette score supports the structure.
- Using K-Means on non-spherical clusters: crescents, rings, and long thin groups need DBSCAN or a hierarchical method.
- Leaving
n_init=1: a single random start can converge somewhere poor. Modern scikit-learn defaults ton_init="auto"; set it explicitly and stop guessing. - Treating DBSCAN's
-1as a cluster: it means "noise". Filter it out before profiling. - Reading PCA components as real quantities:
PC1is a weighted blend of your columns, not a measurable thing. It is useful, not meaningful. - Using t-SNE distances as truth: t-SNE preserves local neighbourhoods, not global distance. Cluster before t-SNE and use the plot only to look.
- Stopping at the labels: the numbers 0, 1, 2 are worthless until you profile each group and give it a name.
Best Practices
- Scale before every distance- or variance-based method:
StandardScalerfor K-Means, PCA, and DBSCAN alike. - Choose
kwith evidence: run the silhouette score across a range and record why you chose what you chose. - Profile every cluster with
groupby().agg()and name it in plain language before you show anyone. - Try DBSCAN as a sanity check: if it finds nothing but noise, your "clusters" may not exist.
- Use PCA to two components for plotting — a scatter coloured by cluster reveals overlap that no score summarises.
- Keep the feature list small and deliberate: irrelevant columns add distance that means nothing, which dilutes real structure.
- Set
random_stateso today's segment 2 is the same as yesterday's. - Validate against something external if you can: do the segments predict churn or lifetime value? A clustering that correlates with nothing you care about is not useful.
- Cluster on the scaled data, report on the original units: nobody wants a segment described as "spend = 1.8 standard deviations".
Practice Exercises
- The k Hunt: Use
make_blobswith 5 centres, hide the true labels, and findkusing both the elbow and the silhouette method. Record which one pointed at 5 more clearly. - The Segment Report: Build a DataFrame of at least 300 fake customers with 4 numeric features, cluster it, then produce a
groupbyprofile table and write a one-sentence business name for each cluster. - The Shape Test: Run K-Means and DBSCAN on
make_moons(noise=0.05). Plot both results side by side and explain in a comment exactly which K-Means assumption the crescents violate.