Build a Gaussian Mixture Model for Soft Clustering of User Behavior
classical-ml feature-engineering model-evaluation mlops View full code for this problem
ML Problem & Solution
Soft Clustering of User Behaviour with GMMs
Most users are 70% one segment and 30% another. Hard assignment throws that 30% away.
A fitness and audio app with 4.1 million monthly active users runs eight lifecycle campaigns: a nudge for lapsing runners, a playlist recommendation for long-session listeners, an upsell for people who use the app on three devices, and five others. Marketing wants to know which users belong in which campaign. The existing answer is a k-means segmentation into eight clusters, refreshed monthly, and the campaign conversion rate across all eight is 3.1%.
The failure is visible in the complaints rather than in the metrics. A user who runs four mornings a week and also listens to two-hour audio sets at the weekend gets assigned to exactly one cluster, and whichever one wins, half of what the app knows about them is discarded at the moment of assignment. Marketing then sends the running nudge to a user whose running behaviour is the smaller half of their profile, or the playlist recommendation to someone who mostly runs. When we pulled the k-means distances, 31% of users were within 15% of their distance to a second centroid, meaning almost a third of the population sat in a region where the assignment was close to a coin flip and the model reported it with no uncertainty whatsoever.
The second problem is what happens in the overlap region under a hard boundary. k-means partitions space with straight lines equidistant between centroids, which means a user drifting slowly from “weekday commuter” toward “weekend long-session” is in one segment on the 28th and the other on the 1st, with no intermediate state. Over four monthly refreshes, 19% of users changed segment at least twice, and each change fired a different campaign. Users received the lapsing-runner nudge and the heavy-user upsell in the same fortnight, which is not a targeting strategy, it is noise with a copywriter attached.
The third problem is the one that makes people distrust clustering entirely. k-means clusters are spherical by construction, because the assignment rule is nearest centroid by Euclidean distance. Behavioural features are not spherical: session count and total minutes are correlated at 0.81, so the real population sits in elongated, tilted ellipses, and fitting spheres to a tilted ellipse produces clusters that are slices of one real group rather than distinct groups. Three of the eight k-means segments turned out to be the same behavioural population cut into thirds along its long axis, which is why three campaigns had nearly identical conversion rates and nearly identical copy.
The analogy: k-means asks which country a city is in, and mixture modelling asks what languages are spoken there and in what proportion. Most cities have one dominant language. The interesting ones, the ones where policy decisions actually matter, are the border cities, and a map that colours every city with exactly one flag has thrown away precisely the information you needed for those.
Formally: given 24 behavioural features per user over a 28-day window for 4.1 million users, produce a probability distribution over K behavioural components per user, optimising for lifecycle campaign conversion under responsibility-weighted targeting, subject to a monthly refit, stable component identities across refits, and a per-user inference cost under 1 ms.
Framing the Problem
This is density estimation used as soft clustering, which is a different object from partitional clustering even though people use the words interchangeably. A Gaussian mixture model does not assign users to groups. It fits a probability density as a weighted sum of K Gaussians, and the “segment membership” you get out is a by-product: the posterior probability that a given user’s feature vector was generated by each component. Those posteriors are called responsibilities, and they are the deliverable.
That distinction has a consequence people miss. A GMM has a likelihood, so unlike k-means it can be evaluated on held-out data, compared across K by a proper scoring rule, and used to flag users the model has never seen anything like. k-means has no likelihood and cannot do any of those things. The price is that you have to take the Gaussian assumption seriously, and behavioural features violate it enthusiastically.
The target is a responsibility vector, not a label. For each user i and component k, r_ik = P(component k | user i), summing to 1 over k. Campaign targeting then uses two numbers: the top responsibility as a confidence, and the whole vector as a mixing weight. A user at [0.92, 0.04, ...] gets the one campaign. A user at [0.51, 0.44, ...] gets the message that works for both, or gets held back, which turned out to matter more than the routing itself.
Constraints, in the order they bind:
- Component identities must be stable across refits. Campaign configuration references component 3 by number. If a refit renames it, the campaign silently starts targeting a different population. This is the constraint that shaped the most code.
- Interpretability for a marketing team. Each component needs a describable centre in original feature units, not standardised ones. “43 sessions, 812 minutes, 71% morning” is usable; “z score 1.4 on factor 2” is not.
- Refit monthly, inference under 1 ms per user, because responsibilities are recomputed nightly for 4.1 million users as behaviour windows roll forward.
- Covariance structure has to be estimated, not assumed. The whole reason for leaving k-means is that the clusters are not spherical, so a spherical GMM would be a more expensive way to get the same wrong answer.
The success metric is lifecycle campaign conversion rate, measured in an A/B test against the incumbent k-means targeting on the same eight messages. The guardrail metrics are held-out average log-likelihood per user, which is what catches the model degrading before conversion does, and message frequency per user per fortnight, which must not rise, because the easy way to lift conversion is to send everyone everything.
BIC is the textbook way to choose `K` for a mixture model, and at 4.1 million users it is close to useless. With `BIC = -2 log L + p log n`, the likelihood term grows linearly in `n` while the penalty grows only logarithmically, so an extra component has to buy `dp * log(n) / 2` in log-likelihood to pay for itself. At `n` equal to 4.1 million, `log(n)` is 15.2, so a full-covariance component in 26 dimensions adds 5,746 to the penalty and needs 2,873 nats of total log-likelihood, which is 0.0007 nats per user. It always gets it. BIC therefore kept selecting the largest `K` we offered it, all the way to 40, and its curve had no minimum. The honest criterion is **held-out average log-likelihood per user**, and the useful one is the elbow in that curve rather than its maximum, because likelihood keeps improving long past the point where a marketing team can act on the components.
Out of scope: time-varying or Markov-switching mixtures (a user’s component changing as a modelled process rather than as a monthly re-estimate), per-market models, and any causal claim about why a user is in a component. Each is a separate system with its own evaluation burden.
Data and Features
The input is a nightly aggregate: one row per user, 24 features over a rolling 28-day window, built from sessions, plays and workouts. Nine counts (sessions, distinct days active, devices used, workouts, playlists, downloads, searches, shares sent, distinct content types), four durations (total minutes, median and longest session length, minutes per active day), three timing shares (morning, evening, weekend), six content-mix shares, and the two zero-inflated duration features handled below. That is 24 raw columns, which becomes 26 after the zero splits, and D=26 is what every parameter count in this post is computed at.
Every one of those features violates the Gaussian assumption in a different way, and this section is where a GMM project is won or lost.
Right skew. Total minutes over 28 days has a mean of 312 and a median of 141, with a 99.9th percentile of 4,880. Fit a two-component mixture to that raw and the components you get are “the bulk” and “the tail”, which is a description of the distribution’s shape rather than of two kinds of user. The fix is a variance-stabilising transform before fitting, and the choice matters: log1p handled the counts well and left the timing shares alone, while a quantile transform to a normal marginal handled everything but destroyed the interpretability the marketing team needed, since a component centre in quantile space cannot be read back as minutes.
Zero inflation. 38% of users have exactly zero weekend minutes, and 22% have exactly zero workouts. No Gaussian can represent a point mass at zero, so the model spends components trying to cover the spike, and one component ends up being “the people with a zero here” rather than a behaviour. This is a structural zero rather than a small value, and the right treatment is to split the feature: a binary indicator for “any weekend activity” plus a continuous feature conditioned on it being nonzero.
Correlation. Sessions and total minutes correlate at 0.81, and morning share and weekday share at 0.68. This is not a problem to fix, it is the reason full covariance is worth its parameter cost, and it is exactly what a spherical or diagonal model cannot represent.
Reaching for a quantile transform because it makes every marginal exactly normal. It does, and it scored 0.4 nats better than `log1p`, and we did not ship it: a component centre in quantile space cannot be read back as minutes, so the marketing team loses the one thing the model was chosen to give them. It is also a rank-based transform fitted on the training users, and `QuantileTransformer` clips to that training range rather than extrapolating, so every new extreme user collapses onto the same value, which is a poor property for a model whose job includes noticing extremes. The fitted mapping also has to be versioned alongside the model or the responsibilities silently change meaning. `log1p` is monotone, parameter-free, and invertible in closed form, which is worth 0.4 nats.
# The feature pipeline. Each transform corrects one specific violation of the
# Gaussian assumption, and the order matters: split zeros, then stabilise
# variance, then standardise, then whiten.
import numpy as np
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import FunctionTransformer, StandardScaler
# 24 raw features in, 26 after the zero splits, which is the D every parameter
# count in this post is computed at.
COUNT_COLS = ["sessions", "active_days", "devices", "workouts", "playlists",
"downloads", "searches", "shares_sent", "distinct_content_types"]
DURATION_COLS = ["total_minutes", "median_session_minutes",
"longest_session_minutes", "minutes_per_active_day"]
SHARE_COLS = ["morning_share", "evening_share", "weekend_share"]
CONTENT_COLS = ["content_run_share", "content_cycle_share",
"content_strength_share", "content_yoga_share",
"content_audio_share", "content_meditation_share"]
ZERO_INFLATED = ["weekend_minutes", "workout_minutes"]
def split_structural_zeros(frame: pd.DataFrame,
columns=ZERO_INFLATED) -> pd.DataFrame:
"""A point mass at zero is not a small value. Give it its own dimension.
38% of users have exactly zero weekend minutes. Left as one feature, a
component gets spent covering the spike instead of describing a behaviour.
"""
out = frame.copy()
for col in columns:
out[f"{col}_any"] = (out[col] > 0).astype(float)
positive = out.loc[out[col] > 0, col]
fill = float(np.log1p(positive).mean()) if len(positive) else 0.0
out[f"{col}_log"] = np.where(out[col] > 0, np.log1p(out[col]), fill)
out = out.drop(columns=[col])
return out
def build_feature_pipeline() -> Pipeline:
"""log1p the heavy tails, pass the shares through, standardise everything."""
log1p = FunctionTransformer(np.log1p, feature_names_out="one-to-one")
columns = ColumnTransformer([
("counts", Pipeline([("log", log1p), ("scale", StandardScaler())]),
COUNT_COLS),
("durations", Pipeline([("log", log1p), ("scale", StandardScaler())]),
DURATION_COLS),
("shares", StandardScaler(), SHARE_COLS),
("content", StandardScaler(), CONTENT_COLS),
("zeros", StandardScaler(),
[f"{c}_any" for c in ZERO_INFLATED] + [f"{c}_log" for c in ZERO_INFLATED]),
], remainder="drop", verbose_feature_names_out=False)
return Pipeline([("columns", columns)])
Standardise each feature, but do not rotate. The tempting wrong reason to avoid PCA whitening is that it destroys the correlation full covariance exists to model, and that reason is false: a full-covariance mixture is equivariant to any invertible linear map up to a constant `log|det J|`, and a global whitening does not diagonalise the within-component covariances. We measured it, and whitened full covariance still beat whitened diagonal by the same margin as raw. The real reasons are narrower and they all still bind here. Component means in a rotated space cannot be inverse-transformed into readable minutes and sessions, which is the interpretability constraint the whole project rests on. `reg_covar` adds a scalar to the diagonal and is not affine-invariant, so the same value regularises differently after a rotation. And PCA that also truncates discards the low-variance directions where some of the component separation lives. Per-feature standardisation is genuinely required, because `reg_covar` only means something when the features share a scale.
The leakage specific to this problem
A GMM has no labels, so the leakage is not label leakage. It is evaluation leakage, and it takes two forms here.
Fitting on all users and evaluating on all users. A mixture model’s training log-likelihood always improves with K, and the improvement is largely memorisation of local density. We fit on a random 80% of users and score the held-out 20%, and the gap between train and held-out average log-likelihood per user was 0.21 nats at K=8 and 1.94 nats at K=32, which is the entire model-selection story in one number. Without the split, K=32 looks like the best model available.
Time contamination. The 28-day window ends the day the snapshot is taken, and behaviour is strongly seasonal on a fitness app: a model fitted on a January window and evaluated on the same window scores well and describes New Year resolution behaviour. We fit on a window ending 60 days before and evaluate on the most recent window, which dropped apparent held-out likelihood by 0.38 nats and is the number that actually predicts next month.
# Two splits, two jobs. Random for model selection, temporal for honesty.
import numpy as np
import pandas as pd
def user_split(n_users: int, frac_train: float = 0.8,
seed: int = 17) -> tuple[np.ndarray, np.ndarray]:
"""Random user holdout. Mixture log-likelihood improves with K forever on
the training set, so K cannot be chosen without this."""
rng = np.random.default_rng(seed)
order = rng.permutation(n_users)
cut = int(frac_train * n_users)
return np.sort(order[:cut]), np.sort(order[cut:])
def temporal_split(snapshots: pd.DataFrame, fit_snapshot: str,
eval_snapshot: str) -> tuple[pd.DataFrame, pd.DataFrame]:
"""Fit on an older 28-day window, evaluate on the most recent one.
A January window fitted and scored on itself describes resolution
behaviour and scores beautifully. Same users, different windows, and the
held-out likelihood drops by about 0.38 nats: that gap is seasonality,
not noise, and it is what a monthly refit is paying for.
"""
fit = snapshots[snapshots["snapshot"] == fit_snapshot]
evaluate = snapshots[snapshots["snapshot"] == eval_snapshot]
shared = np.intersect1d(fit["user_id"], evaluate["user_id"])
return (fit[fit["user_id"].isin(shared)].sort_values("user_id"),
evaluate[evaluate["user_id"].isin(shared)].sort_values("user_id"))
The Naive Baseline
Two baselines, because the interesting comparison is not against nothing. The floor is the incumbent k-means segmentation that marketing already uses. Above it sits a spherical GMM, which is the closest mixture model to k-means and exists to answer a specific question: how much of the improvement comes from being probabilistic, and how much from modelling covariance?
# The two baselines: the incumbent k-means, and the GMM closest to it.
# A spherical GMM with equal weights and hard assignment IS k-means, so this
# isolates soft assignment from covariance structure.
from sklearn.cluster import MiniBatchKMeans
from sklearn.mixture import GaussianMixture
import numpy as np
def kmeans_baseline(X_train: np.ndarray, X_test: np.ndarray, k: int = 8,
seed: int = 17) -> dict:
"""Hard assignment, spherical by construction, no likelihood available."""
km = MiniBatchKMeans(n_clusters=k, batch_size=8192, n_init=10,
random_state=seed).fit(X_train)
distances = km.transform(X_test)
nearest = np.sort(distances, axis=1)[:, :2]
ambiguous = (nearest[:, 0] / np.maximum(nearest[:, 1], 1e-9)) > 0.85
return {
"name": f"k-means, k={k}",
"ambiguous_share": float(ambiguous.mean()),
"inertia": float(km.inertia_),
"held_out_log_likelihood": None, # k-means has no density to score
}
def spherical_gmm_baseline(X_train: np.ndarray, X_test: np.ndarray, k: int = 8,
seed: int = 17) -> dict:
"""One variance per component. The mixture model nearest to k-means."""
gmm = GaussianMixture(n_components=k, covariance_type="spherical",
reg_covar=1e-4, n_init=5, max_iter=500,
random_state=seed).fit(X_train)
return {
"name": f"GMM spherical, K={k}",
"held_out_log_likelihood": float(gmm.score(X_test)),
"n_parameters": int(gmm._n_parameters()),
"converged": bool(gmm.converged_),
}
Numbers on the held-out 20% of users, 819,000 rows:
- k-means,
k=8: 31.4% of held-out users ambiguous by the 0.85 distance-ratio test, no likelihood available, campaign conversion 3.1%. - Spherical GMM,
K=8: held-out average log-likelihood -29.41 nats per user, 223 parameters. - Diagonal GMM,
K=8: held-out average log-likelihood -27.88 nats per user, 423 parameters.
The spherical GMM is the honest baseline and it barely helps. It gives us responsibilities, which is the thing we wanted, but its components are still spheres in a space where the population lives in tilted ellipses, so the responsibilities it reports are confidently wrong in the overlap region rather than usefully uncertain. Going from spherical to diagonal buys 1.53 nats for 200 extra parameters, which tells us the per-feature variances genuinely differ. Neither can represent the 0.81 correlation between sessions and minutes at all, and that correlation is the shape of the data.
The spherical GMM is the baseline that made the project's argument for it. Being probabilistic on its own moved campaign conversion from 3.1% to 3.2%, which is nothing, and that ruled out the tempting explanation that k-means was failing simply because it was hard. The failure was geometric: spheres in a space of tilted ellipses produce responsibilities that are confidently wrong in exactly the overlap region where uncertainty was the thing we wanted. Choose a baseline that isolates one variable and it will tell you which variable to spend on.
The Solution
A full-covariance Gaussian mixture fitted by EM with reg_covar regularisation, K chosen by the elbow of held-out log-likelihood rather than by BIC, warm-started from the previous month’s parameters and identity-matched by Hungarian assignment so component numbers survive a refit, with responsibilities served rather than hard labels.
The mechanism first. EM on a mixture is a chicken-and-egg problem solved by alternating guesses. If you knew which component generated each user, estimating each component’s mean and covariance would be a one-line calculation. If you knew the components, computing which one probably generated each user would be a one-line calculation. EM does both, alternately: the E step computes responsibilities given current parameters, the M step re-estimates parameters as responsibility-weighted averages. Each iteration cannot decrease the likelihood, which is what makes it converge, and it converges to a local optimum, which is what makes initialisation matter.
Covariance type: what the parameter count actually buys
Four options in scikit-learn, and the parameter count per component in D=26 dimensions after the zero splits:
covariance_type |
Covariance parameters per component | Total at K=12 | Held-out log-likelihood | What it can represent |
|---|---|---|---|---|
spherical |
1 | 335 | -29.38 | Spheres of differing size |
diag |
26 | 635 | -27.61 | Axis-aligned ellipses |
tied |
351 shared | 674 | -26.94 | One shared ellipse shape, different centres |
full |
351 | 4,535 | -25.72 | Independent ellipse shape and tilt per component |
full wins by 1.22 nats over tied for nearly seven times the parameters (4,535 against 674, because tied shares one covariance matrix across all twelve components), and the reason is that the components genuinely have different shapes: the heavy-user component is elongated along the sessions-and-minutes axis, while the lapsing component is compact in duration and spread in timing. tied is the interesting runner-up and the right choice when K is large relative to the data per component, because it pools the covariance estimate across all components and is far more stable at small sample sizes.
The failure that stops most GMM projects: singular covariance
Run a full-covariance GMM on 26 correlated behavioural features without regularisation and it will, reliably, blow up. sklearn raises ValueError: Fitting the mixture model failed because some components have ill-defined empirical covariance, and what is happening underneath is worth understanding because the error message points at a symptom.
A component’s covariance is estimated from the responsibility-weighted scatter of the users assigned to it. If a component collapses onto fewer effective users than dimensions, or onto a set of users who are exactly collinear in some direction (which zero-inflated features guarantee, since weekend_minutes_any and weekend_minutes_log are collinear on the subset with zeros), the covariance matrix is singular. Its determinant is zero, the Gaussian density has a 1/sqrt(det) factor, and the likelihood of that component goes to infinity. EM is maximising likelihood, so it does this on purpose: a component shrinking onto a single point is a global optimum of the objective with infinite likelihood.
# The full-covariance fit that actually works. reg_covar is not a nuisance
# parameter, it is what stops EM from finding the infinite-likelihood solution
# of collapsing a component onto a single point.
from sklearn.mixture import GaussianMixture
import numpy as np
def fit_gmm(X: np.ndarray, n_components: int, covariance_type: str = "full",
reg_covar: float = 1e-4, seed: int = 17,
warm_start_from: GaussianMixture | None = None) -> GaussianMixture:
"""Fit by EM. k-means init unless we have last month's parameters to reuse."""
model = GaussianMixture(
n_components=n_components,
covariance_type=covariance_type,
reg_covar=reg_covar,
init_params="k-means++",
n_init=1 if warm_start_from is not None else 8,
max_iter=500,
tol=1e-4,
random_state=seed,
)
if warm_start_from is not None:
# Warm start is the cheapest half of identity stability: starting from
# last month's optimum usually lands in the same basin, so components
# keep their meaning without any matching step at all.
model.weights_init = warm_start_from.weights_
model.means_init = warm_start_from.means_
# precisions_init wants the full precision matrices, not the Cholesky
# factors, despite the two attributes looking interchangeable.
model.precisions_init = warm_start_from.precisions_
model.fit(X)
if not model.converged_:
raise RuntimeError(f"EM did not converge in {model.max_iter} iterations")
return model
def smallest_stable_reg_covar(X: np.ndarray, n_components: int,
candidates=(1e-6, 1e-5, 1e-4, 1e-3, 1e-2),
seed: int = 17) -> float:
"""Smallest regularisation that fits without a singular covariance.
Do not pick this by guessing. Too small and EM collapses a component; too
large and every covariance is dragged toward a sphere, which throws away
the reason for using full covariance at all.
"""
for reg in candidates:
try:
fit_gmm(X, n_components, reg_covar=reg, seed=seed)
return float(reg)
except (ValueError, RuntimeError):
continue
raise RuntimeError("no candidate reg_covar produced a stable fit")
Raising `reg_covar` until the error goes away, then leaving it there. `reg_covar` adds a constant to the diagonal of every covariance matrix, which shrinks every component toward a sphere. At `1e-2` our fit was stable, converged quickly, and scored `-27.4` nats, which is worse than a diagonal model: we had paid for 4,535 parameters and regularised away the thing they were buying. The correct move is to find the smallest value that fits, and if that value is large enough to hurt, the real problem is elsewhere. In our case it was the collinear zero-split features, and dropping one of each collinear pair let `reg_covar` go from `1e-2` to `1e-4`.
Choosing K: why BIC fails at this sample size
The parameter count for a full-covariance mixture is K * (1 + D + D(D+1)/2) - 1, which at D=26 is K * 378 - 1. With BIC = -2 log L + p log n and n = 3.28 million training users, log(n) = 15.0, so each extra component adds 378 * 15.0 = 5,670 to the penalty. The factor of two is the part people drop: the component has to buy 5670 / 2 = 2,835 nats of total log-likelihood, not 5,670. Total log-likelihood is n times the average, so an extra component only needs to improve the average by 2835 / 3.28e6 = 0.00086 nats to pay for itself. It always does.
# Model selection. BIC has no minimum at this sample size, so the honest
# criterion is held-out average log-likelihood, and the useful one is its elbow.
import numpy as np
def selection_curve(X_train: np.ndarray, X_test: np.ndarray, ks,
covariance_type: str = "full", reg_covar: float = 1e-4,
seed: int = 17) -> list[dict]:
"""Fit each K once, report BIC and held-out likelihood side by side."""
rows = []
for k in ks:
model = fit_gmm(X_train, k, covariance_type=covariance_type,
reg_covar=reg_covar, seed=seed)
rows.append({
"K": int(k),
"n_parameters": int(model._n_parameters()),
"bic": float(model.bic(X_train)),
"train_avg_ll": float(model.score(X_train)),
"held_out_avg_ll": float(model.score(X_test)),
"smallest_weight": float(model.weights_.min()),
})
return rows
def elbow_k(curve: list[dict], min_gain_nats: float = 0.05,
min_weight: float = 0.01) -> int:
"""Largest K where the last component still earns its keep.
Two stopping rules, both operational rather than statistical. A component
must add at least `min_gain_nats` of held-out average log-likelihood, and
must carry at least `min_weight` of the population, because a component
holding 0.3% of users is not a segment a marketing team can staff.
"""
usable = [r for r in curve if r["smallest_weight"] >= min_weight]
best = usable[0]["K"] if usable else curve[0]["K"]
for prev, cur in zip(usable, usable[1:]):
if cur["held_out_avg_ll"] - prev["held_out_avg_ll"] < min_gain_nats:
break
best = cur["K"]
return int(best)
The measured curve, full covariance, held-out 819,000 users:
| K | Parameters | BIC (train) | Train avg LL | Held-out avg LL | Smallest weight |
|---|---|---|---|---|---|
| 4 | 1,511 | 203.3e6 | -30.98 | -31.04 | 0.147 |
| 8 | 3,023 | 185.3e6 | -28.24 | -28.45 | 0.061 |
| 12 | 4,535 | 166.6e6 | -25.39 | -25.72 | 0.029 |
| 16 | 6,047 | 162.2e6 | -24.71 | -25.44 | 0.011 |
| 24 | 9,071 | 156.9e6 | -23.90 | -25.31 | 0.004 |
| 32 | 12,095 | 152.2e6 | -23.18 | -25.12 | 0.002 |
| 40 | 15,119 | 148.9e6 | -22.66 | -25.09 | 0.001 |
BIC falls monotonically to K=40 and would keep falling. Held-out likelihood gains 2.73 nats from K=8 to K=12, then 0.28 to K=16, then 0.35 over the next 24 components put together. The train and held-out gap widens from 0.21 nats to 1.94, which is the overfitting BIC could not see. And the operational rule settles it: at K=16 the smallest component holds 1.1% of users, 45,000 people, which is a campaign nobody will write copy for. K=12 it is.
Twelve components against eight campaigns is not a mismatch to resolve by forcing K=8. Components describe the population and campaigns are a set of messages, and the map between them is many-to-one: four of the twelve share the lapsing-user message with a different send time, and the two heaviest share the multi-device upsell. Tying K to the campaign count would be letting the marketing calendar choose a density model, and when a thirteenth component appears next quarter the useful question is whether it deserves its own copy, not whether it fits the existing eight.
The problem nobody warns you about: label switching
EM has no preferred ordering of components. Refit next month on slightly different data and the optimum is equally valid with the components permuted, so what was component 3 is now component 7. Every quality metric is invariant to this, because likelihood does not care about labelling. The campaign configuration cares enormously.
The fix has two halves. Warm-starting from last month’s parameters usually keeps EM in the same basin and preserves the ordering for free. When behaviour has shifted enough that it does not, the components have to be matched explicitly, and the right tool is the Hungarian algorithm on a cost matrix of distances between old and new component means, which finds the globally optimal one-to-one matching rather than the greedy nearest-neighbour matching that fails whenever two components have both moved.
# Identity stability across refits. Without this, campaign configuration
# referencing "component 3" silently starts targeting a different population
# and no model metric changes, because likelihood is invariant to labelling.
import numpy as np
from scipy.optimize import linear_sum_assignment
from scipy.stats import wasserstein_distance
def match_components(previous: GaussianMixture, current: GaussianMixture,
) -> tuple[np.ndarray, dict]:
"""Globally optimal old-to-new component matching by Mahalanobis-ish cost.
Greedy nearest-neighbour matching fails exactly when it matters: if two
components have both drifted, greedy can assign both to the same target
and then hand the leftovers to whatever remains. Hungarian is O(K cubed),
which at K=12 is free, and it is optimal.
"""
k_prev, k_cur = len(previous.weights_), len(current.weights_)
cost = np.zeros((k_prev, k_cur))
for i in range(k_prev):
# Scale the mean distance by the old component's own spread, so a shift
# of 0.5 inside a broad component costs less than inside a tight one.
scale = np.sqrt(np.diag(np.atleast_2d(previous.covariances_[i])))
for j in range(k_cur):
delta = (current.means_[j] - previous.means_[i]) / np.maximum(scale, 1e-6)
weight_gap = abs(current.weights_[j] - previous.weights_[i])
cost[i, j] = np.linalg.norm(delta) + 5.0 * weight_gap
rows, cols = linear_sum_assignment(cost)
mapping = np.full(k_cur, -1, dtype=int)
for i, j in zip(rows, cols):
mapping[j] = i
matched_cost = float(cost[rows, cols].mean())
return mapping, {
"mean_match_cost": matched_cost,
"unmatched_new_components": int((mapping < 0).sum()),
"max_match_cost": float(cost[rows, cols].max()),
}
def relabel(model: GaussianMixture, mapping: np.ndarray) -> GaussianMixture:
"""Permute a fitted model's components into the previous month's order."""
order = np.argsort(np.where(mapping >= 0, mapping, mapping.max() + 1))
model.weights_ = model.weights_[order]
model.means_ = model.means_[order]
model.covariances_ = model.covariances_[order]
model.precisions_ = model.precisions_[order]
model.precisions_cholesky_ = model.precisions_cholesky_[order]
return model
def responsibility_drift(old_resp: np.ndarray, new_resp: np.ndarray) -> dict:
"""Per-component Wasserstein distance between responsibility distributions.
The monitoring signal. A component whose responsibility distribution has
moved has changed meaning even if its mean has barely shifted, and that is
invisible in log-likelihood.
"""
return {
f"component_{k}": float(wasserstein_distance(old_resp[:, k], new_resp[:, k]))
for k in range(old_resp.shape[1])
}
The design decision that mattered most was serving the whole responsibility vector rather than `argmax`. Everything else in this post is a prerequisite for that one choice being possible: full covariance so the responsibilities are calibrated rather than confidently wrong, `reg_covar` so the fit exists at all, Hungarian matching so the vector's components mean the same thing in February as in January. The conversion lift came from two specific uses of the vector, and neither is available from a label: weighting the message mix for users whose top responsibility was between 0.4 and 0.7, and **holding back entirely** the 6.2% of users whose top responsibility was below 0.4. That holdback was worth more than the routing.
Evaluation and Metrics
Four things get measured, and they answer different questions. Held-out likelihood asks whether the density fits. Calibration asks whether the responsibilities mean what they say. Identity stability asks whether the components survive a refit. Campaign conversion decides.
Held-out average log-likelihood per user is the right density metric and it needs one interpretation note: it is reported per user rather than as a total, so it is comparable across differently sized holdouts, and it is negative because a 26-dimensional continuous density evaluated at a point is a density and not a probability. Only differences matter. A gain of 1 nat per user means the held-out data is e times more likely under the new model.
Responsibility calibration is the metric most GMM write-ups skip and it is the one that justifies soft assignment. If the model says a user has responsibility 0.7 for component k, then among all users with responsibility near 0.7 for component k, roughly 70% should behave like component k. There is no label to check that against, so we check it by proxy: hold out a random 20% of each user’s sessions, fit on the rest, and ask whether the held-out sessions of a 0.7 user look like component k’s distribution 70% of the time. This is a reliability diagram for clustering, and it is what separated full covariance from diagonal more sharply than likelihood did.
# The four evaluation layers. Calibration is the one that justifies soft
# assignment, and the one most GMM write-ups skip.
import numpy as np
import pandas as pd
def held_out_likelihood(model, X_train: np.ndarray, X_test: np.ndarray) -> dict:
"""Average log-likelihood per user, plus the train-test gap.
The gap is the overfitting BIC cannot see: 0.21 nats at K=8 and 1.94 at
K=32 on the post's data, while BIC fell monotonically across that range.
"""
train, test = float(model.score(X_train)), float(model.score(X_test))
return {"train_avg_ll": train, "held_out_avg_ll": test,
"generalisation_gap": train - test}
def responsibility_calibration(model, X_holdout: np.ndarray,
n_bins: int = 10) -> pd.DataFrame:
"""Reliability of the top responsibility against held-out behaviour.
For each bin of predicted top responsibility, the share of users whose
held-out feature vector is still most likely under the same component.
Perfect calibration puts observed on the diagonal against predicted.
"""
first, second = np.array_split(X_holdout, 2, axis=0)[:2]
n = min(len(first), len(second))
resp_a = model.predict_proba(first[:n])
resp_b = model.predict_proba(second[:n])
top = resp_a.max(axis=1)
agree = resp_a.argmax(axis=1) == resp_b.argmax(axis=1)
bins = np.clip(np.digitize(top, np.linspace(0, 1, n_bins + 1)) - 1,
0, n_bins - 1)
rows = []
for b in range(n_bins):
mask = bins == b
if mask.sum() < 50:
continue
rows.append({
"bin": f"{b / n_bins:.1f} to {(b + 1) / n_bins:.1f}",
"n_users": int(mask.sum()),
"mean_predicted": float(top[mask].mean()),
"observed_agreement": float(agree[mask].mean()),
})
frame = pd.DataFrame(rows)
frame["calibration_error"] = (frame["mean_predicted"]
- frame["observed_agreement"]).abs()
return frame
def outlier_share(model, X: np.ndarray, quantile: float = 0.001) -> dict:
"""Users in the far tail of the fitted density. k-means cannot do this.
A mixture model has a likelihood, so "this user looks like nothing the
model has seen" is a computable statement rather than a hunch. These users
are excluded from campaigns rather than assigned to whichever component
happens to be nearest.
"""
scores = model.score_samples(X)
threshold = float(np.quantile(scores, quantile))
return {"threshold": threshold,
"share_below": float((scores < threshold).mean()),
"median_score": float(np.median(scores))}
Baseline against solution, held-out 819,000 users and an A/B test over 1.4 million users per arm:
| Configuration | Held-out avg LL | Calibration error | Identity stability | Ambiguous (top r 0.4 to 0.7) | Campaign conversion |
|---|---|---|---|---|---|
| k-means, k=8 (incumbent) | n/a | n/a | 0.61 | 31.4% | 3.1% |
| GMM spherical, K=8 | -29.41 | 0.184 | 0.68 | 24.1% | 3.2% |
| GMM diagonal, K=8 | -27.88 | 0.121 | 0.71 | 19.8% | 3.5% |
| GMM full, K=8 | -28.45 | 0.058 | 0.74 | 14.2% | 3.9% |
| GMM full, K=12, argmax targeting | -25.72 | 0.041 | 0.76 | 12.7% | 4.0% |
| GMM full, K=12, warm start plus Hungarian | -25.72 | 0.041 | 0.97 | 12.7% | 4.2% |
| GMM full, K=12, responsibility-weighted plus holdback | -25.72 | 0.041 | 0.97 | 12.7% | 4.4% |
Three things in that table are worth more than the headline. Calibration error improves by more than a factor of three from spherical to full at matched K=8, from 0.184 to 0.058, while held-out likelihood improves by 0.96 nats, which says covariance structure matters much more for the usefulness of the responsibilities than for the fit. Identity stability jumps from 0.76 to 0.97 from warm starting and matching alone, with the model itself unchanged, and that single non-modelling change was worth 0.2 points of conversion. And the last two rows share an identical model: the final 0.2 points came from how the responsibilities were used, not from any improvement in the density.
The number that catches a silent regression is **per-component responsibility drift**, the Wasserstein distance between this month's and last month's distribution of responsibilities for each component. Held-out likelihood will not move, because a component that has quietly changed meaning still fits the data. Component weights will not move much either. What moves is the shape of the responsibility distribution for one component, and that is the signal that a campaign is now going to a different population. We alert when any component's responsibility Wasserstein distance exceeds 0.08, and that has fired three times: twice for genuine seasonal shifts that needed the campaign copy revisited, and once when an upstream change to the session aggregation silently doubled the session count for tablet users.
Common Pitfalls and Failure Modes
| Pitfall | Why It Happens | How to Detect | How to Fix |
|---|---|---|---|
| Singular covariance, EM crashes or returns infinite likelihood | A component collapses onto fewer effective users than dimensions, or onto collinear features; density has a 1/sqrt(det) factor so likelihood diverges |
ValueError on ill-defined covariance, or a component weight near zero with an enormous likelihood |
Set reg_covar to the smallest value that fits; remove collinear features rather than raising it further |
| BIC selects the largest K offered | The p * log(n) penalty grows logarithmically while log-likelihood grows linearly in n; at millions of rows the penalty is negligible |
BIC curve with no minimum across the whole K range | Select on held-out average log-likelihood, and stop at the elbow plus a minimum component weight |
| Components describe the skew, not the behaviour | Raw counts and durations are heavily right-tailed, so one component covers “the bulk” and one covers “the tail” | Component means separated almost entirely along one heavy-tailed feature | log1p or quantile-transform before fitting; check that each component differs on more than one feature |
| A component covers a spike at zero | 38% exact zeros cannot be represented by any Gaussian, so a component is spent on the point mass | A component with tiny variance centred exactly at the zero-feature value | Split into a binary indicator plus a continuous feature conditioned on nonzero |
| Label switching across refits | EM has no canonical component ordering, and every likelihood-based metric is invariant to permutation | Downstream configuration targeting a component whose population has changed, with no metric moving | Warm start from the previous fit, then Hungarian-match on component means and weights |
| PCA whitening or truncation before the fit | Whitening is reflexively applied as preprocessing; truncation looks like a free dimensionality win | Component means no longer inverse-transform to readable units; a tuned reg_covar behaving differently after the rotation |
Standardise per feature without rotating. Full covariance is affine-equivariant, so whitening alone is harmless to the fit and harmful to the deliverable; truncation is what loses information |
Treating argmax responsibility as a label |
The vector is inconvenient and a label is easy to join on | The 6.2% of users with a top responsibility under 0.4 receiving a confident assignment anyway | Serve the vector; weight the message mix in the 0.4 to 0.7 band and hold back below 0.4 |
The most common beginner mistake on this exact problem is fitting a GMM, calling `predict` instead of `predict_proba`, and shipping it as a better k-means. Everything expensive about a mixture model, the covariance estimation, the likelihood, the EM iterations, exists to produce a calibrated distribution, and `argmax` discards all of it. The model then costs far more to fit than k-means and delivers a partition that is slightly different rather than better: in our A/B test, full covariance at `K=12` with `argmax` targeting was worth 0.9 conversion points over k-means, and the same model with identity matching and responsibility-weighted targeting was worth 1.3. That remaining 0.4 splits evenly between the identity fix and the method call, so `predict_proba` alone was 0.2 points, which is still more than the entire gain from `K=8` to `K=12`.
Scaling and Productionizing
The refit is monthly and the scoring is nightly, which splits the operational concerns cleanly: fitting is the expensive, fragile, human-supervised part, and scoring is a matrix multiply.
Scoring is cheap and exact. Computing responsibilities for one user is K Gaussian density evaluations, and with the Cholesky factors precomputed each is a triangular solve in D=26 dimensions. That is 12 times about 700 floating-point operations, and the whole 4.1 million user population scores in 90 seconds on 16 cores. sklearn’s precisions_cholesky_ is what makes this fast; recomputing a matrix inverse per component per user is D cubed work against D squared, roughly 26 times more arithmetic at D=26 for an identical answer.
Fitting is the part that needs a budget:
User snapshot 4.1e6 rows x 24 raw features, parquet = 790 MB
After zero splits 4.1e6 x 26 float32 = 427 MB
Train split 3.28e6 x 26, fits in memory = 341 MB
EM, K=12 full, n_init=8 8 restarts x ~140 iterations, 16 cores = 31 min
EM, warm started, n_init=1 ~40 iterations from last month's optimum = 3 min 50 s
Selection curve, 7 values K in 4..40, one fit each, no restarts = 1 h 12 min
Hungarian matching 12 x 12 cost matrix = 4 ms
Nightly scoring 4.1e6 users, Cholesky triangular solves = 90 s
Served artifact weights, means, 12 x 26 x 26 Cholesky, JSON = 170 KB
Per-user inference 12 density evaluations in 26 dimensions = 0.21 ms
Warm starting is an eight-fold saving on the monthly refit and it is not primarily a cost optimisation: the reason n_init=8 is needed on a cold fit is that EM finds different local optima from different initialisations, and the reason one restart suffices when warm started is that last month’s optimum is already in the right basin. The cost saving is a side effect of the stability fix.
Above roughly 50 million users the full dataset stops fitting in memory and the answer is not distributed EM but subsampling: a mixture model’s parameters are estimated from responsibility-weighted sufficient statistics, and 5 million users estimate a 12-component model in 26 dimensions to well within the month-to-month variation. We verified this directly: fitting on a 2 million user sample rather than 3.28 million changed held-out average log-likelihood by 0.03 nats and moved no component mean by more than 0.04 standardised units. Distributed EM is the right answer only when K is large enough that per-component sample size becomes the binding constraint, which for behavioural segmentation it almost never is.
Refresh cadence is set by responsibility drift. We refit monthly, and the measurement justifying monthly rather than quarterly is the decay of held-out likelihood on a frozen model: -25.72 nats in its first month of service, -25.98 in the second, -26.51 in the third, -27.93 in the fourth. By the fourth month a freshly fitted diagonal model at -27.61 beats the stale full-covariance one, which is the point at which the extra parameters have stopped earning anything.
The monitoring signal for silent degradation is the triple (per-component responsibility Wasserstein distance, smallest component weight, share of users below the outlier threshold). Responsibility drift catches a component changing meaning. The smallest component weight catches a component dying, which happens when a behaviour genuinely disappears from the population and leaves EM with a component to spend elsewhere. The outlier share catches upstream data problems fastest of the three, because a feature pipeline bug pushes users into the density’s tail immediately, where a behavioural shift moves them gradually. Any component’s drift above 0.08 pages someone; a smallest weight below 0.01 blocks the refit from promoting.
Gaussian mixtures have one canonical production lineage, and it is not marketing segmentation: Reynolds and Rose's 1995 speaker-identification work and Reynolds, Quatieri and Dunn's 2000 GMM-UBM system in Digital Signal Processing were the state of the art in speaker verification for over a decade, and the engineering there is instructive. They fit one large Universal Background Model on pooled data from all speakers, then adapt it per speaker by MAP adaptation of the means only, leaving covariances and weights shared. That is the same problem we have with per-component sample size, solved by pooling instead of by regularisation, and it is worth borrowing when `K` is large. The lineage continued into i-vectors (Dehak and colleagues, 2011), where the GMM supervector became a fixed-length embedding, which is the direct ancestor of every modern speaker-embedding system. On the segmentation side, the honest note is that recommendation and lifecycle systems at Netflix and Spotify scale have largely moved to learned embeddings with soft nearest-neighbour retrieval rather than parametric mixtures; GMMs survive where the components must be describable to a human in original feature units, which is exactly the constraint a marketing team imposes.
Alternative Approaches
| Approach | Held-out avg LL | Fit and serve cost | Interpretability | Best fit |
|---|---|---|---|---|
| GMM, full covariance, K=12 | -25.72 | 31 min cold, 3 min 50 s warm, 0.21 ms per user | Good: component means readable in original units after inverse transform | Soft membership needed and components must be describable to a non-technical team |
| GMM, tied covariance, K=12 | -26.94 | 14 min, 0.18 ms per user | Good, and the shared shape is itself interpretable | Large K or thin data per component, where pooling beats independent estimation |
| Bayesian GMM, variational, K=30 prior | -25.81 | 1 h 20 min, 0.24 ms per user | Moderate: effective K is inferred, which is harder to explain | You do not want to choose K, and can accept a prior doing it |
| k-means, k=8 | n/a, no density | 4 min, 0.02 ms per user | Excellent: centroids are single points | Hard partition genuinely wanted, speed matters, uncertainty does not |
| HDBSCAN on UMAP projection | n/a, no density | 26 min, no incremental scoring | Poor: components live in a projected space with no units | Irregular non-elliptical cluster shapes and explicit outlier rejection |
| Latent class analysis on discretised features | comparable after binning | 22 min, 0.15 ms per user | Excellent for categorical profiles | Features are genuinely categorical rather than continuous |
| Two-tower embedding with soft retrieval | n/a, different objective | 6 h training, 1.2 ms per user | Poor: no describable components | Maximum targeting accuracy, no requirement to explain a segment |
What we shipped is the top row, and the deciding factor was not the 1.22 nats over tied. It was that a component’s mean, inverse-transformed back through the log1p and standardisation, reads as “43 sessions, 812 minutes, 71% morning, 2.1 devices”, and a marketing team can write copy against that sentence. The Bayesian variational GMM is close on likelihood and is the better choice if you would rather not defend a choice of K, at the cost of explaining a Dirichlet process prior to someone who wants to know how many segments there are.
We would switch to tied covariance immediately if K needed to exceed about 25, because per-component sample size becomes the binding constraint and pooling the covariance is a better use of the data than regularising 25 separate estimates. We would abandon mixtures entirely for the two-tower approach if the interpretability requirement were dropped, and that is the honest summary of the tradeoff: a GMM is not the most accurate way to target users, it is the most accurate way to target users while still being able to say what a segment is.
Key Takeaways
- The responsibility vector is the product;
argmaxthrows the project away. Full covariance atK=12with hard assignment was worth 0.9 conversion points over k-means, and the same model with identity matching and responsibility-weighted targeting was worth 1.3. Callingpredict_probainstead ofpredictaccounted for 0.2 of that, which is more than the entire gain fromK=8toK=12. - BIC does not work at large n. The penalty grows as
log(n)while log-likelihood grows asn, so an extra component needed only 0.0017 nats of average improvement to pay for itself and BIC fell monotonically toK=40. Select on held-out likelihood and stop at the elbow. reg_covaris load-bearing, and a large value is a symptom. Without it EM finds the infinite-likelihood solution of collapsing a component onto a point. With1e-2the fit was stable and scored worse than a diagonal model, because regularisation had erased what full covariance was buying. The real fix was removing collinear features.- Do not rotate the features, and know why. Full covariance is affine-equivariant, so PCA whitening does not damage the fit the way it is usually claimed to. It damages the deliverable: a component mean in a rotated space cannot be read back as minutes, and
reg_covaris not affine-invariant, so the regularisation you tuned no longer means the same thing. - Structural zeros need their own dimension. 38% exact zeros cannot be represented by any Gaussian, so a component gets spent covering the point mass. A binary indicator plus a conditional continuous feature is two columns and fixes it.
- Label switching is an operations bug that no model metric can see. Likelihood is invariant to component permutation, and the campaign configuration is not. Warm starting plus Hungarian matching took identity stability from 0.76 to 0.97 and was worth 0.2 conversion points with the model unchanged.
- Calibration separated the covariance types better than likelihood did. At matched
K=8, spherical to full improved held-out likelihood by 0.96 nats and calibration error by a factor of three, and calibration error is what predicted the conversion difference. A percentage change in a log-density is meaningless, so report the nats. - The holdback mattered more than the routing. Suppressing campaigns for the 6.2% of users whose top responsibility was below 0.4 delivered more lift than reweighting the message mix for the ambiguous middle, because the cost of a wrong message is not zero.
The counter-intuitive lesson is that the best thing this model does is decline to answer. Everything in the project points toward a better assignment, and the single most valuable output turned out to be the flag on 6.2% of users saying the model does not know. k-means cannot produce that flag at any level of tuning, because nearest-centroid always has a nearest centroid, and a system that is never uncertain is not confident, it is uninformative about its own uncertainty. The 1.3 conversion points did not come from being right more often. They came from knowing when we were guessing.
Frequently Asked Questions
Q: Why not just use k-means, which is faster and simpler?
A: Use it if you genuinely want a hard partition and do not care about uncertainty. On this problem 31.4% of users sat within 15% of a second centroid’s distance and k-means reported no uncertainty about any of them, which means almost a third of the targeting decisions were coin flips presented as facts. k-means also has no likelihood, so it cannot score held-out data, cannot be compared across k by a proper scoring rule, and cannot flag a user as unlike anything it has seen. That last capability turned out to be the most valuable single output of the project.
Q: Why not a Bayesian GMM, which infers K for you? A: It is a legitimate choice and scored within 0.09 nats of our model, so the accuracy argument is a wash. Two reasons we did not ship it. The effective number of components depends on the Dirichlet concentration prior, so you have not removed a hyperparameter, you have replaced a defensible one with a less intuitive one, and “how many segments are there” is a question a marketing team will ask. And its fit took 1 hour 20 minutes against 31 minutes, with variational approximation making warm starting across refits less straightforward, which is where our stability fix lives.
Q: Why full covariance rather than diagonal, given the parameter cost?
A: Because the correlation is the shape of the data. Sessions and total minutes correlate at 0.81, so the population lives in tilted ellipses, and a diagonal model can only fit axis-aligned ones. At matched K=12 the difference was 1.89 nats of held-out likelihood and, more importantly, a factor-of-two reduction in calibration error, from 0.121 to 0.058, which is what the responsibilities are for. We would reverse this decision if K went above about 25, where per-component sample size makes 25 independent 351-parameter covariance estimates worse than one pooled estimate.
Q: How do I choose reg_covar without guessing?
A: Sweep upward from 1e-6 and take the smallest value that fits without a singular-covariance error, which is what smallest_stable_reg_covar does. Then check that the value you landed on is not doing damage: if the held-out likelihood of the full-covariance model is no better than a diagonal model, the regularisation has erased the covariance structure and the real problem is collinearity or too few effective samples per component. Ours went from 1e-2 to 1e-4 purely by dropping one of each collinear zero-split pair.
Q: Why report held-out log-likelihood per user, and why is it negative?
A: Per user rather than summed so it is comparable across holdouts of different sizes, and negative because a continuous density in 26 dimensions evaluated at a point is a density, not a probability, so its log is unbounded below and its absolute value means nothing. Only differences are interpretable: 1 nat of improvement means the held-out data is about 2.7 times more likely under the new model. The train-to-held-out gap is the more useful reading, because it is the overfitting that BIC could not detect, widening from 0.21 nats at K=8 to 1.94 at K=32.
Q: What breaks first in production? A: Component identity, and it breaks silently. A refit produces a perfectly good model whose component 3 is last month’s component 7, every likelihood metric looks fine or better because likelihood is invariant to permutation, and eight campaign configurations quietly start targeting the wrong populations. Warm start, Hungarian-match, and alert on per-component responsibility drift rather than on any aggregate fit statistic, because the aggregate cannot see it.
Interview Questions
Q: Your GMM fit crashes with a singular covariance error. Explain what is happening and how you would fix it.
Expected depth: Start from the density: a multivariate Gaussian has a 1/sqrt(det(Sigma)) normalising factor, so as a covariance approaches singularity the density at its mean diverges. EM is maximising likelihood, so collapsing a component onto a single point or a lower-dimensional subspace is not a bug, it is a global optimum of the objective with infinite likelihood. Name the two causes: a component with fewer effective samples than dimensions, and exactly collinear features. Give the fixes in order: reg_covar as ridge regularisation on the diagonal, removing collinear features, reducing K, switching to tied covariance to pool the estimate. Add that a large reg_covar shrinks every component toward a sphere, so a value big enough to guarantee stability may have erased the reason for using full covariance.
Q: You have 5 million rows. BIC keeps choosing the largest number of components you offer. Why, and what do you use instead?
Expected depth: Write out BIC as -2 * log L + p * log(n). The likelihood term scales with n and the penalty with log(n), so as n grows the penalty becomes negligible in relative terms. Keep the factor of two, which is the usual slip: a component has to buy dp * log(n) / 2 in log-likelihood, so at 5 million rows with log(n) of 15.4, a 378-parameter component needs 378 * 15.4 / 2 / 5e6, roughly 0.00058 nats of average improvement, to pay for itself. Note that BIC is derived as an asymptotic approximation to the marginal likelihood under regularity conditions that mixture models violate anyway, since the likelihood is unbounded and the parameters are not identifiable under permutation. Propose held-out average log-likelihood with an elbow rule, cross-validation if the data is small, and an operational floor on minimum component weight because a component holding 0.2% of the population is not actionable regardless of its likelihood contribution.
Q: Explain the E step and the M step, and why EM converges.
Expected depth: E step: compute responsibilities r_ik = w_k * N(x_i | mu_k, Sigma_k) normalised over k, which is the posterior probability that component k generated observation i. M step: re-estimate w_k as the mean responsibility, mu_k as the responsibility-weighted mean of the data, and Sigma_k as the responsibility-weighted scatter about that mean. Convergence comes from EM being a lower-bound maximisation: the E step constructs a bound on the log-likelihood that is tight at the current parameters, the M step maximises it, so the log-likelihood cannot decrease. Then the caveats that matter in practice: convergence is to a local optimum, so initialisation and n_init matter; the likelihood is unbounded so “converged” can mean a degenerate solution; and convergence is in likelihood, not in parameters, which is exactly why label switching happens.
Q: How would you evaluate a soft clustering model before shipping it? Expected depth: Four layers with distinct jobs. Held-out average log-likelihood per user, on a user-level split, for density fit, plus the train-to-held-out gap as the overfitting signal. Responsibility calibration, checked by splitting each user’s own behaviour and asking whether a 0.7 responsibility corresponds to 70% agreement, because a soft assignment is only worth more than a hard one if the numbers mean something. Identity stability across refits, by Hungarian-matched component distance, because downstream systems reference components by index. An online experiment as the only launch gate. Be explicit that internal cluster-validity indices like silhouette are inappropriate for a mixture model, because they measure compactness under a distance metric while the model is fitting a density, and a well-fitted overlapping mixture will score badly by construction.
Q: A month after launch the model looks fine on every metric but the campaigns are underperforming. Diagnose it. Expected depth: Reach for label switching first: likelihood, BIC, component weights and calibration are all invariant to a permutation of components, and a refit’s optimum is equally valid permuted, so a campaign referencing component 3 can silently target last month’s component 7 with nothing moving. Diagnose by Hungarian-matching this month’s components to last month’s and looking at the matching cost, and by per-component Wasserstein distance between responsibility distributions. Then the alternatives: genuine distribution shift, where component means have moved and the copy is now wrong; a component dying and its population being redistributed; an upstream feature-pipeline change, which is distinguishable because it shows up immediately in the share of users below the outlier threshold rather than gradually. The structural fix is warm starting plus explicit matching plus a drift alarm on the responsibility distributions rather than on any aggregate fit statistic.
View full code for this problem