Lab: Segment Customers and Defend the Segments
Segment 2,000 synthetic shop customers: log-transform and scale recency, frequency, spend and tenure, scan k with inertia and silhouette, compare k-means with DBSCAN and a Gaussian mixture, profile each segment in real units, and test the chosen segments with bootstrap refits.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: Generate the customer table
- Step 2: Transform and scale the features
- Step 3: Scan k with k-means
- Step 4: Compare with DBSCAN and a Gaussian mixture
- Step 5: Profile the segments
- Step 6: Test the segments for stability
- Check your understanding
- Apply it: stretch tasks
- Review prompt
Lessons of Unsupervised Learning
- Clustering: Centroids, Mixtures, Hierarchies and Density Concept · 25 min
- Lab: Segment Customers and Defend the Segments Lab · 30 min
- PCA: Finding the Directions That Matter Concept · 20 min
- Worked Example: Catching Anomalies with an Isolation Forest Worked example · 20 min
- Lab: Recommendations from Interaction Data with Matrix Factorization Lab · 30 min
- Check: Structure Without Labels Knowledge check · 8 questions
What you will learn
- Apply k-means, Gaussian mixture models, hierarchical clustering and DBSCAN, choosing the algorithm and its parameters from the data's shape, and validate clusters with silhouette scores and segment profiles.
01. Goal and setup
A segmentation is only useful if you can defend it: explain why this number of segments, why this algorithm, what each segment is, and show that the segments do not change when the data changes a little. In this lab you segment 2,000 synthetic customers of an online shop and build that defence step by step: transform and scale the features, scan k with k-means, compare with DBSCAN and a Gaussian mixture, write a profile of each segment, and test the segments' stability with bootstrap refits.
The data is generated with a fixed seed, so your numbers will match the expected output. It has four columns that a real shop would compute from its order history: days since the last order (recency), orders in the last 12 months (frequency), spend in the last 12 months, and months since the first order (tenure). This lesson builds on Clustering: Centroids, Mixtures, Hierarchies and Density.
You need: Python 3.12, scikit-learn 1.9, pandas 3.1 and NumPy 2.5. Each script runs in a few seconds.
segment-lab/
├── data/customers.csv written by step 1
├── data/segments.csv written by step 5
├── make_data.py step 1: generate the customer table
├── prepare.py step 2: log-transform and scale
├── choose_k.py step 3: inertia and silhouette over k
├── compare.py step 4: DBSCAN and a Gaussian mixture
├── profile.py step 5: one profile row per segment
└── stability.py step 6: bootstrap refits and ARImkdir segment-lab && cd segment-lab
python3.12 -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
python -m pip install "scikit-learn==1.9.*" "pandas==3.1.*"02. Step 1: Generate the customer table
The generator draws four latent groups of customers with different habits, mixes them and writes the table without the group labels, as a real export would arrive. The summary adds the skew of each column, a measure of asymmetry: 0 for a symmetric distribution, positive when a long tail stretches to the right.
"""Write data/customers.csv: 2,000 synthetic customers with a fixed seed."""
from pathlib import Path
import numpy as np
import pandas as pd
rng = np.random.default_rng(7)
# share, days since last order (min, mean extra), mean orders, order value, tenure
GROUPS = [(0.20, (0, 8), 26, 70, (24, 96)),
(0.35, (0, 30), 9, 45, (12, 72)),
(0.30, (0, 75), 3, 22, (3, 36)),
(0.15, (150, 80), 2, 40, (24, 96))]
parts = []
for share, (r_min, r_mean), orders, value, (t_lo, t_hi) in GROUPS:
n = int(2000 * share)
n_orders = rng.poisson(orders, n) + 1
parts.append(pd.DataFrame({
"recency_days": np.minimum(r_min + rng.exponential(r_mean, n).round() + 1, 365),
"orders_12m": n_orders,
"spend_12m": (n_orders * value * rng.lognormal(0, 0.35, n)).round(2),
"tenure_months": rng.integers(t_lo, t_hi + 1, n),
}))
df = pd.concat(parts, ignore_index=True).sample(frac=1, random_state=0)
df.insert(0, "customer_id", [f"C{i:04d}" for i in range(len(df))])
Path("data").mkdir(exist_ok=True)
df.to_csv("data/customers.csv", index=False)
print(df.shape)
summary = df.describe().loc[["min", "50%", "max"]]
summary.loc["skew"] = df.skew(numeric_only=True)
print(summary.round(1).to_string())python make_data.py(2000, 5)
recency_days orders_12m spend_12m tenure_months
min 1.0 1.0 13.0 3.0
50% 29.0 7.0 273.4 36.0
max 365.0 42.0 6496.0 96.0
skew 1.6 1.3 2.3 0.4Spend has a skew of 2.3: the median customer spent £273, the biggest £6,496. Recency and order counts are skewed too. Tenure, drawn from uniform ranges, is close to symmetric.
03. Step 2: Transform and scale the features
k-means, GMMs and DBSCAN all compare distances, so the features need two fixes. First, a skewed column puts most customers in a narrow band and a few far away, and those few then dominate squared distances and drag centres towards them. np.log1p, the logarithm of 1 + x, compresses the long tail and is safe for zeros. Second, StandardScaler gives every column mean 0 and standard deviation 1, so a difference of one standard deviation in recency counts as much as one in spend. The transform lives in one function that every later script imports.
import numpy as np
import pandas as pd
from sklearn.preprocessing import StandardScaler
FEATURES = ["recency_days", "orders_12m", "spend_12m", "tenure_months"]
SKEWED = ["recency_days", "orders_12m", "spend_12m"]
def load():
"""Customers, plus the log-transformed and standardised feature matrix."""
df = pd.read_csv("data/customers.csv")
X = df[FEATURES].copy()
X[SKEWED] = np.log1p(X[SKEWED])
return df, StandardScaler().fit_transform(X)
if __name__ == "__main__":
df, X = load()
print("skew before:", df[FEATURES].skew().round(2).to_list())
print("skew after: ", pd.DataFrame(X, columns=FEATURES).skew().round(2).to_list())
print("column means ~ 0:", np.allclose(X.mean(axis=0), 0),
"| column stds:", X.std(axis=0).round(2))python prepare.pyskew before: [1.57, 1.26, 2.31, 0.42]
skew after: [-0.02, 0.21, 0.18, 0.42]
column means ~ 0: True | column stds: [1. 1. 1. 1.]The log brings the three skewed columns close to symmetric, and scaling puts all four on the same footing. Scaling alone would not do the first job: it changes the units of a column, not the shape of its distribution. Tenure was left unlogged because it was not skewed.
04. Step 3: Scan k with k-means
Fit k-means for k = 2 to 8 and record two numbers. Inertia, the sum of squared distances to the nearest centre, keeps falling as k grows, so you look for the elbow, where the fall slows down. The silhouette, from the previous lesson, rewards compact and well-separated clusters.
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
from prepare import load
df, X = load()
print(" k inertia silhouette")
for k in range(2, 9):
km = KMeans(k, n_init=10, random_state=0).fit(X)
print(f"{k:2d} {km.inertia_:9.0f} {silhouette_score(X, km.labels_):11.3f}")python choose_k.py k inertia silhouette
2 4251 0.390
3 3245 0.350
4 2433 0.340
5 2097 0.322
6 1816 0.315
7 1595 0.314
8 1458 0.308Inertia falls by 1,006 from k = 2 to 3 and by 812 from 3 to 4, then by only 336 from 4 to 5: an elbow at four. Silhouette is highest at k = 2 (0.390) and declines slowly. The two signals disagree, which is common, and neither is decisive on its own: the elbow is a judgement call and silhouette tends to favour few, broad clusters. Keep k = 2 and k = 4 as candidates and gather more evidence.
05. Step 4: Compare with DBSCAN and a Gaussian mixture
Next, check whether another idea of a cluster tells a different story. DBSCAN gets min_samples = 8, twice the number of features, and values of eps around the percentiles of the 8th-neighbour distance. A Gaussian mixture is compared across k by BIC, with n_init=3 restarts each, and at k = 4 its labels are compared with k-means by ARI.
import numpy as np
from sklearn.cluster import DBSCAN, KMeans
from sklearn.metrics import adjusted_rand_score
from sklearn.mixture import GaussianMixture
from sklearn.neighbors import NearestNeighbors
from prepare import load
df, X = load()
kmeans4 = KMeans(4, n_init=10, random_state=0).fit_predict(X)
# DBSCAN: min_samples = 2 x 4 features; eps from the 8th-neighbour distances
dist, _ = NearestNeighbors(n_neighbors=8).fit(X).kneighbors(X)
print("8th-neighbour distance p50/p90/p99:",
np.percentile(dist[:, -1], [50, 90, 99]).round(2))
for eps in [0.4, 0.5, 0.6]:
labels = DBSCAN(eps=eps, min_samples=8).fit_predict(X)
sizes = np.bincount(labels[labels >= 0])
print(f"DBSCAN eps {eps}: clusters {len(sizes)}, noise {np.mean(labels == -1):.1%},"
f" largest cluster {sizes.max() / len(X):.1%}")
# Gaussian mixture: BIC over k, then agreement with k-means at k = 4
for k in range(2, 7):
gmm = GaussianMixture(k, n_init=3, random_state=0).fit(X)
line = f"GMM k = {k}: BIC {gmm.bic(X):7.0f}"
if k == 4:
ari = adjusted_rand_score(kmeans4, gmm.predict(X))
line += f" ARI with k-means k = 4: {ari:.2f}"
print(line)python compare.py8th-neighbour distance p50/p90/p99: [0.38 0.54 0.75]
DBSCAN eps 0.4: clusters 5, noise 15.3%, largest cluster 66.8%
DBSCAN eps 0.5: clusters 2, noise 4.2%, largest cluster 94.9%
DBSCAN eps 0.6: clusters 1, noise 1.2%, largest cluster 98.8%
GMM k = 2: BIC 16315
GMM k = 3: BIC 15438
GMM k = 4: BIC 15054 ARI with k-means k = 4: 0.78
GMM k = 5: BIC 15064
GMM k = 6: BIC 15102DBSCAN finds no segments. At eps 0.4 it calls 15.3% of customers noise and leaves two-thirds in one cluster; at 0.5 and 0.6 almost everyone joins a single cluster. Customer groups here blend into each other without empty space between them, so density has no gap to follow. That is typical of behavioural data, and it is useful to know: DBSCAN's noise points are still worth a look as unusual customers, but not as a segmentation.
The mixture agrees with k-means. Its BIC is lowest at k = 4 (15,054, just below 15,064 at k = 5), and its four components match the k-means segments with an ARI of 0.78. Two methods with different assumptions point to about four groups.
06. Step 5: Profile the segments
A segment profile describes each cluster in the original units, so that a marketing team can read it. Fit k-means with k = 4, group the raw table by segment and report each segment's share of customers, the median of each feature and its share of total spend. Medians resist the remaining outliers better than means. The script also saves the segment of every customer for later lessons.
import pandas as pd
from sklearn.cluster import KMeans
from prepare import FEATURES, load
df, X = load()
df["segment"] = KMeans(4, n_init=10, random_state=0).fit_predict(X)
profile = df.groupby("segment")[FEATURES].median()
profile.insert(0, "share", df["segment"].value_counts(normalize=True))
spend = df.groupby("segment")["spend_12m"].sum()
profile["spend_share"] = spend / spend.sum()
pd.set_option("display.width", 100)
print(profile.round(2).to_string())
df[["customer_id", "segment"]].to_csv("data/segments.csv", index=False)python profile.py share recency_days orders_12m spend_12m tenure_months spend_share
segment
0 0.33 20.0 10.0 445.43 39.0 0.26
1 0.32 59.0 4.0 87.42 20.0 0.05
2 0.14 206.0 3.0 109.54 67.0 0.03
3 0.21 6.0 26.5 1827.61 61.0 0.66Each row has a clear meaning, so you can name it:
- segment 3, loyal high spenders (21% of customers, 66% of spend): ordered 6 days ago, 26.5 orders a year, £1,828 median spend, five years of tenure;
- segment 0, regulars (33%): ordered 20 days ago, 10 orders, £445;
- segment 1, new and occasional (32%): 4 orders and £87, with the shortest tenure, 20 months;
- segment 2, lapsing (14%): long-standing customers (67 months) whose last order was 206 days ago.
These profiles turn into actions: protect segment 3, win back segment 2, grow segment 1. The k = 2 solution from step 3 cannot support that: it puts the loyal customers and most regulars on one side and everyone else on the other, so a new customer and a lapsing one get the same label. The cluster numbers themselves are arbitrary and can change with the seed or the library version, so always name segments from their profiles, never by number.
07. Step 6: Test the segments for stability
A segment that disappears when you resample the customers is not one to build a campaign on. The bootstrap draws a new sample of 2,000 rows with replacement from the 2,000 customers, so some appear twice and others not at all. Refit k-means on 20 such samples, label every customer with each refit, and compare those labels with the full-data fit using ARI.
import numpy as np
from sklearn.cluster import KMeans
from sklearn.metrics import adjusted_rand_score
from prepare import load
df, X = load()
rng = np.random.default_rng(0)
print(" k mean ARI worst ARI (20 bootstrap refits vs the full-data fit)")
for k in range(2, 7):
reference = KMeans(k, n_init=10, random_state=0).fit(X).labels_
scores = []
for b in range(20):
rows = rng.integers(0, len(X), len(X)) # resample with replacement
model = KMeans(k, n_init=10, random_state=b).fit(X[rows])
scores.append(adjusted_rand_score(reference, model.predict(X)))
print(f"{k:2d} {np.mean(scores):9.3f} {np.min(scores):10.3f}")python stability.py k mean ARI worst ARI (20 bootstrap refits vs the full-data fit)
2 0.970 0.904
3 0.761 0.287
4 0.971 0.898
5 0.818 0.613
6 0.939 0.828k = 4 is the most stable choice: a mean ARI of 0.971 and a worst case of 0.898. k = 3 is the least stable (worst 0.287). With four real groups and three centres, two groups have to share a centre, and which pair is merged is close to a tie, so different samples merge different pairs. k = 2 is also stable, but its profile is too coarse to act on.
You can now defend k = 4 with five pieces of evidence: the inertia elbow, a silhouette 0.05 below the best (silhouette tends to favour fewer, broader clusters), the mixture's BIC and its agreement with k-means, interpretable profiles, and bootstrap stability. Silhouette alone would have picked k = 2.
08. Check your understanding
09. Apply it: stretch tasks
- Choose the scaling deliberately. Rerun
choose_k.pyandstability.pywithout the log step and describe how the profiles and the stability change. - Soft membership. Fit the GMM with k = 4, find the customers whose largest
predict_probais below 0.6, and profile them. Who sits between segments? - Practice project. On your own customer or transaction table, repeat the full defence: scaling, a k scan with silhouette, DBSCAN with
epsfrom the k-distance percentiles, a profile table and a bootstrap stability check. Write one paragraph per segment and one paragraph defending your choice of k. You will plot the segments in two PCA components in the next lesson.
10. Review prompt
Without looking back, explain why skewed features are log-transformed before scaling, and why scaling alone is not enough; what the inertia elbow and the silhouette each reward; why DBSCAN found no segments in this data; what a segment profile contains and why it uses medians in original units; and how bootstrap refits with ARI test whether segments are stable.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.