Predictive Modeling and Machine Learning Fundamentals Questions
Applied predictive-modeling cases worked end to end on tabular business data. Covers choosing a model family for a business target (churn, lifetime value, lead scoring, conversion, support-ticket escalation), setting a baseline, defining the label, observation window and prediction horizon, catching leakage, sanity-checking and interpreting results for non-technical stakeholders (feature importance and its traps with correlated features, explaining a single flagged customer), handling censored outcomes with survival methods such as Kaplan-Meier and Cox models, turning model scores into thresholds and business actions with cost-sensitive reasoning, targeting for incremental effect with uplift modeling, and clustering and unsupervised methods in practice: k-means and its initialization (k-means++), empty clusters, scaling, distance choices and mini-batch variants, choosing and validating the number of clusters without labels (elbow, silhouette, stability), density-based, hierarchical and mixture-model alternatives, mixed numeric and categorical features, high-dimensional preparation and visualization, and customer segmentation carried through to stakeholder communication, testing whether segment-based targeting works, keeping segments stable over refits, and downstream use. Excludes regression and classification algorithm internals, metric and validation theory, feature engineering mechanics, and large-scale or production ML systems (including distributed or streaming clustering), which are covered elsewhere.
You are given clickstream data and asked to segment users into engagement groups using unsupervised learning. Describe how you would go from raw events to segments a product team can act on.
Sample Answer
Direct answer
Aggregate the raw events into one row per user of behaviour summaries (how often, how intensely, how broadly, how recently) over a shared observation window, put the columns on a comparable scale, cluster with a method that fits the shape of the data (k-means as a first pass), pick the number of segments with several measures plus a stability check and a usefulness test, profile each segment in the original units, give each a plain name, and validate the segments on something the clustering did not use. Segments are only useful if a product team can say what it would do differently for each one.
Terms
Segment: a group of users with similar behaviour. k-means: an algorithm that puts k centre points in the data, assigns each user to the nearest centre, moves each centre to the mean of its users, and repeats. Inertia: the total squared distance from users to their centres, lower means tighter clusters but it always falls as k grows. Silhouette: for each user, how much closer they are to their own cluster than to the next closest one, from -1 to 1. ARI (adjusted Rand index): agreement between two clusterings, 1 for identical and about 0 for chance.
From raw events to features
- Decide the unit and window. One row per user, a fixed window (for example 30 days), and an agreed set of users (new accounts with too little history are handled separately).
- Clean events. Remove bots and internal accounts, and keep users with no events (they are a real segment).
- Summaries a person can read. Active days, events per active day, distinct features used, days since last activity.
- Transform and scale. Counts are skewed, so take a log, then standardize so no column dominates only because of its units. Without scaling, k-means measures distance mostly in the largest-unit column.
- Cluster, choose k, check, profile, name, validate.
Worked example
The simulated clickstream has 1,800 users over 30 days generated from three hidden habits (casual, steady, power). The hidden habit is never used for clustering; it is printed at the end only to check the demo, which is possible because the data is simulated. Real data has no such answer key, so the substitute is outcomes the clustering did not use.
import numpy as np
import pandas as pd
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import silhouette_score, adjusted_rand_score
rng = np.random.default_rng(0)
# ---- 1. raw events: one row per (user, day, feature used); 30 days of data, 1,800 users from 3 hidden habits ----
N, DAYS = 1800, 30
habit = rng.choice(3, N, p=[0.5, 0.3, 0.2]) # 0 = casual, 1 = steady, 2 = power (hidden; never used below)
active_prob = np.array([0.08, 0.35, 0.80])[habit]
events_per_day = np.array([1.5, 3.0, 9.0])[habit]
n_features = np.array([2, 5, 12])[habit]
rows = []
for u in range(N):
days = np.nonzero(rng.random(DAYS) < active_prob[u])[0]
for dd in days:
for _ in range(max(1, rng.poisson(events_per_day[u]))):
rows.append((u, dd, rng.integers(0, n_features[u])))
ev = pd.DataFrame(rows, columns=["user", "day", "feature"])
print("events:", len(ev), "users with at least one event:", ev.user.nunique())
# ---- 2. one row per user: behaviour summaries, with a shared observation window ----
g = ev.groupby("user")
f = pd.DataFrame({
"active_days": g.day.nunique(),
"events_per_active_day": g.size() / g.day.nunique(),
"distinct_features": g.feature.nunique(),
"days_since_last": DAYS - 1 - g.day.max(),
}).reindex(range(N))
f["active_days"] = f.active_days.fillna(0)
f = f.fillna({"events_per_active_day": 0, "distinct_features": 0, "days_since_last": DAYS})
X = StandardScaler().fit_transform(np.log1p(f.values)) # log tames the long right tail, then put columns on one scale
# ---- 3. choose k with several views, none of which uses the hidden habit ----
print("\nk silhouette inertia stability (mean ARI between 5 reseeded runs of 10 starts each)")
for k in range(2, 7):
runs = [KMeans(k, n_init=10, random_state=s).fit(X).labels_ for s in range(5)]
ari = np.mean([adjusted_rand_score(runs[i], runs[j]) for i in range(5) for j in range(i + 1, 5)])
km = KMeans(k, n_init=10, random_state=0).fit(X)
print(f"{k} {silhouette_score(X, km.labels_):.3f} {km.inertia_:9.1f} {ari:.3f}")
# ---- 4. profile the chosen solution in the original units ----
km = KMeans(3, n_init=10, random_state=0).fit(X)
f["segment"] = km.labels_
order = f.groupby("segment").active_days.mean().sort_values().index # label segments by activity so the numbering is not arbitrary
f["segment"] = f.segment.map({old: new for new, old in enumerate(order)})
prof = f.groupby("segment").agg(users=("active_days", "size"), active_days=("active_days", "mean"),
events_per_day=("events_per_active_day", "mean"),
features=("distinct_features", "mean"), days_since_last=("days_since_last", "mean")).round(1)
print("\n", prof.to_string())
print("\nshare of each hidden habit inside each segment (used only to check the demo):")
print(pd.crosstab(f.segment, pd.Series(habit, name="hidden_habit"), normalize="index").round(2).to_string())
events: 103727 users with at least one event: 1750
k silhouette inertia stability (mean ARI between 5 reseeded runs of 10 starts each)
2 0.530 2644.5 1.000
3 0.536 1516.9 1.000
4 0.502 1067.6 1.000
5 0.532 787.9 0.992
6 0.507 637.7 0.995
users active_days events_per_day features days_since_last
segment
0 778 2.2 1.6 1.6 11.5
1 640 9.4 2.9 4.4 1.6
2 382 24.1 9.0 12.0 0.2
share of each hidden habit inside each segment (used only to check the demo):
hidden_habit 0 1 2
segment
0 0.99 0.01 0.0
1 0.18 0.82 0.0
2 0.00 0.00 1.0
Reading the output:
- 103,727 events, and 1,750 of the 1,800 users appear in them; the other 50 have no events, so the code gives them 0 for active days, events per active day and distinct features, and 30 (the whole window) for days since last activity, because they were last seen at least 30 days ago. That last value is deliberate: a zero there would wrongly say they were active today. These 50 land in the least active segment.
- Choosing k. Silhouette is nearly flat from k = 2 to 5 (0.530, 0.536, 0.502, 0.532), so the 0.006 gap between k = 2 and k = 3 is noise, not a winner. Inertia keeps falling with every k, as it must, and shows no sharp elbow: it drops 43% from k = 2 to 3, 30% from 3 to 4 and 26% from 4 to 5. Stability (mean ARI between five reseeded runs, each the best of 10 starts) is between 0.992 and 1.000 for every k from 2 to 6, so each of these segmentations reproduces and stability does not separate them either. Its job is to warn when a candidate k is not reproducible, and none is a problem here. A single start per run would add a different kind of noise, the luck of the starting centroids, which is why each run uses 10 starts. When the three views agree that several values of k are acceptable, the choice is made on use: k = 3 gives three profiles that differ on every column and suggest three different actions, whereas k = 2 can only split the three profiles into two groups, so two of them share a segment. The demo data was generated from three habits, so 3 is the expected answer here; on real data the same reading applies, and the usefulness test and the outcome validation below carry the decision. What would change it is a product need for finer groups, accepting that each extra group is less distinct.
- Profile in original units. Segment 0 (778 users): about 2.2 active days, 1.6 events per active day, 1.6 features, last seen 11.5 days ago. Segment 1 (640 users): 9.4 active days, 2.9 events per day, 4.4 features, last seen 1.6 days ago. Segment 2 (382 users): 24.1 active days, 9.0 events per day, 12.0 features, last seen 0.2 days ago. Natural names: occasional visitors, regular users, power users.
- Check against the answer key. Segment 0 is 99% casual-habit users, segment 1 is 82% steady, segment 2 is 100% power. Segment numbers are arbitrary, so the code orders them by average active days to keep them reproducible.
Making segments actionable
Give each segment a rule a system can apply (the profile above translated into thresholds, or a saved model assigning new users), a name, a size, and one action: for example onboarding nudges for occasional visitors, feature discovery prompts for regular users, early access or feedback invitations for power users. Validate on outcomes the clustering did not use, such as 90-day retention, and re-run the clustering on a later window to see whether the same segments reappear. Refresh on a schedule so assignments do not drift silently.
When k-means is not the right tool
K-means assumes roughly round, similar-sized groups and is pulled by outliers. Density-based clustering (DBSCAN) finds irregular shapes and labels noise, hierarchical clustering gives a tree of merges to inspect, and Gaussian mixtures give soft memberships. In practice k-means (often after trying hierarchical clustering on a sample) is the usual first pass, and DBSCAN and Gaussian mixtures are second-line tools that you reach for only if profiles look smeared or a few extreme users dominate.
Pitfalls
- Clustering raw counts: heavy users dominate the distance.
- Choosing k with only one score, or from the elbow of inertia alone.
- Presenting segments without an action, a size, or a validation outcome.
- Treating cluster numbers as meaningful or stable across re-runs.
What is the elbow method for choosing the number of clusters, how do you build the plot, and what do you do when there is no clear elbow?
Sample Answer
Direct answer
The elbow method fits k-means for a range of cluster counts k, plots the inertia (the sum of squared distances from each point to its cluster's centroid) against k, and picks the k where the curve stops dropping steeply and flattens, like a bent arm. Inertia always falls as k grows (at k=n it is zero), so the bend marks the point where an extra cluster stops buying much. When there is no clear elbow, that is information: either the data has no strong cluster structure, or the structure is not the compact round kind inertia rewards, and you switch to other evidence rather than forcing a pick.
How to build the plot
- Standardise the features, since inertia uses Euclidean distance and an unscaled column dominates it.
- For each k=1,…,K (for example K=10), fit k-means with several restarts (
n_init) and a fixed seed, and recordinertia_. Restarts matter because one unlucky start gives a noisy point and a false kink. - Plot k on the horizontal axis and inertia on the vertical axis, joining the points.
- Read the shape. A useful number to print next to the plot is the percentage drop from k to k+1, since the eye is poor at judging slope.
- To automate the choice, one heuristic finds the point farthest from the straight line joining the first and last points after rescaling both axes to [0,1]; published methods build on similar ideas (for example Kneedle, which looks for the point where a rising or falling curve bends most sharply away from a straight line), and all are heuristics. They only need a curve that bends one way, a convex shape like a ski slope that starts steep and flattens.
Worked example: a clear elbow and a curve with none
The program builds two datasets: four Gaussian blobs, and one Gaussian blob with no real groups. For each it prints the inertia for k=1 to 10, the percentage drop to the next k, and the result of the chord heuristic above, also prints the rescaled coordinates behind that heuristic, and a second rule built on the drop column (the first k whose next drop is under 40% of the drop before it), and saves the plot (elbow.png) with both curves scaled by their value at k=1. A final pair of lines tallies what both rules pick on 20 other draws of each dataset.
import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn.datasets import make_blobs
ks = np.arange(1, 11)
def inertia_curve(X):
return np.array([KMeans(int(k), n_init=10, random_state=0).fit(X).inertia_ for k in ks])
def chord_scores(ks, w):
"""Rescale both axes to [0, 1]. The first point becomes (0, 1) and the last (1, 0), so the
straight line joining them is x + y = 1, and |x + y - 1| is proportional to the distance from it."""
x = (ks - ks[0]) / (ks[-1] - ks[0])
y = (w - w[-1]) / (w[0] - w[-1])
return x, y, np.abs(x + y - 1)
def chord_elbow(ks, w):
return int(ks[np.argmax(chord_scores(ks, w)[2])])
def cliff_elbow(w, frac=0.4):
"""First k whose next drop collapses to under frac of the drop before it; None if no step does."""
d = -np.diff(w) / w[:-1] * 100 # d[i] is the % drop from k = i + 1 to k = i + 2
hits = [int(ks[i]) for i in range(1, len(d)) if d[i] < frac * d[i - 1]]
return hits[0] if hits else None
X_clear, _ = make_blobs(n_samples=400, centers=4, cluster_std=0.8, random_state=2)
X_none = np.random.default_rng(0).normal(size=(400, 2)) # one blob, no real groups
fig, ax = plt.subplots(figsize=(5, 3))
for name, X in [("four blobs", X_clear), ("single gaussian blob", X_none)]:
w = inertia_curve(X)
drop = -np.diff(w) / w[:-1] * 100 # % fall from k to k+1
print(f"--- {name}")
print("k :", " ".join(f"{k:6d}" for k in ks))
print("inertia :", " ".join(f"{v:6.0f}" for v in w))
print("% drop to k+1:", " " + " ".join(f"{d:6.1f}" for d in drop))
x, y, s = chord_scores(ks, w)
print("rescaled x :", " ".join(f"{v:6.2f}" for v in x))
print("rescaled y :", " ".join(f"{v:6.2f}" for v in y))
print("|x + y - 1| :", " ".join(f"{v:6.2f}" for v in s))
print("chord elbow k:", chord_elbow(ks, w))
print("cliff rule k :", cliff_elbow(w))
ax.plot(ks, w / w[0], marker="o", label=name)
ax.set_xlabel("k"); ax.set_ylabel("inertia / inertia at k=1"); ax.legend()
fig.tight_layout(); fig.savefig("elbow.png", dpi=80)
print("plot saved:", "elbow.png")
# Do the two rules behave the same on 20 other draws of each dataset?
from collections import Counter
chord_blobs, cliff_blobs, chord_one, cliff_one = Counter(), Counter(), Counter(), Counter()
for s in range(1, 21):
wb = inertia_curve(make_blobs(n_samples=400, centers=4, cluster_std=0.8, random_state=100 + s)[0])
wo = inertia_curve(np.random.default_rng(100 + s).normal(size=(400, 2)))
chord_blobs[chord_elbow(ks, wb)] += 1; cliff_blobs[cliff_elbow(wb)] += 1
chord_one[chord_elbow(ks, wo)] += 1; cliff_one[cliff_elbow(wo)] += 1
print("20 redraws, four blobs : chord picks", dict(sorted(chord_blobs.items())), "| cliff rule picks", dict(cliff_blobs))
print("20 redraws, one blob : chord picks", dict(sorted(chord_one.items())), "| cliff rule picks", dict(cliff_one))
Output:
--- four blobs
k : 1 2 3 4 5 6 7 8 9 10
inertia : 10284 4439 1144 520 473 427 383 345 309 284
% drop to k+1: 56.8 74.2 54.5 9.1 9.6 10.4 9.9 10.3 8.1
rescaled x : 0.00 0.11 0.22 0.33 0.44 0.56 0.67 0.78 0.89 1.00
rescaled y : 1.00 0.42 0.09 0.02 0.02 0.01 0.01 0.01 0.00 0.00
|x + y - 1| : 0.00 0.47 0.69 0.64 0.54 0.43 0.32 0.22 0.11 0.00
chord elbow k: 3
cliff rule k : 4
--- single gaussian blob
k : 1 2 3 4 5 6 7 8 9 10
inertia : 799 533 348 280 236 196 174 152 137 124
% drop to k+1: 33.2 34.7 19.5 15.7 17.3 10.9 12.7 9.8 9.4
rescaled x : 0.00 0.11 0.22 0.33 0.44 0.56 0.67 0.78 0.89 1.00
rescaled y : 1.00 0.61 0.33 0.23 0.17 0.11 0.07 0.04 0.02 0.00
|x + y - 1| : 0.00 0.28 0.45 0.44 0.39 0.34 0.26 0.18 0.09 0.00
chord elbow k: 3
cliff rule k : None
plot saved: elbow.png
20 redraws, four blobs : chord picks {2: 3, 3: 16, 4: 1} | cliff rule picks {4: 17, 3: 3}
20 redraws, one blob : chord picks {3: 7, 4: 13} | cliff rule picks {None: 20}
Four blobs. The drops are 56.8%, 74.2% and 54.5% going from k=1 to 2, 2 to 3 and 3 to 4, and then only 8.1 to 10.4% per step from k=4 onward (9.1, 9.6, 10.4, 9.9, 10.3, 8.1). A practical reading rule compares each drop with the one before it. The cliff steps are 56.8%, 74.2% and 54.5%, and then the drop collapses to 9.1%, under a fifth of the 54.5% before it (9.1 / 54.5 is about 0.17). The elbow is the k where that collapse begins, which is k=4 and matches the four blobs that generated the data. The program applies this as the first k whose next drop is under 40% of the drop before it, and prints 4.
The automatic chord heuristic printed 3, one below the correct 4. The trace shows why. After rescaling, the first point is (0,1) and the last is (1,0), so the chord is the line x+y=1, and the distance of a point from that line is proportional to ∣x+y−1∣. For k=3 the rescaled point is (0.22,0.09), giving ∣0.22+0.09−1∣=0.69; for k=4 it is (0.33,0.02), giving 0.64; for k=2 it is (0.11,0.42), giving 0.47. The score peaks at the largest single bend, and because the heuristic measures how far a point bends away from the chord rather than where the cliff ends, it lands on k=3. This is not a one-off: on 20 other draws of the four-blob data the chord heuristic picked 3 sixteen times, 2 three times and 4 once, so it usually lands below the planted count, while the drop-ratio rule picked 4 seventeen times and 3 three times. Neither rule is a verdict; read the collapse in the drop column and use the automatic value as a prompt to look.
One blob. The drops are 33.2%, 34.7%, 19.5%, 15.7%, 17.3%, 10.9% and so on, a smooth decline with no step from "large" to "small". The chord heuristic still printed 3, since any decreasing curve that bends one way has a point farthest from its chord; its top score is 0.45 at k=3, but the score only ranks the points of one curve. The drop-ratio rule printed None: no drop falls below 40% of the one before it (the sharpest is 19.5% after 34.7%, which is 56%). On 20 other draws of a single blob the chord heuristic picked 3 seven times and 4 thirteen times, and the drop-ratio rule found no collapse in all 20. That is the failure mode to remember: the heuristic always returns a number, including when there is nothing there. In an interview, the trustworthy evidence is the drop column (is there a cliff followed by a plateau?) plus a second measure, and the automatic pick is only a convenience.
What to do when there is no clear elbow
- Use a second, differently-built measure: the silhouette score across the same k range, the gap statistic, or the BIC of a Gaussian mixture. Agreement of two or three is stronger than one bend.
- Test stability: if the best k or the partitions change a lot across subsamples, the structure is weak.
- Question the method: inertia rewards round, equally spread clusters. Elongated, ring-shaped or very unequal groups can hide the elbow; a density-based or mixture method may suit the data.
- Let the use case choose: if the business can run at most five campaigns, pick the best k at or below five and report how much inertia that leaves.
- Report honestly: "no natural number of clusters; k=4 chosen for usability" is a valid result.
Pitfalls
- Using one run per k without restarts.
- Reading the plot with the vertical axis starting above zero, which exaggerates bends; scaling by the k=1 value, as the program does, makes curves comparable.
- Treating the elbow as proof that k natural clusters exist.
Your customer data mixes numeric and categorical fields. How do you handle the categorical variables before clustering, and what are the trade-offs?
Sample Answer
Clustering needs a notion of distance between customers, and a category such as "plan = Pro" has no natural distance to "plan = Basic". The standard fixes are to turn each category into 0/1 columns (one-hot encoding) and scale everything so no feature dominates, or to switch to a distance built for mixed data (Gower distance) or to an algorithm built for it (k-modes and k-prototypes, which replace the mean with the most common category). A medoid is the real customer that sits most centrally in a group; k-medoids uses medoids as centres instead of means, which works with any distance table. The default is to standardize the numbers, one-hot encode low-cardinality categories (those with few distinct levels), group rare levels, and check that the weight of the categorical block is a decision rather than an accident.
The options and their trade-offs
| Approach | What it does | Costs |
|---|---|---|
| Ordinal codes (1, 2, 3) | Maps ordered categories (plan tier, satisfaction band) to numbers; ordinal means the order is real | Wrong for unordered categories: it invents an order and a spacing |
| One-hot encoding | One 0/1 column per category level; a mismatch contributes a fixed distance | A variable with many levels adds many columns and gets a larger say; sparse (most entries are 0); high dimension |
| One-hot with weights | Scale each categorical block to the weight you intend | Weights are a judgment call and must be reviewed |
| Gower distance | Per feature: numeric difference divided by the range; categorical 0 if equal, 1 if not; then the average over features | Needs the full n by n distance table, so it suits thousands of customers, not millions; pairs with hierarchical clustering or k-medoids rather than k-means |
| k-modes / k-prototypes | Cluster centre is the most common category (and the mean for numbers in k-prototypes) | Needs a weight between the numeric and categorical parts; not in every toolkit; initialization-sensitive like k-means |
| Learned embeddings (rarely needed for a first segmentation) | Map each category to a short numeric vector learned from the data, for example a product-category level represented by 8 numbers that place similar categories near each other | More machinery; the vectors are hard to explain |
| Group rare levels and drop weak variables | Merge levels under (say) 2% of customers into "other"; remove variables unrelated to the purpose | A business judgment; always worth doing first |
What goes wrong: a computed example
300 customers fall into three true groups. Two numeric features: annual spend in dollars (large numbers, standard deviation 150 within a group) and tenure in years (small numbers). Three categorical features: plan (3 levels) and device (3 levels), both linked to the group, and country (10 levels), unrelated to the group. The code compares seven treatments by the adjusted Rand index (ARI; 1.0 means the segments match the true groups, about 0 chance level), averaged over 10 random datasets. The Gower function is also checked against a construction from SciPy distances (a mean of range-scaled absolute differences for numbers and mismatches for categories), and computed by hand for two customers. A reference line gives k-means on raw spend alone. The last two rows separate the distance from the clustering rule, because Gower has so far been scored together with average linkage (a hierarchical clustering rule that merges the two groups whose members are on average closest).
import numpy as np
from scipy.cluster.hierarchy import linkage, fcluster
from scipy.spatial.distance import pdist, squareform
from sklearn.cluster import KMeans
from sklearn.metrics import adjusted_rand_score
def make(seed, n_per=100):
rng = np.random.default_rng(seed)
y = np.repeat(np.arange(3), n_per)
spend = rng.normal(np.array([300.0, 500.0, 700.0])[y], 150.0) # dollars, large scale
tenure = rng.normal(np.array([2.0, 3.0, 4.0])[y], 1.0) # years, small scale
plan_p = np.array([[.7, .2, .1], [.2, .6, .2], [.1, .2, .7]]) # plan type depends on group
plan = np.array([rng.choice(3, p=plan_p[g]) for g in y])
device = np.array([rng.choice(3, p=plan_p[g][::-1]) for g in y]) # device type depends on group
country = rng.integers(0, 10, size=len(y)) # 10 levels, unrelated to group
return spend, tenure, plan, device, country, y
def z(a): return (a - a.mean()) / a.std()
def onehot(a): return np.eye(a.max() + 1)[a]
def gower(num, cat):
"""Mean over features of: |difference| / range for numbers, 0 or 1 (match or not) for categories."""
rng_ = num.max(0) - num.min(0)
dn = np.abs(num[:, None, :] - num[None, :, :]) / rng_
dc = (cat[:, None, :] != cat[None, :, :]).astype(float)
return np.concatenate([dn, dc], axis=2).mean(axis=2)
# check Gower against a SciPy construction on a small sample
spend, tenure, plan, device, country, y = make(0)
num = np.c_[spend, tenure]; cat = np.c_[plan, device, country]
G = gower(num[:50], cat[:50])
rngs = num[:50].max(0) - num[:50].min(0)
G_ref = squareform((pdist(num[:50] / rngs, "cityblock") + pdist(cat[:50], "hamming") * 3) / 5)
print("Gower matches the SciPy construction:", bool(np.allclose(G, G_ref)))
# three customers by hand: spend range 600 and tenure range 4 are assumed for this small illustration
a = dict(spend=300, tenure=2.0, plan="Basic", device="phone", country="DE")
b = dict(spend=500, tenure=3.0, plan="Basic", device="tablet", country="FR")
parts = [abs(a["spend"] - b["spend"]) / 600, abs(a["tenure"] - b["tenure"]) / 4,
float(a["plan"] != b["plan"]), float(a["device"] != b["device"]), float(a["country"] != b["country"])]
print("Gower terms for customers a and b:", np.round(parts, 3).tolist(), "-> distance", round(float(np.mean(parts)), 3))
def kmeans_ari(F, y, seed):
return adjusted_rand_score(y, KMeans(3, n_init=10, random_state=seed).fit_predict(F))
names = ["numbers only, standardized", "one-hot + raw dollars (no scaling)", "one-hot + standardized numbers",
"as above, one-hot scaled by 1/sqrt(2)", "Gower + average linkage",
"one-hot + standardized, average link.", "Gower without country + average link."]
res = {n: [] for n in names}
ref_spend = []
for seed in range(10):
spend, tenure, plan, device, country, y = make(seed)
num = np.c_[spend, tenure]; cat = np.c_[plan, device, country]
cat_oh = np.hstack([onehot(plan), onehot(device), onehot(country)])
zn = np.c_[z(spend), z(tenure)]
res[names[0]].append(kmeans_ari(zn, y, seed))
res[names[1]].append(kmeans_ari(np.c_[spend, tenure, cat_oh], y, seed))
res[names[2]].append(kmeans_ari(np.c_[zn, cat_oh], y, seed))
# a mismatch on a one-hot variable moves two columns by 1, i.e. squared distance 2; dividing by sqrt(2) makes it 1
res[names[3]].append(kmeans_ari(np.c_[zn, cat_oh / np.sqrt(2)], y, seed))
D = squareform(gower(num, cat), checks=False)
res[names[4]].append(adjusted_rand_score(y, fcluster(linkage(D, "average"), 3, "maxclust")))
# same linkage, Euclidean distance on the one-hot + standardized table: isolates the effect of the linkage rule
res[names[5]].append(adjusted_rand_score(y, fcluster(linkage(np.c_[zn, cat_oh], "average"), 3, "maxclust")))
# Gower again with the unrelated country column removed: isolates the effect of the useless feature
D2 = squareform(gower(num, cat[:, :2]), checks=False)
res[names[6]].append(adjusted_rand_score(y, fcluster(linkage(D2, "average"), 3, "maxclust")))
ref_spend.append(kmeans_ari(spend[:, None], y, seed)) # reference: raw spend alone, nothing else
print("\nmean ARI over 10 datasets (3 true groups, 300 customers each time)")
for n in names:
print(f" {n:40s} {np.mean(res[n]):.3f}")
print(f" (reference) k-means on raw spend alone {np.mean(ref_spend):.3f}")
# Six other sets of ten datasets (seeds 10 to 69): do the Gower and country comparisons hold up?
def set_means(seeds):
out = [[], [], [], []]
for seed in seeds:
spend, tenure, plan, device, country, y = make(seed)
num = np.c_[spend, tenure]; cat = np.c_[plan, device, country]
F = np.c_[z(spend), z(tenure), onehot(plan), onehot(device), onehot(country)]
out[0].append(adjusted_rand_score(y, fcluster(linkage(squareform(gower(num, cat), checks=False), "average"), 3, "maxclust")))
out[1].append(adjusted_rand_score(y, fcluster(linkage(squareform(gower(num, cat[:, :2]), checks=False), "average"), 3, "maxclust")))
out[2].append(adjusted_rand_score(y, fcluster(linkage(F, "average"), 3, "maxclust")))
out[3].append(kmeans_ari(F, y, seed))
return [np.mean(v) for v in out]
print("\nother sets of ten datasets: Gower | Gower without country | one-hot + std, average link. | one-hot + std, k-means")
for lo in range(10, 70, 10):
m = set_means(range(lo, lo + 10))
print(f" seeds {lo}-{lo + 9}: {m[0]:.3f} {m[1]:.3f} {m[2]:.3f} {m[3]:.3f}")
Output:
Gower matches the SciPy construction: True
Gower terms for customers a and b: [0.333, 0.25, 0.0, 1.0, 1.0] -> distance 0.517
mean ARI over 10 datasets (3 true groups, 300 customers each time)
numbers only, standardized 0.356
one-hot + raw dollars (no scaling) 0.268
one-hot + standardized numbers 0.534
as above, one-hot scaled by 1/sqrt(2) 0.438
Gower + average linkage 0.287
one-hot + standardized, average link. 0.347
Gower without country + average link. 0.301
(reference) k-means on raw spend alone 0.269
other sets of ten datasets: Gower | Gower without country | one-hot + std, average link. | one-hot + std, k-means
seeds 10-19: 0.262 0.265 0.229 0.509
seeds 20-29: 0.282 0.272 0.333 0.527
seeds 30-39: 0.268 0.307 0.342 0.524
seeds 40-49: 0.240 0.262 0.304 0.515
seeds 50-59: 0.265 0.276 0.342 0.520
seeds 60-69: 0.280 0.284 0.324 0.535
What the run shows, for this synthetic data. First the hand case: customers a and b differ by 200 dollars of spend on an assumed range of 600 (0.333), by 1 year of tenure on a range of 4 (0.25), have the same plan (0), and differ in device and country (1 and 1); the mean of the five terms is 0.517.
- Skipping scaling is costly: with raw dollars next to 0/1 columns, spend swamps everything, so neither tenure nor the categories vote (0.268, essentially the 0.269 of clustering on raw spend alone, in the reference line), worse than using both numbers standardized (0.356).
- Standardizing the numbers and adding the one-hot columns uses the categories that carry signal and gives the best score (0.534).
- Down-weighting the categories by 1/sqrt(2) (so a mismatch costs 1 instead of 2 in squared distance) lowers it to 0.438, since here two of the three categorical variables are informative. The weight is a choice, and the right one depends on whether categories deserve as much say as numbers.
- Gower distance with average-linkage hierarchical clustering scores 0.287 here, below even the numbers alone (0.356). The last two rows say why. The same average linkage on the one-hot and standardized table scores 0.347, against 0.534 for k-means on that same table, so most of the loss comes from the linkage rule on groups that overlap this much, not from Gower (that average-linkage row moves between sets of ten datasets, from 0.229 to 0.342 in the last block, but stays far below k-means on the same table, 0.509 to 0.535). Removing the unrelated country column moves Gower from 0.287 to 0.301. The last block of the output repeats the comparison on six other sets of ten datasets: Gower scores 0.240 to 0.282 with the country column and 0.262 to 0.307 without it, so dropping the column helped in six of the seven sets of ten (the shipped one and the six printed) but by at most 0.039, against a gap of about 0.25 to k-means on the one-hot table. The useless column costs Gower a little; it is not why Gower scores low. Under the same average linkage the one-hot table scored above Gower in six of the seven sets (0.347 against 0.287 in the shipped set), so this toy does not show Gower beating one-hot encoding; it shows that Gower is a way to measure distance on mixed data with no encoding step, and that the clustering rule on top still has to suit the data. Pair Gower with a rule you have checked (medoid clustering, or hierarchical clustering compared across linkages).
- A score of 0.534 is the best here and is only a reference for this generator. Real customers have no true groups to score against, so on real data judge segments by stability on resamples and by whether the profiles are usable.
Because the data and the ARI means come from one fixed generator, they illustrate the pitfalls rather than rank the methods for real customers.
Practical guidance
- Encode by type. Ordered categories become ordinal numbers. Unordered categories become one-hot columns (binary yes/no flags stay as single 0/1 columns).
- Control cardinality (the number of distinct levels in a column). Merge rare levels. A 50-level "city" column becomes a "region" column with a handful of levels.
- Scale, then weight on purpose. Standardize numeric columns (subtract the mean, divide by the standard deviation). Decide how much say the categorical block should have, and test the segmentation at two or three weights to see whether the segments change.
- Drop variables that are not part of the purpose (an ID, a country that does not matter for the campaign).
- Validate as usual: stability on resamples, silhouette (how much closer a customer is to its own group than to the next nearest, computed in whatever distance you chose), and profiles that a stakeholder can read (for categories, the share of each level in the cluster, not a mean).
Commit and flip
Start with standardized numbers plus one-hot encoding of low-cardinality categories and k-means or hierarchical clustering. Switch to Gower with hierarchical or medoid clustering when categories dominate the table and the data fits an n by n distance table. Use k-prototypes when you need k-means-style scale and have mostly categorical fields. Check the weight of the categorical block in every case.
Common mistakes
- Encoding unordered categories as 1, 2, 3 and clustering on the codes.
- One-hot encoding a 40-level column and letting it dominate the distance.
- Reporting the cluster "mean" of a one-hot column (it is a share, and must be read as one).
- Scaling the numbers but not thinking about the weight of the categories.
You clustered customers into six segments. Five have a clean story, but one small cluster of about forty customers looks like 'a bit of everything.' How do you decide what to do with it before presenting to marketing?
Sample Answer
Direct answer
Do not present it as a persona yet. First find out whether it is a real group or a leftover, using a few checks: how spread out it is compared with the other clusters, whether it survives a change in the number of clusters, and whether its members behave differently on something that matters (response, churn, revenue). Then choose one of three actions: merge it into its nearest neighbour, label it plainly as "mixed / no clear profile" and give it no targeted playbook, or keep it only if it differs on an outcome that the business can act on.
What "a bit of everything" usually means
K-means (an algorithm that assigns each customer to the nearest of k centre points, called centroids) must put every customer in some cluster. After the compact groups are carved out, the customers that fit none of them can end up together. The cluster's average profile looks like a blend because the members are spread in many directions and the average washes them out. That is a statement about the cluster's shape, not about customers who "do everything".
The checks, in order
- Dispersion. Mean distance of members to their centroid, compared with other clusters. A cluster far wider than the rest is a catch-all.
- Separation. The silhouette score of each member (between -1 and 1: how much closer the customer is to its own cluster than to the next nearest one). A low cluster average says the boundary is blurry. Also the distance from its centroid to the nearest other centroid, compared with its own spread.
- Stability. Refit on bootstrap resamples (random draws of customers with replacement, so each resample repeats some customers and leaves others out) and see whether the same customers keep being grouped, scoring the match with the Jaccard overlap: the number of customers two groups share divided by the number in either of them. Stability says the group is repeatable, not that it has a story. A diffuse cluster can be perfectly repeatable, or it can be unstable; the check tells you which.
- Does k=5 absorb it? Drop to one fewer cluster and see where the members go. All to one neighbour means it was a fringe of that neighbour.
- Outcome check. Compare its response or churn rate with its nearest neighbour. With a few dozen customers the rates are noisy, so only a large difference is believable.
Worked example
The program builds 1,040 customers in four features: five compact groups of 200, plus 40 more drawn with a much wider spread (standard deviation 2.5 against 1.0; a real analyst would not know this, and it is printed only to show that the checks find what was built in). K-means with k=6 is asked for six clusters. The two sizes to keep apart are the 40 wide-spread customers that were built and the 33 that end up together in the small cluster.
import numpy as np
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_samples
from sklearn.preprocessing import StandardScaler
rng = np.random.default_rng(0)
# 5 compact segments (200 customers each) + 40 customers with a much wider spread (sd 2.5 vs 1.0)
centers = rng.normal(0, 3.0, size=(5, 4))
X = np.vstack([c + rng.normal(0, 1.0, size=(200, 4)) for c in centers])
mixed = rng.normal(0, 3.0, size=4) + rng.normal(0, 2.5, size=(40, 4))
X = StandardScaler().fit_transform(np.vstack([X, mixed]))
truth_mixed = np.r_[np.zeros(1000, bool), np.ones(40, bool)]
km = KMeans(n_clusters=6, n_init=10, random_state=0).fit(X)
lab = km.labels_
dist = np.linalg.norm(X - km.cluster_centers_[lab], axis=1)
sil = silhouette_samples(X, lab)
def best_jaccard(members, labels_b):
return max((members & (labels_b == k)).sum() / (members | (labels_b == k)).sum()
for k in np.unique(labels_b))
# Stability: refit on 30 bootstrap resamples, compare each cluster to its best-matching resampled cluster
stab = np.zeros(6); B = 30
for b in range(B):
idx = np.unique(rng.integers(0, len(X), len(X)))
kb = KMeans(n_clusters=6, n_init=5, random_state=b).fit(X[idx])
lb = kb.predict(X) # assign all customers to the resampled centroids
for k in range(6):
stab[k] += best_jaccard(lab == k, lb)
stab /= B
print("customers:", len(X))
print("cluster size mean_dist mean_silhouette boot_jaccard")
for k in np.argsort([(lab == k).sum() for k in range(6)]):
m = lab == k
print(f"{k:7d} {m.sum():4d} {dist[m].mean():10.2f} {sil[m].mean():15.2f} {stab[k]:12.2f}")
small = np.argmin(np.bincount(lab))
print("small cluster id:", small, "share of all customers:", round(float((lab == small).mean()), 3), " share of its members from the wide-spread group:",
round(truth_mixed[lab == small].mean(), 2))
print("the 40 wide-spread customers, counted by the cluster they landed in:", np.bincount(lab[truth_mixed], minlength=6))
cd = np.linalg.norm(km.cluster_centers_ - km.cluster_centers_[small], axis=1)
cd[small] = np.inf
print("distance from its centroid to the nearest other centroid:", round(cd.min(), 2),
"(cluster 'radius' = mean member distance", round(dist[lab == small].mean(), 2), ")")
# Does the small cluster survive when k drops to 5?
k5 = KMeans(n_clusters=5, n_init=10, random_state=0).fit(X).labels_
members = lab == small
print("small-cluster members landing in each k=5 cluster:", np.bincount(k5[members], minlength=5))
# Repeat on 30 other random draws of the same design (seeds 1 to 30)
rows = []
for s in range(1, 31):
r = np.random.default_rng(s)
cs = r.normal(0, 3.0, size=(5, 4))
Z = np.vstack([c + r.normal(0, 1.0, size=(200, 4)) for c in cs])
wide = r.normal(0, 3.0, size=4) + r.normal(0, 2.5, size=(40, 4))
Z = StandardScaler().fit_transform(np.vstack([Z, wide]))
is_wide = np.r_[np.zeros(1000, bool), np.ones(40, bool)]
k6 = KMeans(n_clusters=6, n_init=10, random_state=0).fit(Z)
l6 = k6.labels_
d6 = np.linalg.norm(Z - k6.cluster_centers_[l6], axis=1)
sm = np.argmin(np.bincount(l6)); mem = l6 == sm
ratio = d6[mem].mean() / np.mean([d6[l6 == k].mean() for k in range(6) if k != sm])
jac = np.mean([best_jaccard(mem, KMeans(n_clusters=6, n_init=5, random_state=b).fit(Z[np.unique(r.integers(0, len(Z), len(Z)))]).predict(Z))
for b in range(30)])
l5 = KMeans(n_clusters=5, n_init=10, random_state=0).fit(Z).labels_
rows.append((mem.sum(), is_wide[mem].mean(), ratio, jac, len(np.unique(l5[mem]))))
rows = np.array(rows)
formed = (rows[:, 0] <= 60) & (rows[:, 1] >= 0.8) # smallest cluster is small and mostly the wide-spread customers
print("\n30 other draws: the wide-spread customers form a small cluster in", int(formed.sum()), "draws")
print(" size of that cluster:", int(rows[formed, 0].min()), "to", int(rows[formed, 0].max()),
"| spread vs the other clusters:", round(rows[formed, 2].min(), 2), "to", round(rows[formed, 2].max(), 2), "times")
print(" bootstrap Jaccard:", round(rows[formed, 3].min(), 2), "to", round(rows[formed, 3].max(), 2),
"| k=5 destinations (how many clusters its members go to):", np.bincount(rows[formed, 4].astype(int), minlength=6)[1:].tolist(), "draws for 1, 2, 3, 4, 5 clusters")
print(" draws with no such cluster: smallest cluster had", rows[~formed, 0].astype(int).tolist(), "members")
Output:
customers: 1040
cluster size mean_dist mean_silhouette boot_jaccard
3 33 1.67 0.20 0.97
4 194 0.74 0.32 0.97
1 200 0.77 0.60 1.00
5 201 0.76 0.36 0.97
0 203 0.79 0.50 1.00
2 209 0.74 0.35 0.97
small cluster id: 3 share of all customers: 0.032 share of its members from the wide-spread group: 1.0
the 40 wide-spread customers, counted by the cluster they landed in: [ 1 0 0 33 3 3]
distance from its centroid to the nearest other centroid: 2.7 (cluster 'radius' = mean member distance 1.67 )
small-cluster members landing in each k=5 cluster: [ 0 0 0 0 33]
30 other draws: the wide-spread customers form a small cluster in 25 draws
size of that cluster: 17 to 40 | spread vs the other clusters: 1.82 to 2.61 times
bootstrap Jaccard: 0.34 to 1.0 | k=5 destinations (how many clusters its members go to): [8, 4, 9, 4, 0] draws for 1, 2, 3, 4, 5 clusters
draws with no such cluster: smallest cluster had [100, 27, 109, 91, 83] members
Reading it: the count line shows where the 40 built wide-spread customers went: 33 landed together in cluster 3, and the other 7 were scattered one, three and three into clusters 0, 4 and 5 where they sit at the edge of compact groups. So the share of 1.0 in the line above means every one of cluster 3's 33 members is a wide-spread customer (the cluster is pure); it does not mean all 40 were recovered (33 of 40 were). Cluster 3 holds 33 customers (3.2%). Its members sit on average 1.67 from the centroid against 0.74 to 0.79 for the others, which is about twice as spread. Its silhouette is 0.20, the lowest of the six (the others range from 0.32 to 0.60). The bootstrap Jaccard overlap is 0.97 (a value between 0 and 1: 1 means the same members every time, averaged over the 30 resamples), so it is repeatable. At k=5 all 33 go into one cluster. The nearest other centroid is 2.7 away. Together: a real, repeatable, but diffuse fringe of a neighbour.
That is one draw of the data, and two of these checks vary from draw to draw. The last block of the output rebuilds the data with 30 other random seeds. In 25 of them the wide-spread customers form a small cluster (17 to 40 members, at least 80% of them wide-spread customers) whose members sit 1.82 to 2.61 times as far from their centroid as the members of the other clusters; in the other 5 no such cluster forms (the smallest cluster then has 100, 27, 109, 91 or 83 members and is under 80% wide-spread customers). When the cluster does form, its bootstrap overlap ranges from 0.34 to 1.0, and at k=5 its members go to a single neighbour in 8 draws and split across two, three or four clusters in 4, 9 and 4 draws. So stability and the k=5 test are checks with real outcomes: a diffuse cluster that is repeatable and absorbed by one neighbour, as here, is a fringe to merge into that neighbour; one that is unstable and scatters at k=5 is a leftover of the fit with no claim to be a segment, and is labelled "mixed / no clear profile" with no playbook.
Decision for this case
Commit to, for this draw: merge it into that neighbour for marketing, and report it as a boundary group inside that segment if its response rate differs. Keep it as its own segment only if all of these hold: the outcome check shows a large difference, the group is large enough to market to (at 33 customers the campaign economics probably do not work), and a one-sentence rule describes who is in it. If it is an outlier set (a handful of customers that do not belong to the population at all, such as data errors, test accounts or one-off bulk buyers) remove it before clustering and handle it separately.
What to say to marketing
"Five segments have clear profiles. A sixth group of 33 customers (3% of the base) is a spread-out edge group with no common behaviour, so we are not building a campaign for it. They are treated like the closest segment for now."
Pitfalls
- Choosing k to make the odd cluster disappear without checking whether the merge damaged the other five.
- Reading a stable cluster as a meaningful one.
- Naming it ("explorers") from three or four members that happen to look similar. A story that fits any 33 customers is not evidence.
What are the main strengths and weaknesses of k-means, and how would you decide whether it is the right choice for a given segmentation problem?
Sample Answer
Direct answer
K-means is fast, simple and gives each segment a centroid (its mean customer) that is easy to describe, but it assumes clusters are compact, roundish, of similar spread, and it needs k (the number of clusters) up front, depends on the starting centroids and is pulled by outliers and by feature units. For a customer segmentation I would start with k-means on standardised, sensibly transformed features as the baseline, because stakeholders can read a centroid. I would switch method only when diagnostics show the shapes violate its assumptions.
Strengths and weaknesses
| Strength | Why it holds |
|---|---|
| Scales linearly in the number of points | Each iteration costs on the order of n×k×d operations (O(nkd)) for n points, k clusters and d features: every point is compared with every centroid across every feature |
| Interpretable output | Each cluster is summarised by its centroid, which reads like a customer profile |
| Assigns new points cheaply | Nearest centroid, so scoring tomorrow's customers is trivial |
| Well understood, widely available | Easy to explain, debug and reproduce with a fixed seed |
| Weakness | What goes wrong | Diagnostic |
|---|---|---|
| Must choose k | No label says how many | Silhouette, gap, stability across k |
| Local optimum | The result depends on initial centroids | Same inertia across seeds; use k-means++ and restarts |
| Round, similar-spread clusters only | Its boundaries are straight lines between centroids, so crescents and rings get cut, and a wide cluster next to narrow ones is split badly | Plot a 2-D projection; compare against a mixture model or a density method |
| Sensitive to scale | Large-unit features dominate distance | Compare clusters with and without standardising |
| Sensitive to outliers | A far point drags a mean, or takes a cluster for itself | Inspect cluster sizes and the farthest points |
| Hard assignment | A customer between two segments is forced into one | Look at distance gaps to the two nearest centroids, or use a mixture model for membership probabilities |
| Numeric, Euclidean | Categorical columns have no mean | Encode carefully, or use a method for mixed data |
Evidence on five datasets
A single outlier shows the mechanism first: the mean of 1, 2, 3, 4, 5 is 3, and adding one value of 100 moves it to 19.17. A centroid is a mean, so far points drag it in the same way. The program then generates five labelled datasets: three overlapping round blobs of equal spread, two crescents, three blobs on a line with one much wider than the others, and two blobs plus 30 outlier points in two ways (scattered uniformly over a wide box, or packed into one far spot). It scores k-means, a Gaussian mixture (GMM: each cluster is a Gaussian bell shape with its own centre and its own covariance, meaning its own spread and tilt, set here by covariance_type="full"; it gives soft membership, a probability of belonging to each cluster rather than a single label), and DBSCAN (density-based: a point with at least min_samples points (itself included) inside radius eps starts a dense region, regions grow into clusters, and sparse points are noise, labelled -1) against the planted labels with the adjusted Rand index (ARI: 1 is a perfect match, about 0 a random one). The outlier rows are scored on the 600 real points only, so a perfect method can reach 1.0. Features are standardised first. DBSCAN's eps is the best of six values, chosen with the labels, so its column is an optimistic upper bound that a real project cannot compute; the last column is how many clusters DBSCAN formed at that eps. Without labels, a common way to pick eps is a k-distance plot: sort every point's distance to its min_samples-th nearest neighbour (counting the point itself, as in the rule above) and set eps near the bend where distances start to climb steeply. After the table the program prints how many clusters DBSCAN formed at each eps on the round blobs, where the real points of the scattered-outlier row went, and a redraw of both outlier rows with 20 other seeds.
import numpy as np
from sklearn.cluster import KMeans, DBSCAN
from sklearn.datasets import make_blobs, make_moons
from sklearn.metrics import adjusted_rand_score
from sklearn.mixture import GaussianMixture
from sklearn.preprocessing import StandardScaler
# One outlier drags a mean: five customers, then the same five plus one extreme value
five = np.array([1.0, 2.0, 3.0, 4.0, 5.0])
print("mean of 1..5:", five.mean(), " mean after adding a value of 100:", round(float(np.append(five, 100).mean()), 2))
rng = np.random.default_rng(0)
cases = {}
cases["round blobs, equal size"] = make_blobs(600, centers=3, cluster_std=1.0, random_state=0)
cases["two moons"] = make_moons(600, noise=0.07, random_state=0)
Xa, ya = make_blobs(900, centers=[[0, 0], [5, 0], [10, 0]], cluster_std=[0.6, 0.6, 2.2], random_state=0)
cases["unequal spread"] = (Xa, ya)
Xb, yb = make_blobs(600, centers=[[0, 0], [8, 0]], cluster_std=1.0, random_state=0)
# Outlier rows are scored on the 600 real points only, so a perfect method can reach 1.0
cases["+30 outliers, scattered"] = (np.vstack([Xb, rng.uniform(-30, 40, (30, 2))]), yb)
cases["+30 outliers, one far spot"] = (np.vstack([Xb, rng.normal([40, 40], 0.5, (30, 2))]), yb)
grid = [0.1, 0.15, 0.2, 0.3, 0.4, 0.5] # DBSCAN eps values tried, after standardising; min_samples=5
blob_dbscan, where = {}, []
print(f"{'dataset':28s} {'k-means':>8s} {'GMM':>8s} {'DBSCAN best':>12s} {'at eps':>7s} {'groups':>7s}")
for name, (X, y) in cases.items():
k = len(set(y))
real = np.arange(len(y)) # the points that have a planted label
Z = StandardScaler().fit_transform(X)
km = KMeans(k, n_init=10, random_state=0).fit_predict(Z)
gm = GaussianMixture(k, covariance_type="full", n_init=5, random_state=0).fit_predict(Z)
# ARI counts DBSCAN's noise label (-1) as one more group. "Best over the grid" uses the labels,
# so it is an optimistic upper bound that nobody has in practice.
labs = {e: DBSCAN(eps=e, min_samples=5).fit_predict(Z) for e in grid}
db = {e: adjusted_rand_score(y, labs[e][real]) for e in grid}
e_best = max(db, key=db.get)
if name.startswith("round"):
blob_dbscan = {e: len(set(l) - {-1}) for e, l in labs.items()}
if name.endswith("scattered"):
for who, lab in (("k-means", km), ("GMM", gm)):
where.append(f"scattered outliers, {who}: real points per cluster {np.bincount(lab[real], minlength=k).tolist()}, "
f"the 30 added points per cluster {np.bincount(lab[len(y):], minlength=k).tolist()}")
n_groups = len(set(labs[e_best]) - {-1})
print(f"{name:28s} {adjusted_rand_score(y, km[real]):8.3f} {adjusted_rand_score(y, gm[real]):8.3f} "
f"{db[e_best]:12.3f} {e_best:7.2f} {n_groups:7d}")
print()
print("round blobs, DBSCAN clusters by eps:", blob_dbscan)
print(*where, sep="\n")
# Are the two outlier rows typical? Redraw the blobs and the 30 added points with 20 other seeds.
for label, draw in (("scattered", lambda r: r.uniform(-30, 40, (30, 2))),
("one far spot", lambda r: r.normal([40, 40], 0.5, (30, 2)))):
km_ok = km_one = gm_ok = 0
for s in range(1, 21):
r = np.random.default_rng(s)
Xs, ys = make_blobs(600, centers=[[0, 0], [8, 0]], cluster_std=1.0, random_state=s)
Zs = StandardScaler().fit_transform(np.vstack([Xs, draw(r)]))
kl = KMeans(2, n_init=10, random_state=0).fit_predict(Zs)[:600]
gl = GaussianMixture(2, covariance_type="full", n_init=5, random_state=0).fit_predict(Zs)[:600]
km_ok += adjusted_rand_score(ys, kl) > 0.9
km_one += np.bincount(kl, minlength=2).max() == 600 # all 600 real points in one cluster
gm_ok += adjusted_rand_score(ys, gl) > 0.9
print(f"{label:12s}, 20 redraws: k-means separated the real groups in {km_ok}, "
f"put all 600 real points in one cluster in {km_one}; GMM separated them in {gm_ok}")
Output:
mean of 1..5: 3.0 mean after adding a value of 100: 19.17
dataset k-means GMM DBSCAN best at eps groups
round blobs, equal size 0.794 0.800 0.353 0.20 8
two moons 0.480 0.494 1.000 0.20 2
unequal spread 0.404 0.967 0.802 0.10 6
+30 outliers, scattered 1.000 0.000 1.000 0.30 2
+30 outliers, one far spot 0.000 0.000 1.000 0.20 3
round blobs, DBSCAN clusters by eps: {0.1: 24, 0.15: 16, 0.2: 8, 0.3: 1, 0.4: 1, 0.5: 1}
scattered outliers, k-means: real points per cluster [300, 300], the 30 added points per cluster [19, 11]
scattered outliers, GMM: real points per cluster [600, 0], the 30 added points per cluster [2, 28]
scattered , 20 redraws: k-means separated the real groups in 7, put all 600 real points in one cluster in 13; GMM separated them in 0
one far spot, 20 redraws: k-means separated the real groups in 0, put all 600 real points in one cluster in 20; GMM separated them in 0
How to read it:
- Round blobs: k-means and the GMM tie (0.794 and 0.800; the blobs overlap, so neither reaches 1). DBSCAN's best is 0.353 because the overlapping blobs have no gap for it to find: at small
epsit shatters them into many small dense pieces (24, 16 and 8 clusters at 0.10, 0.15 and 0.20, where 3 are planted, as the line under the table shows), and ateps0.3 and above it merges everything into one cluster (ARI 0.000). The assumption fits k-means, so the simple method is enough and the extra machinery buys nothing. - Crescents: k-means scores 0.480 because it can only cut with a straight boundary between centroids, while DBSCAN recovers them (1.000).
- Unequal spread: k-means 0.404, GMM 0.967. A mixture model gives each cluster its own spread, which k-means cannot.
- Outliers scattered over a wide box: the GMM scores 0.000. The printed cluster contents show why: it puts all 600 real points in one component, which also takes 2 of the 30 added points, and gives a second, very wide component to the other 28, so the real groups are never separated. A model that must explain every point can spend a component on the outliers. The same happened on all 20 redraws (GMM separated the real groups in 0 of 20). k-means scores 1.000 on the shipped dataset, but that is the lucky draw, not the rule: on the 20 redraws it separates the real groups in only 7. In the other 13 it puts all 600 real points in one cluster and spends the second centroid on the added points, because cutting the wide box of outliers removes more squared distance than separating two tight blobs. So scattered outliers can wreck k-means as well, and whether they do depends on the draw.
- Outliers packed in one far spot: now k-means scores 0.000 for the opposite reason: with k=2 it spends one centroid on the distant clump and splits nothing among the real points. This is not a draw-dependent result: on the 20 redraws k-means put all 600 real points in one cluster every time, and the GMM separated the real groups in none. DBSCAN scores 1.000 by forming a third cluster for the clump and keeping the two real groups intact. So the outlier weakness is real and depends on where the outliers are: they hurt when they are far, numerous or clumped enough to win a centroid, and the diagnostic is to look at cluster sizes and the farthest points. Apart from the two redraw lines, each row of the table comes from one generated dataset, so it illustrates the pattern and does not rank the methods.
How to decide for a segmentation problem
- Ask what the segments are for. If marketing needs a handful of nameable profiles, a centroid-based method is a natural fit.
- Look at the data. Standardise, take logs of skewed money and count features, and plot a 2-D projection. Crescents, rings and very uneven spread argue against k-means.
- Run k-means anyway as the baseline. Check silhouette, stability across seeds and subsamples, and cluster sizes.
- Compare one alternative that fixes the specific symptom: a GMM for unequal spread or overlapping groups, DBSCAN for arbitrary shapes plus noise, hierarchical clustering (repeatedly merging the two closest groups into a tree, which you can cut at any level) when a tree of nested segments is useful.
- Choose on usefulness. Keep the simplest method whose segments differ in behaviour you can act on.
What flips the choice: many outliers or unknown shape (density-based), the need for membership probabilities (mixture), or a requirement to scale to very many points with minimal cost (k-means or its mini-batch variant, which updates centroids from small random batches of points instead of all points each pass, trading a little accuracy for speed).
Common mistakes
- Treating the output as proof that clusters exist; k-means returns k clusters on any data.
- Skipping scaling.
- Switching to a fancier method without a diagnostic showing the baseline is failing.
Unlock Full Question Bank
Get access to all 17 Predictive Modeling and Machine Learning Fundamentals interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.