Skip to content
Tech Interview Prep
Technical interview guide

Supervised vs. Unsupervised Learning

Learning from labeled examples versus finding structure in unlabeled data, and where semi-supervised and reinforcement learning fit.

Minutes to read
3
Practice MCQs
25
Interview Q&A
25
Edition
v5
Editorial status
Reviewed

Scope: scikit-learn stable documentation and Google Machine Learning Crash Course accessed 2026-08-30..

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-1

Compare supervised and unsupervised learning using a product example.

Answer

Short answer. Supervised learning needs labelled outcomes and predicts one; unsupervised learning has no target and finds structure. Choose by what you have and what consumes the output: a routing decision needs a label, a theme report for humans does not.

Assumptions. A support org with ~120k tickets/month, 40 existing routing queues, a model that assigns each ticket to one queue, and a product team asking what customers are complaining about. Numbers below are illustrative, not measured.

Supervised: ticket routing. Train logistic regression or gradient-boosted trees on TF-IDF or 768-dim sentence embeddings of historical tickets, labelled with the queue that resolved them. Hold out 10% stratified. Report macro-F1 and per-class recall, not accuracy: queues are imbalanced and a security-incident queue matters more than a password reset.

Unsupervised: theme discovery. No queue labels. Embed tickets, run k-means (k=40) or HDBSCAN, read the top terms per cluster. This answers "what are people talking about", not "where does this ticket go".

Supervised routingUnsupervised themes
TargetQueue label from historyNone
AlgorithmLogistic regression / GBM on embeddingsk-means (k=40), HDBSCAN
Metricmacro-F1, per-class recall on held-out 12ksilhouette, cross-seed ARI, human audit
Failurelabel drift, rare-class collapseseed instability, cluster drift, no ground truth
Ships whenper-class recall floor met on a fresh holdoutmost clusters stable across seeds and interpretable

What the routing model costs when it is wrong. At 71% top-1 accuracy, 120k × 0.29 = 34,800 misroutes/month. If 30% of those cost an extra 4 minutes of agent time at $60/hr loaded: 34,800 × 0.3 × 4 / 60 ≈ 696 agent-hours ≈ $41,800/month. That is the number that justifies or kills the project, and it is why per-class recall on the expensive queues is the metric to gate on.

Failure modes, with detection.

  • Label drift. A new intent ("billing dispute: crypto") appears; the classifier forces it into the nearest old queue with high confidence. Detect with weekly macro-F1 on 2k freshly labelled tickets, plus PSI on the predicted-label distribution against the training prior: alert at 0.2.
  • Rare-class collapse. Security incidents are 0.4% of tickets and get 0.3 recall while macro-F1 looks fine. Detect with a per-class recall floor (e.g. security ≥ 0.85), reported per queue, not aggregated.
  • Seed instability. Run k-means five times with different seeds and compute ARI between partitions. If mean pairwise ARI < 0.6, the clusters are an artefact of initialization. In a plausible run, 22 of 40 clusters matched across seeds; the other 18 are noise and should not reach product.
  • Cluster drift. Centroids move as the product changes. Track cosine distance between this month's and last month's centroids; re-read any cluster above 0.15 before republishing.
  • No ground truth. A cluster can be coherent and useless ("tickets containing 'the'"). Audit 50 sampled tickets per cluster, and only keep a cluster if routing to it measurably changes handling time.

When not to use each. Don't ship unsupervised clusters as a router: with no ground truth there is no way to catch a confidently wrong assignment. Don't ship supervised routing when you have under ~200 labelled examples per class: bootstrap with active learning or weak supervision (label functions over regex and keywords) first, then train. If you have a decision but no labels, that middle path is the answer, not either extreme.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-5

How do classification and regression differ in outputs and evaluation?

Answer

Core answer (first 90 seconds). The difference is the output space, and evaluation follows from it. A classifier emits a score per class; a decision needs a threshold on top of that score, so evaluation splits in two: is the ranking right (ROC-AUC, PR-AUC) and is the score a usable probability (log loss, Brier score, calibration)? A regressor emits a point on a continuum, or a distribution over it, and the metric you pick silently chooses which functional of the conditional distribution you are fitting: squared error is minimized by the conditional mean, absolute error by the conditional median, pinball loss by the conditional quantile. Picking the metric is picking the target. Neither family has a universal metric: prevalence, tail weight, asymmetry and the cost of the actual decision decide.

Same MAE, different RMSE. Four held-out rows, residuals:

residualsMAERMSE
1, 1, 1, 11.001.00
0, 0, 0, 41.002.00

RMSE squares before averaging, so one 4-unit miss contributes as much to the loss as sixteen 1-unit misses. If a single miss costs the same as four small ones (a delivery ETA, a staffing forecast) MAE matches your cost and RMSE does not. If large misses are disproportionately bad (capacity planning, where being 4 short is worse than four separate 1-short days) RMSE is the honest one.

Same ranking, different calibration. 100 held-out rows, 20 positives. Both models rank every positive above every negative, so ROC-AUC = 1.00 for both.

modelpositive scoresnegative scoresflagged at 0.5precisionrecall
A0.600.40201.001.00
B0.900.801000.201.00

Identical AUC, precision 1.00 vs 0.20 at the same threshold. AUC is invariant to any monotone transform of the score; the decision is not. Log loss and Brier are proper scoring rules, minimized only by the true probability, so they catch what AUC cannot.

Failure modes.

  • Threshold miscalibration. Train on a class-balanced subsample, or with class weights, and the intercept shifts: raw scores are no longer probabilities, so 0.5 stops being the decision boundary. Detect with a reliability diagram and expected calibration error on held-out data, and compare mean predicted probability against observed prevalence. Fix by recalibrating (Platt, isotonic) on a held-out split, not by moving the threshold by hand.
  • RMSE chasing the tail. A fat-tailed target or one bad sensor reading dominates the loss and the model bends toward it. Detect by reporting MAE and RMSE together and inspecting the residual distribution; a large gap means a few rows own the fit.
  • Skewed regression targets. Fit with MSE and evaluate with MAE and you optimized the mean but are being scored on the median. Detect by plotting residuals against prediction: systematic bias on the tail is the signature.
  • Rare positives. At 1% prevalence, predicting all-negative gives 99% accuracy. Use PR curves, not ROC, and report precision at the operating threshold.

When not to reach for the default. Ordinal or count targets want ordinal or Poisson/Negative-Binomial losses, not squared error. If the decision needs an interval, quantile regression or conformal prediction gives one; a point prediction plus RMSE does not. Asymmetric costs want a cost-weighted threshold, not a new metric.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-2

How do you define a supervised-learning target safely?

Answer

The first thing I'd do is pin down the prediction unit and the exact moment the prediction is made. Assume we're building a churn model for a subscription service: unit is user, prediction time is end of day, outcome is cancellation. A safe target definition has four parts: feature cutoff, label window, outcome event, and label maturity delay. Feature cutoff: only use data with timestamp < prediction time. Label window: the outcome must occur within a fixed window after prediction time, say 30 days. Outcome event: a cancellation record. Label maturity delay: you can't know the label until the window closes, so you only train on data older than 30 days.

Leakage happens when you accidentally include post-prediction data. For example, if you join the cancellation table without filtering by date, a user who cancels on day 10 will have that cancellation date as a feature, and the model learns to predict the label from the label. Treatment changes the label distribution: if you run a retention campaign, churn drops from 5% to 3%, so a model trained on pre-campaign data will be miscalibrated.

Alternatives: direct outcome (actual cancellation) vs proxy (no login in 7 days). Direct is accurate but delayed 30 days; proxy is immediate but noisy: it might flag users who are on vacation. Deciding criterion: if the intervention is expensive (e.g., a $50 credit), use direct; if you're just prioritizing outreach, proxy is fine but validate it against direct on a holdout.

Failure modes and detection: label drift. Monitor the positive rate weekly; if it moves more than 2 percentage points, investigate. Leakage: compare offline AUC to online AUC; if offline is 0.95 and online is 0.70, you have leakage. Silent relabeling: version your label definition (e.g., label_v1, label_v2) and trigger a new evaluation when it changes.

Here's a concrete trace. User A: signup Jan 1, last login Feb 1, cancel Mar 1. Prediction time Feb 1. Label window Feb 1–Mar 3. Label = 1. Features: logins before Feb 1. If we accidentally include cancel date, the model sees Mar 1 and predicts perfectly. Code snippet (Python 3.9, pandas 1.3):

Python
import pandas as pd
# events: user_id, event_time, event_type
cutoff = pd.Timestamp('2023-02-01')
window_end = cutoff + pd.Timedelta(days=30)

# Features: only events before cutoff
features = events[events.event_time < cutoff]

# Labels: for each user, 1 if cancel within window, else 0
cancels = events[(events.event_type == 'cancel') &
                 (events.event_time >= cutoff) &
                 (events.event_time <= window_end)]
labels = pd.DataFrame({'user_id': events.user_id.unique()})
labels['label'] = labels.user_id.isin(cancels.user_id).astype(int)

Table comparing direct vs proxy (hypothetical figures):

Label typeLatencyAccuracy (AUC)Cost per label
Direct cancellation30 days0.85$0 (logged)
Proxy: no login 7d7 days0.72$0

Arithmetic: if you have 1 year of data, a 30-day label delay means you lose the last 30 days for training, reducing training set by ~8% (30/365). If you use a 7-day proxy, you lose only 2%.

The safe definition is a contract: document it, version it, and monitor it. That's how you avoid the silent failures that make a model look great offline and fail in production.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-15

How do self-supervised, semi-supervised, active, and weak supervision differ?

Answer

Core answer (first 90 seconds)

All four answer one question, where does the training signal come from, and they differ in what you spend to get it.

  • Self-supervised: no labels. You invent a pretext task whose target is derived from the raw input (predict a masked token, match two augmented views) and hope the representation transfers.
  • Semi-supervised: a few labels plus a lot of unlabeled data, exploiting an assumption that the decision boundary sits in a low-density region.
  • Active learning: unlabeled data plus a human budget; the model picks which points a human labels.
  • Weak supervision: many cheap noisy label sources (rules, heuristics, distant supervision) whose errors you estimate and denoise.

They compose: self-supervised pretrain → weak supervision to bootstrap labels → active learning to spend a small human budget on uncertain cases → semi-supervised to absorb the rest.

ApproachSignal sourceKey assumptionNamed methodFailure modeDetection
Self-supervisedpretext task on raw datastructure predicts downstream-relevant featuresBERT MLM (15% mask), MAE (75% patch mask), SimCLRpretext–downstream mismatch; representation collapselinear probe on frozen features vs full fine-tune gap
Semi-supervisedfew labels + unlabeledcluster/manifold: boundary in low-density regionFixMatch (confidence threshold τ=0.95), pseudo-labeling, MixMatchconfirmation bias. Wrong pseudo-labels reinforcepseudo-label accuracy on a held-out labeled slice, per round
Activemodel chooses points for human labelsuncertainty correlates with informativenessentropy / least-confidence / margin sampling, BALD, core-setselection bias: labeled set no longer i.i.d.evaluate on a random held-out set, never the selected pool
Weaknoisy rules/heuristicslabeling-function errors are conditionally independent given the true labelSnorkel label model, data programmingcorrelated LFs break independence → overconfident labelshold out LFs; compare pairwise agreement against measured accuracy

Mechanism and trade-offs

Self-supervision buys a representation for compute, not labels. MAE masking 75% of patches forces reconstruction of global structure; BERT masking 15% of tokens is cheap but learns a weaker visual signal. The trade-off is that the pretext objective is a proxy, if it is misaligned with the downstream task, fine-tuning recovers less than supervised pretraining on the same budget.

Semi-supervision buys accuracy from unlabeled data only while its assumption holds. FixMatch keeps an unlabeled sample only when the model's confidence exceeds τ=0.95, which is exactly the mechanism that causes confirmation bias: a confidently wrong prediction is reinforced every round. It is the wrong choice when classes overlap heavily or the labeled set is too small to seed a boundary.

Active learning buys label efficiency at the cost of a non-i.i.d. labeled set. Entropy sampling picks the most uncertain points, so the labeled distribution drifts toward the boundary and a random test set overestimates performance. Batch acquisition compounds this: the top-k uncertain points are often near-duplicates.

Weak supervision buys scale from cheap rules. The Snorkel label model estimates each labeling function's accuracy and correlation to produce probabilistic labels, but its independence assumption fails when rules are copied from the same source: the model then reports high confidence on systematically wrong labels.

Worked trace: entropy-based active learning

Python
import numpy as np
p = np.array([[0.9, 0.1], [0.55, 0.45], [0.7, 0.3]])
ent = -(p * np.log(p)).sum(axis=1)
order = np.argsort(-ent)

Row by row: ent[0] = −(0.9·ln0.9 + 0.1·ln0.1) = 0.325; ent[1] = −(0.55·ln0.55 + 0.45·ln0.45) = 0.688; ent[2] = −(0.7·ln0.7 + 0.3·ln0.3) = 0.611. So ent = [0.325, 0.688, 0.611] and order = [1, 2, 0]: the model asks the human to label the 0.55/0.45 point first, then 0.7/0.3, and the confident 0.9/0.1 point last.

Failure modes and when each is wrong

  • Self-supervised: representation collapse (all embeddings map to one point). Detect by checking embedding variance across a batch.
  • Semi-supervised: confirmation bias. Detect by tracking pseudo-label accuracy each round; if it falls, the threshold is too low.
  • Active: selection bias. Detect by comparing accuracy on the selected pool against a random held-out set; a large gap means the pool is unrepresentative.
  • Weak: correlated labeling functions. Detect by holding out one LF and checking whether the label model's confidence drops when it is removed.

In every case the evaluation set must be independently labeled and deployment-representative, and never the actively-selected pool.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-11

Explain PCA and when it is useful.

Answer

The 90-second answer. PCA is an unsupervised linear projection. Center each column, form the covariance matrix (or run SVD on the centered matrix), and take the eigenvectors with the largest eigenvalues. Those directions are orthogonal and ordered by variance explained, so projecting onto the top k gives the linear k-dimensional representation that retains the most variance: no other linear projection keeps more.

It earns its place when numeric features are correlated, when p is large relative to n, for denoising, for 2-D visualization, and as preprocessing for models that choke on collinearity. It does not earn its place when features carry different units and you skip standardization, when the data has outliers, when the manifold is nonlinear, or when the signal lives in a low-variance direction: PCA maximizes variance, not class separation.

Worked example. Two features with covariance matrix [[4, 3], [3, 4]]: each has variance 4, they covary by 3 (correlation 0.75). Eigenvalues solve (4-λ)² - 9 = 0, giving λ₁ = 7 and λ₂ = 1. Total variance is 8, so PC1 explains 7/8 = 87.5% and PC2 the remaining 12.5%. The PC1 eigenvector is (1, 1)/√2: the diagonal. Dropping PC2 costs 12.5% of total variance, and the per-sample reconstruction error is the squared projection onto that dropped axis.

In scikit-learn.

Python
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline

pipe = Pipeline([
    ("scale", StandardScaler()),
    ("pca", PCA(n_components=0.95)),   # keep components until 95% cumulative variance
])
Xtr_p = pipe.fit_transform(X_train)     # fit on train only
Xte_p = pipe.transform(X_test)          # reuse the same rotation
pca = pipe.named_steps["pca"]
print(pca.n_components_)                # e.g. 12 of 50
print(pca.explained_variance_ratio_.sum())  # >= 0.95

Named defaults worth knowing: n_components=None keeps min(n_samples, n_features) components; passing a float in (0, 1) makes sklearn switch svd_solver from 'auto' to 'full'; 'auto' picks randomized SVD only when the data exceeds 500×500 and n_components < 0.8 * min(n_samples, n_features), otherwise exact SVD; whiten=False by default. TruncatedSVD is the sparse-input variant (it skips centering), and IncrementalPCA handles data that won't fit in memory.

Scaling is not optional. A feature measured in millimetres has variance 10⁶ times larger than the same feature in metres. Unstandardized, PC1 is essentially that one column. Standardize whenever units differ.

Failure modes. Fitting the scaler or PCA on the full dataset before splitting leaks test statistics into training: fit inside each CV fold. Variance is not robust: one point at 10σ can dominate PC1, so inspect per-sample reconstruction error for outliers. Components are defined only up to sign, so never hardcode a sign. PCs are dense linear combinations of every input, which usually kills interpretability. And if the discriminative direction has small variance, PCA discards it: use LDA or PLS when labels exist, kernel PCA or an autoencoder when the manifold is nonlinear.

Choosing k. A cumulative-variance threshold (95% is the common default), a reconstruction-error target, or the downstream validation metric. If the task is classification, pick k by validation score, not by variance alone. Persist the fitted pipeline (scaler means, component matrix, and the sklearn version) so inference applies the identical transform.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-9

Explain k-means assumptions and common failure modes.

Answer

The 90-second answer. k-means is a least-squares problem: partition n points into k groups minimizing inertia, the sum of squared Euclidean distances from each point to its cluster centroid. Every failure mode follows from that one objective. Squared Euclidean distance assumes clusters are roughly spherical, similar in size and variance, and that every feature is on a comparable scale; using a mean as the cluster summary assumes the mean is meaningful for that data. Violate any of these and the algorithm still converges: it converges to the wrong partition, with no error signal.

Where the assumptions bite.

Scale and weighting. Squared distance means a feature with 100× the range contributes 10,000× as much. Standardize first (StandardScaler); k-means is not scale-invariant, and the partition changes when you rescale.

Shape. The objective is minimized by Voronoi cells around centroids, so elongated clusters get cut across the long axis. Two 1:10 ellipses side by side come back as four roughly round pieces.

Outliers. One point at distance d contributes d². Ten points at 0 and one at 100: the centroid sits at 100/11 ≈ 9.09, and the outlier alone carries (90.9)² ≈ 8,265 of the 9,091 total inertia. 91% of the objective from 1 of 11 points.

Initialization. Lloyd's algorithm is local search. Points (0,0), (0,1), (10,0), (10,1), k=2, seeded at (0,0) and (0,1):

iterationassignmentcentroidsinertia
1{(0,0),(10,0)}, {(0,1),(10,1)}(5,0), (5,1)100
2unchanged(5,0), (5,1)100

It converged to a vertical split with inertia 100. The horizontal split {(0,0),(0,1)} / {(10,0),(10,1)} has inertia 1. Same data, same k, 100× the objective. init='k-means++' (the scikit-learn default) samples each seed with probability proportional to squared distance to the nearest chosen seed, which makes this trap unlikely: from (0,0), the two far points carry 201/202 ≈ 99.5% of the seeding mass, but it is a heuristic, not a guarantee. Run restarts and keep the lowest inertia; since scikit-learn 1.4 the default n_init='auto' means a single run with k-means++.

Categorical features. One-hot encoding puts every mismatch exactly √2 apart, so "red vs blue" and "red vs green" are equally distant. Use k-prototypes, or Gower distance with k-medoids.

Wrong k. Inertia decreases monotonically in k and reaches 0 at k=n, so the elbow is a heuristic. Use silhouette (sklearn.metrics.silhouette_score, range [-1,1]) or BIC if you move to a mixture model. Empty clusters can occur; scikit-learn reseeds them rather than leaving them empty.

When k-means is the wrong tool.

alternativehandlescost / caveat
GaussianMixture (full covariance)elongated, different-variance, overlapping clusters; soft assignmentsneeds enough points per component to fit covariance; k by BIC/AIC
DBSCANarbitrary shapes, labels outliers as noise (-1)eps and min_samples are global; fails when densities differ
AgglomerativeClustering (ward)no centroid assumption, gives a hierarchyO(n²) memory for the tree; small n
KMedoids / PAMoutliers, arbitrary distanceslower per iteration than Lloyd

Deciding rule: non-convex or noisy → DBSCAN/HDBSCAN; overlapping with covariance structure → GMM; small n and you want a hierarchy → agglomerative; outliers dominate → k-medoids or trim first.

Detection, not vibes. Per-cluster inertia imbalance flags a large cluster being cut. Top-1% point-to-centroid distances flag outliers. Spread in final inertia across restarts flags a bad local optimum. A silhouette that is low and flat across k means the geometry is wrong, not that k is wrong.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-14

Compare self-training and label propagation.

Answer

Both methods use unlabeled data, but the signal they trust is different. Self-training trusts the supervised model's confidence: fit a classifier on labeled data, promote high-confidence predictions to pseudo-labels, retrain, repeat. Label propagation trusts graph smoothness: build a graph over all points, clamp the labeled nodes, and let labels diffuse along edges. In scikit-learn, SelfTrainingClassifier defaults to threshold=0.75, criterion='threshold', k_best=10, max_iter=10. LabelPropagation defaults to kernel='rbf', gamma=20, n_neighbors=7 (used when kernel='knn'), max_iter=1000, tol=0.001; LabelSpreading adds alpha=0.2 so labeled points can move. The classic hard-clamping algorithm is Zhu & Ghahramani (2002). Self-training is a hard-threshold cousin of entropy minimization: instead of penalizing high-entropy outputs, it discards them.

Mechanically, self-training is a wrapper. With 100 unlabeled points and threshold=0.75, if 12 have predicted probability >= 0.75, all 12 are added that iteration; if none do, training stops. Label propagation is a fixed-point iteration. Take four nodes: A labeled 0, D labeled 1, B and C unlabeled. Edges A-B, B-C, C-D, all weight 1. Start F_B=F_C=0.5. Iterate B=(F_A+F_C)/2, C=(F_B+F_D)/2. Iter 1: B=0.25, C=0.75. Iter 2: B=0.375, C=0.6875. Iter 3: B=0.34375, C=0.671875. Fixed point: B=1/3, C=2/3. So B gets class 0, C gets class 1. The label travels one hop per iteration; max_iter=1000 is usually enough for small graphs, but a long chain needs enough iterations to reach the far end.

Self-trainingLabel propagation
Signalmodel confidencegraph smoothness
sklearnSelfTrainingClassifier(threshold=0.75, max_iter=10)LabelPropagation(kernel='rbf', gamma=20, max_iter=1000, tol=0.001)
Outputinductive: predict new Xtransductive: labels for fitted unlabeled set; sklearn predict reuses the kernel
Failureconfirmation bias; threshold too low or too highgraph construction; error spreads; disconnected components
Detectpseudo-label precision on held-out human setper-component label coverage, neighbor agreement

Self-training fails when the base model is miscalibrated. A threshold of 0.6 lets wrong pseudo-labels accumulate; 0.99 adds almost nothing and stalls. Detect it by measuring pseudo-label precision on a held-out human-labeled set: a drop from 0.92 to 0.71 after three iterations is a stop signal. Label propagation fails when the graph encodes the wrong similarity. k=7 on 10k points with 100 features can connect opposite classes; gamma=20 RBF can be too local or too global. A disconnected component with no labeled node gets no label at all. Detect it by per-component label coverage and neighbor label agreement, not just overall accuracy.

Use self-training when you have a calibrated classifier and need inductive predictions on new points. Use label propagation when feature similarity is the reliable signal and the unlabeled set is fixed. Before either, compare against labeling 20 informative cases: if that beats 1000 pseudo-labels, the semi-supervised loop is not the bottleneck.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-13

How would you use semi-supervised learning safely?

Answer

Semi-supervised learning pays off when unlabeled data is abundant and cheap and labels are scarce and expensive. It's safe only when you can measure the pseudo-label error rate against a human-labeled set the model never trains on. My default: supervised baseline first, then self-training with a confidence threshold, a held-out human-labeled probe set that pseudo-labels never touch, and a stop rule, if pseudo-label precision on that probe set falls below the baseline's own accuracy, stop and buy labels.

Why it goes wrong. The model's decision boundary decides which unlabeled points get labels, and those labels reinforce the boundary. Where the boundary is wrong, the model is confidently wrong, the wrong labels clear the threshold, and the error compounds round over round. Thresholding doesn't fix this; it selects for confidence, and a modern network is confidently wrong in exactly the regions you care about. That's confirmation bias, and it's why a fixed threshold is a tuning knob, not a safety mechanism.

Concrete defaults. FixMatch (Sohn et al., NeurIPS 2020) uses τ = 0.95 on the weakly-augmented prediction and a μ = 7 ratio of unlabeled to labeled batch size. Those were tuned on CIFAR-10 with 40 labels per class: balanced, in-distribution. On long-tailed data a single global 0.95 acts as a class filter: head classes clear it, tail classes don't, and you train the model to be more confident about what it already knew. FlexMatch (Zhang et al., NeurIPS 2021) replaces the global threshold with per-class thresholds derived from each class's learning status; that's the first fix I'd reach for.

The threshold lives in the mask:

Python
# FixMatch-style unlabeled loss, PyTorch 2.x
with torch.no_grad():
    prob = model(weak_aug(u)).softmax(dim=-1)   # (B, C)
    conf, pseudo = prob.max(dim=-1)             # both (B,)
    mask = conf.ge(0.95).float()                # tau = 0.95
loss_u = (F.cross_entropy(model(strong_aug(u)), pseudo, reduction="none")
          * mask).sum() / mask.sum().clamp(min=1.0)

prob.max(dim=-1) returns the value and the argmax index, so conf and pseudo are both length B. reduction="none" gives one loss per row; multiplying by mask zeroes rows below 0.95. The clamp(min=1.0) is the paper's guard for a batch where nothing clears the threshold: without it you divide by zero and get NaN gradients.

What it costs. 1,000 labeled rows, 50,000 unlabeled, baseline 78% on the probe set. Round one, 60% of unlabeled rows clear τ = 0.95, so 30,000 pseudo-labels. At 91% pseudo-label precision that's about 2,700 wrong labels injected. Hand-labeling 30,000 rows at $0.05 each is $1,500 and roughly two days of vendor turnaround. If your team can label 30k rows in a day, SSL is the wrong tool: that comparison, not the accuracy curve, is the deciding criterion.

Failure modes and what to watch:

FailureDetection signalStop / fix threshold
Confirmation biaspseudo-label precision on the held-out probe set, per roundprecision < baseline accuracy on the same probe set
Class collapseper-class share of pseudo-labels vs. per-class share of labeled rowsa tail class holding >5% of labeled rows gets <1% of pseudo-labels
Unlabeled pool shifteddomain-classifier AUC between labeled and unlabeled featuresAUC > 0.7: the pools are separable, so the cluster assumption is gone
Deployment feedback loopagreement between model labels and a 1–5% human-labeled random traffic sample, tracked weeklyagreement drops >3 points over two weeks

When not to use it at all: the unlabeled pool is shifted (row three above), the classes are interleaved in one dense region so the cluster assumption fails. Short-text sentiment is the usual example, positive and negative share vocabulary, or downstream needs calibrated probabilities, since self-training sharpens them and you'd have to recalibrate afterward.

Deployment is where the loop closes. Model-generated labels shape what gets collected next, so keep a random 1–5% of traffic human-labeled regardless of model output, and log provenance on every synthetic label so you can retract a training round when the probe set says it was bad.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-4

How do you prevent preprocessing leakage in an ML pipeline?

Answer

The rule. Every quantity that is learned from data: a fill value, a mean and standard deviation, a vocabulary, a target-encoding map, a set of selected feature indices, PCA components, cluster centroids, a resampling plan: is fit on the training rows of the fold that will be scored, then applied unchanged to the validation rows. The pipeline object is how you enforce that structurally instead of by discipline: scikit-learn's Pipeline and ColumnTransformer call fit only on the training slice and transform on both, so a transform cannot see the validation rows unless you put it outside the pipeline.

Assumptions: supervised learning, you are selecting a configuration and estimating its generalization error, and the split is the thing you are protecting.

What counts as learned. Anything with a fit. The ones people miss: target encoding (the row's own label enters its own level mean), feature selection and PCA (validation rows vote on which columns survive), SMOTE and other resampling (synthetic points interpolate across the boundary), and early stopping or model selection against the validation fold (the fold stops being held out the moment you use it to choose).

Worked trace. Four rows, one feature x, binary label. Rows 1–2 are the training fold, rows 3–4 validation. Row 1's x is missing; observed values are row 2 = 20, row 3 = 30, row 4 = 40.

  • Leaky: fill with the mean of all observed x = (20 + 30 + 40) / 3 = 30.
  • Correct: fill with the mean of the training fold's observed x = 20 / 1 = 20.

The validation rows moved the fill value by 10, half the training mean, and row 3 is then scored by a model whose training row 1 was filled using row 3's own value. When missingness correlates with the label (income not reported by high earners), the shift is directional and the model learns the wrong sign.

Failure modes and how to catch them.

Leak pointWhat crossesDetection
Imputation / scalingvalidation values in the fill or mean/stdthe fitted statistic should differ per fold; identical across folds means it was fit once on everything
Target encodingthe row's own label, or validation labelspermute the target and rerun the whole pipeline; AUC meaningfully above 0.5 means labels crossed
Feature selection / PCAvalidation rows choose the surviving columnsthe selected index set should differ per fold
Resamplingsynthetic points spanning train and validationresample inside the training fold only; check the nearest neighbours of synthetic rows
Group / time splitsame entity or a later timestamp on both sidesassert empty group-ID intersection; assert max(train time) < min(validation time)
Early stopping on the validation foldthe fold itselfyou no longer have an unbiased estimate; the score is optimistic by the number of decisions made against it

The cost is not a small bias. The offline metric is what you used to choose the configuration, so leakage becomes a selection error: you pick the pipeline that best exploits the boundary, and the gap only appears after deployment, when the same model is scored on data it has never influenced.

Trade-offs. The pipeline object gives a structural guarantee, but nested CV is expensive: 5 outer × 5 inner folds is 25 fits per configuration, so 20 configurations is 500 fits. At 10 minutes each, 83 hours. The corner people cut is the inner loop, which is exactly where the leak lives. Manual fit/transform loops work with non-scikit code (custom embeddings, SQL feature jobs) but nothing enforces them and the failure is silent. Precomputing transforms once on a development window and freezing them is cheap and reproducible, but the frozen object must be refit for the final model, and reusing it across folds is the leak. Caching fitted transforms is fine only if the cache key is the fold's row-index set, not the transform's name.

When it isn't leakage. A tokenizer or embedding model pretrained on an external corpus never saw your labels or your evaluation rows, so it is not leakage even though it was "fit". The test is whether the artefact's parameters depend on the evaluation data, not whether something was fit somewhere.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-3

Design an evaluation split for repeat customers over time.

Answer

Clarify first: is the model scoring known customers next month, or ranking customers never seen? The split differs.

Assume known-customer forecasting. I have 18 months of snapshots, 2023-01-01 to 2024-06-30, one row per customer per month. Label = purchase in the next 30 days. I use an expanding-window temporal split with a 30-day gap between train end and validation start so labels mature. Six folds, then one final holdout.

foldtrain snapshotsvalidation snapshotstrain customersval customers
12023-01-01..2023-06-012023-08-01..2023-08-318,0002,100
22023-01-01..2023-07-012023-09-01..2023-09-308,9002,150
32023-01-01..2023-08-012023-10-01..2023-10-319,7002,200
42023-01-01..2023-09-012023-11-01..2023-11-3010,5002,250
52023-01-01..2023-10-012023-12-01..2023-12-3111,3002,280
62023-01-01..2023-12-012024-02-01..2024-02-2912,4002,300

Final test: train through 2024-01-31, test 2024-04-01..2024-06-30. Do not touch it until one final run.

Why the gap: a snapshot on 2023-06-01 has a label window ending 2023-07-01. If validation starts 2023-08-01, the last training label is known before validation begins. Without the gap, training labels overlap the validation window. Symptom: validation AUC 0.84 with no gap vs 0.76 with a 30-day gap. Cost: you ship a model that looks 8 points better than it is; the top-decile campaign converts 12% instead of the promised 20%.

Label maturity: if you pull data on 2023-07-15 for a 2023-07-01 snapshot, purchases from 2023-07-16 to 2023-07-31 are missing. Symptom: positive rate for the last 30 days is 3.1% vs 4.4% for earlier months. Cost: the model under-predicts and misses roughly 30% of buyers. Fix: wait 30 days or drop the last 30 days of training snapshots.

Learned transforms: target encoding, imputation, and scaling must be fit inside each training fold. If you fit them on all data, validation statistics leak. Symptom: validation AUC 0.02-0.05 higher than a per-fold pipeline. Use scikit-learn Pipeline inside TimeSeriesSplit.

Group leakage: if the deployment must score customers never seen, use GroupKFold by customer_id for the outer split, and inside each training fold use a temporal split for tuning. If you random-split snapshots, the same customer appears in train and test. Symptom: random split AUC 0.91 vs GroupKFold 0.74. Cost: the new-customer campaign fails because the model memorizes customer ID.

Trade-offs. Expanding window uses all history, good for stable repeat behavior, but old data may be stale and training is 2-3x slower. Rolling window, say last 6 months, adapts to drift but has less data for rare segments. Deciding criterion: if feature PSI between 6-month windows exceeds 0.2, use rolling; otherwise expanding. Random split is acceptable only for static, time-invariant prediction, e.g. predicting preferred category from stable demographics with no label horizon. For repeat purchase over time, random split leaks future and can inflate AUC by 0.15-0.20. Grouped by customer for new-customer generalization; ungrouped for known-customer forecasting. Grouped reduces training customers by about 20% per fold, widening confidence intervals.

Report AUC, PR-AUC, calibration, and top-decile lift by cohort: new vs repeat, high vs low frequency, region.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6

How would you evaluate a rare-event classifier?

Answer

Clarify before you measure. Three things decide the evaluation: the deployment base rate, the cost of a false positive versus a false negative, and how many alerts a human can actually review per day. If prevalence is 0.1% and review capacity is 200 a day, the metric that matters is precision@200, not accuracy, not ROC-AUC.

Core answer. Split by time and by entity, keep deployment prevalence in the final test set, and evaluate at one locked operating threshold. Report PR-AUC, precision@k at the review capacity, calibration, and expected cost. Compare against a no-skill baseline and the existing rule. Note that PR-AUC's no-skill baseline is the prevalence itself: 0.001 here, so a PR-AUC of 0.05 can be a strong model.

Why ROC-AUC alone misleads. It averages over all thresholds and makes a 1% FPR look negligible. At low prevalence it isn't. Test set of 100,000 events at 0.1% prevalence: 100 positives, 99,900 negatives. Hypothetical figures:

modelROC-AUCTPRFPRTPFPprecision
A0.950.900.010909998.3%
B0.850.700.0017010041%

Model A wins on ROC-AUC and loses operationally: 92% of its alerts are false.

Expected cost. With C_fn = $200 and C_fp = $20: A costs 10×200 + 999×20 = $21,980; B costs 30×200 + 100×20 = $8,000. The lower-AUC model is 2.7× cheaper. Sweep thresholds on validation and pick the minimum expected cost; that threshold is the one you lock.

Calibration. Cost-based thresholding needs p(y=1|x), not just a ranking. Two traps. First, if you trained on a resampled balanced set, the scores are not deployment posteriors: correct the intercept: logit_true = logit_sample + log(π/(1−π)) − log(π_s/(1−π_s)). With π_s = 0.5 and π = 0.001, a sample score of 0.90 (logit 2.20) becomes logit −4.71, p ≈ 0.9%. Second, check with a reliability diagram and Brier score, and fix with Platt scaling or isotonic regression on a held-out slice.

Top-k. If analysts clear 200 alerts a day, precision@200 decides whether the model ships. It is a different operating point from any fixed threshold, so report it separately.

Failure modes. Label delay: positives are confirmed weeks later, so recent negatives are unknown. Exclude a label-maturity window. Selective review: labels exist only for what the old policy flagged, so the model inherits its blind spots. Hold out a random audit sample. Leakage: random splits leak the same entity or future information. Split by time and group. Prevalence shift: reweight test metrics to deployment prevalence and monitor score drift (PSI) plus precision@k on the audit stream.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-7

How should a production classification threshold be chosen?

Answer

The 90-second version. I'd pick the threshold that minimises expected cost per decision, subject to a hard cap on review volume, not the threshold that maximises F1. Concretely: fix the cost of a false negative, a false positive, and one manual review; sweep the validation scores; read off the cheapest feasible point; then freeze it as a versioned policy and re-derive it when prevalence or calibration moves. The number that decides it is almost never the model's: it's the cost ratio and the queue capacity.

Assumptions I'd state up front. A payment-fraud model scoring 100,000 transactions/day at 0.5% prevalence (500 frauds). A missed fraud costs $120 (chargeback plus loss). Blocking a legitimate transaction costs $8 in friction and lost margin. One manual review costs $3.50, and the review team can clear 1,000/day. Those four numbers are the whole decision.

Mechanism. A threshold converts a ranking into a decision, so its value is set by the cost ratio, not by the model. Two thresholds on the same validation set:

thresholdflaggedTPFPFNprecisionrecall
0.52,0004001,60010020%80%
0.960030030020050%60%

Expected daily cost = FN·$120 + FP·$8 + flagged·$3.50:

  • t=0.5: 100·120 + 1,600·8 + 2,000·3.5 = $31,800, and 2,000 reviews blows the 1,000/day cap. Infeasible.
  • t=0.9: 200·120 + 300·8 + 600·3.5 = $28,500, 600 reviews. Feasible.

So 0.9 wins on cost and on capacity. Capacity is a constraint, not a cost term: an infeasible point is off the table however cheap it looks.

How the cost curve is built. Sweep thresholds over held-out scores and sum the three terms:

Python
import numpy as np

def cost_curve(scores, y, cost_fn, cost_fp, cost_review, thresholds):
    out = []
    for t in thresholds:
        flagged = scores >= t
        tp = np.sum(flagged & y)
        fp = np.sum(flagged & ~y)
        fn = np.sum(~flagged & y)
        out.append((t, tp, fp, fn,
                    fn * cost_fn + fp * cost_fp + (tp + fp) * cost_review))
    return out

Why prevalence and calibration decide transfer. Precision is prevalence-dependent; recall is not. Drop prevalence from 0.5% to 0.1% (100 frauds) and t=0.9 keeps roughly the same 300 false positives (they scale with the negative class, which barely moved) while true positives fall to ~60. Precision collapses from 50% to 60/360 ≈ 17%, so the same threshold now sends mostly clean traffic to review. Calibration is the other half: a threshold is a claim that score 0.9 means ~90% fraud. If the model is retrained or the population shifts, ranking (AUC) can hold while the reliability curve moves, and 0.9 no longer means what it did. Check calibration with a reliability plot and Brier score before reusing a threshold across a model version.

Failure modes, with detection.

  • Prevalence drift: fraud rate halves after a rule change. Detect by comparing daily positive rate against the validation prior; alert on a sustained shift. Cost: precision halves, review queue fills with false positives.
  • Calibration drift: retrain shifts the score distribution. Detect by Brier score and a reliability plot on a labelled holdout; a threshold that was calibrated is now arbitrary.
  • Capacity breach: a spike pushes flagged volume past 1,000/day. Detect by queue depth and time-to-clear; the fallback is to raise the threshold automatically rather than let the queue back up.
  • Subgroup regression: a threshold tuned on the aggregate can raise false-positive rate on one segment. Detect by per-segment precision/recall at the chosen point, not just overall.

In production. Monitor score distribution, positive rate, calibration, queue depth, and override rate. Changing the threshold is a versioned policy release with its own validation, not a config tweak: the fixed policy is what the final test evaluates.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

How do you choose the number of clusters?

Answer

What I say first. Before touching a metric I pin down what the clusters are for and the smallest segment that is still useful. Concretely: 200k customers, 12 scaled numeric features, and a downstream campaign that needs at least ~5,000 people per segment to be worth running. That floor is a hard constraint, not a preference: it rules out k values before any diagnostic runs. Then I fit a bounded range, say k = 2..12, and look for a region where the diagnostics agree and the partition survives resampling. If two k values are equally defensible I report both and say which one the downstream use favors.

Why each diagnostic behaves the way it does. Inertia (within-cluster sum of squares) falls monotonically with k: every added centroid can only reduce it. The elbow is where the marginal reduction flattens: each new centroid splits the currently loosest cluster, so the gain is roughly proportional to that cluster's variance, and it decays as clusters tighten. On smooth data there is no elbow at all, which is why I never read it alone. Silhouette is (b − a) / max(a, b) per point, where a is mean distance to its own cluster and b to the nearest other cluster; it rewards tight, well-separated, roughly convex clusters and punishes elongated or density-varying ones. Likelihood/BIC only fits if the generative assumption (Gaussian components for a GMM) is credible. Stability is the tie-breaker: if two halves of the data produce different partitions, the k is an artifact of the seed, not structure.

Python
from sklearn.cluster import KMeans
from sklearn.metrics import adjusted_rand_score
import numpy as np

def stability(X, k, n_rep=20, seed=0):
    rng = np.random.default_rng(seed)
    scores = []
    for _ in range(n_rep):
        perm = rng.permutation(len(X))
        h1, h2 = perm[:len(X)//2], perm[len(X)//2:]
        m1 = KMeans(n_clusters=k, n_init=10, random_state=0).fit(X[h1])
        m2 = KMeans(n_clusters=k, n_init=10, random_state=0).fit(X[h2])
        scores.append(adjusted_rand_score(m1.predict(X), m2.predict(X)))
    return float(np.mean(scores))

Worked check (illustrative figures for the 200k-customer case):

kinertia (×10⁶)silhouettemean ARI (20 splits)smallest cluster
24.100.310.9461,000
43.050.380.8822,000
62.620.360.614,800
82.410.330.441,900
122.200.290.31700

Silhouette peaks at 4, ARI collapses past 4, and the smallest cluster at 6 already breaches the 5,000 floor. I pick 4 and note that 6 is defensible only if the campaign can absorb a 4,800-person segment.

Failure modes and how I catch them. No elbow: fit the range and check whether the consecutive inertia drop ratio stays within ~10%, if so, the curve carries no signal. Silhouette inflated at k=2 by distance concentration in high dimensions: cluster random Gaussian data of the same dimensionality and compare; if the real silhouette barely clears the null, discard it. Seed artifact: ARI below ~0.6 across splits means the partition is not reproducible. Operational cost: each cluster needs its own monitoring and runbook, and a 700-person segment cannot support a campaign. I check the smallest cluster against the floor before committing, not after.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

How do you decide whether clustering is appropriate?

Answer

Clustering is appropriate when three conditions hold together: there are no labels and buying them costs more than the decision is worth; the action you'll take is robust to which particular partition you get; and you can validate the partition against something outside the clustering. Miss any one and you should use a supervised model, a hand-written rule, or just report the distribution.

The first question I ask is what changes when a row moves from cluster 3 to cluster 5. If nothing does (no routing, no budget, no threshold) then the partition is a visualization, not a result, and I'd rather spend the week on a labelled proxy. If a proxy label exists (churn, fraud, conversion), a supervised model gives a calibrated probability and a decision boundary you can defend; clustering gives neither.

Checking the structure is real before choosing k

  • Hopkins statistic: ~0.5 means the data is indistinguishable from uniform noise; above ~0.75 is worth pursuing. Cheap, and it stops a lot of wasted work.
  • k-means minimizes within-cluster sum of squares, so it assumes roughly spherical, similar-sized clusters. On two interleaved crescents it will split them down the middle and report a good-looking objective.
  • DBSCAN finds arbitrary shapes but needs eps and min_samples, and one density threshold fails when clusters have different densities.
  • Single-linkage chains: a single thin bridge of points merges two clusters that are otherwise separate.

Stability, with numbers

Python
from sklearn.cluster import KMeans
from sklearn.metrics import adjusted_rand_score
from sklearn.preprocessing import StandardScaler

X = StandardScaler().fit_transform(features)          # 40k rows, 12 features
runs = [KMeans(n_clusters=6, n_init=10, random_state=s).fit_predict(X)
        for s in range(10)]
aris = [adjusted_rand_score(runs[0], r) for r in runs[1:]]

Ten runs, nine comparisons against run 0. If those ARIs come back 0.91, 0.88, 0.93, 0.90, the partition is a property of the data. If they come back 0.41, 0.55, 0.30, 0.62, the partition is a property of the random seed, and no amount of silhouette tuning fixes that. (Those are illustrative values, not measured ones.) ARI is 1.0 for identical labellings and 0 for chance agreement, so the gap between the two cases is unambiguous.

Failure modes and how they show up

  • Scaling dominates distance. A feature in 0–1,000,000 swamps one in 0–1 under Euclidean distance; the clustering is then a one-dimensional sort on that column. Detect it by clustering on each feature alone and checking whether the result matches.
  • Distance concentration. As dimensionality grows, the ratio of nearest to farthest neighbour distance tends toward 1, so "nearest" stops meaning anything. Detect it by comparing the distance distribution to a shuffled baseline; if they overlap, reduce dimensions first.
  • Silhouette lies about non-convex clusters. It rewards compact, convex blobs, so it will prefer a k-means split of two crescents over the correct DBSCAN labelling. Use it to compare k for the same algorithm, not to compare algorithms.
  • Subgroup impact. A cluster that is 90% one protected or high-value group is a finding about the data, not a segment. Check composition before anyone acts on it.

When to reject

Reject clustering when a rule already captures the decision (e.g. "accounts older than 90 days with no login"), when the label can be collected for a few thousand rows, or when the downstream metric doesn't move between partitions. Accept it when the structure is stable under resampling, the geometry matches the algorithm's assumptions, and a held-out outcome (conversion, retention, cost) differs across clusters by more than the noise band you measured.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

How do you validate customer segments produced by clustering?

Answer

Clustering has no ground truth, so validating segments means answering two questions: do they survive perturbation of the data, and do they change a decision? Silhouette, Davies-Bouldin and the gap statistic are proxies for the first and say nothing about the second.

State your assumptions before any metric: what the segments are for (targeting, prioritisation, reporting), which features and distance, how many segments, and what the baseline policy is. No baseline policy means nothing to validate against.

1. Stability, measured against a null

Fit on a development sample, then re-fit on 100 random 80% subsamples and compare each partition to the full-data one with ARI. ARI is chance-corrected, two random partitions of the same points score ~0, so 0.75 is high, not "moderate". The trap is that ARI is also high for degenerate solutions, e.g. one cluster holding 90% of customers. Report cluster sizes next to it, and compute per-customer co-association: the fraction of runs in which a customer lands with the same peers. ARI can read 0.8 while a third of customers sit on a boundary and flip.

The step people skip is the null: run the identical pipeline on data with the same marginals but no cluster structure (shuffle each feature independently, or sample from a Gaussian with the same covariance). If the null returns ARI 0.7, your 0.75 is noise.

Python
import numpy as np
from sklearn.cluster import KMeans
from sklearn.metrics import adjusted_rand_score

def stability(X, k, n_runs=100, frac=0.8, seed=0):
    rng = np.random.default_rng(seed)
    n = X.shape[0]
    base = KMeans(k, n_init=10, random_state=seed).fit_predict(X)
    co = np.zeros((n, n), np.int32); seen = np.zeros((n, n), np.int32)
    aris = []
    for r in range(n_runs):
        idx = rng.choice(n, int(frac * n), replace=False)
        lab = KMeans(k, n_init=10, random_state=r).fit_predict(X[idx])
        aris.append(adjusted_rand_score(base[idx], lab))
        co[np.ix_(idx, idx)] += (lab[:, None] == lab[None, :])
        seen[np.ix_(idx, idx)] += 1
    p = np.where(seen > 0, co / np.maximum(seen, 1), np.nan)
    own = np.array([np.nanmean(p[i, base == base[i]]) for i in range(n)])
    return np.mean(aris), np.median(own), (own < 0.6).mean()

It returns mean ARI, median per-customer co-association, and the share of customers below 0.6. On a hypothetical 10,000-customer, 4-segment run (figures illustrative): mean ARI 0.75, median co-association 0.88, 12% of customers below 0.6. Stable in aggregate, but a tenth of the base is boundary noise, which matters if you mail those people.

2. Outcome validation, without leakage

With churn or spend labels, p-values are useless at n=10,000; report effect size (eta-squared, or the spread in churn rate across segments) with a confidence interval. The bigger trap is circularity: if churn-related features went into the clustering matrix, a churn difference is a tautology. Hold the outcome features out entirely.

The test that decides it: does adding segment dummies to a model that already contains the raw features improve out-of-sample AUC? Usually it doesn't, and that is fine: segments are a compression for humans to act on, not a prediction upgrade. Say that out loud; it is the distinction most candidates miss.

3. Decision validation

Compare the segment-targeted policy against the baseline policy at the same budget, not against no treatment. Measure incremental revenue per customer, with a power calculation on that metric. A 5% conversion lift with CI [2%, 8%] only counts if the baseline policy wasn't already capturing most of it.

Failure modes and how they show up

FailureDetection
Distance concentration: silhouette near 0 for every k in high-dimensional one-hot spaceCompare silhouette to the null; a gap under ~0.05 means the geometry is meaningless
Degenerate solution: one cluster holds most customersCluster size distribution; flag >80% in one cluster
Boundary instabilityPer-customer co-association below 0.6
Circular validationOutcome features present in the clustering matrix
Segments that don't generaliseAssign held-out customers to nearest centroid; check the distance distribution
Sensitive attributes driving segmentsComposition audit per segment (ECOA / fair-lending exposure)

On thresholds: silhouette above 0.5 is rare on real customer data past ~10 features. 0.1–0.3 is a common range. Silhouette and Davies-Bouldin are only comparable across k on the same representation and distance, never across datasets. The gap statistic (Tibshirani, Walther & Hastie, 2001) compares within-cluster dispersion to a uniform reference over the data's bounding box and often selects k=1 on real data; treat it as one vote, not a verdict.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

How do you evaluate dimensionality reduction for visualization?

Answer

The 90-second answer

I first fix what the plot is for, because that decides both the method and the yardstick. For global structure and variance, PCA, and cumulative explained variance ratio is an exact, legitimate yardstick. For local neighborhoods, t-SNE or UMAP, and I judge those with neighborhood-preservation metrics, never with distances read off the picture. I standardize features, fit the transform on the reference set only, and report the method, its parameters (perplexity, n_neighbors, min_dist), the seed, and how the picture moves across a small grid of those. If the plot drives a decision, I validate that decision on held-out data in the original space.

Why the yardsticks differ

PCA projects onto the top eigenvectors of the covariance matrix; component i's explained variance ratio is exactly the share of total variance it captures, so "the first two components hold 43% of variance" is a real statement about the data. t-SNE minimizes KL divergence between a Gaussian similarity in the original space: perplexity sets the effective neighborhood size, roughly 2^entropy, typically 5–50, default 30, and a heavy-tailed Student-t similarity in 2D. The objective only matches neighbor probabilities, so inter-cluster distances and cluster sizes carry no meaning. UMAP builds a fuzzy k-NN graph (n_neighbors default 15, min_dist default 0.1) and optimizes cross-entropy; it retains somewhat more global structure than t-SNE but is still not metric. That is why explained variance is the right yardstick for PCA and meaningless for the other two.

methodpreservesyardstickmeaningless on the plot
PCAglobal variance, linear axescumulative explained variance rationonlinear manifold structure
t-SNElocal neighborhoodstrustworthiness, k-NN overlapinter-cluster distances, cluster sizes
UMAPlocal + some globaltrustworthiness, k-NN overlapcluster sizes, absolute distances

What I actually compute

Python
import numpy as np
from sklearn.manifold import trustworthiness
from sklearn.neighbors import NearestNeighbors

def knn_overlap(X, Z, k=10):
    ix = NearestNeighbors(n_neighbors=k+1).fit(X).kneighbors(X, return_distance=False)[:, 1:]
    iz = NearestNeighbors(n_neighbors=k+1).fit(Z).kneighbors(Z, return_distance=False)[:, 1:]
    return np.mean([len(set(a) & set(b)) / k for a, b in zip(ix, iz)])

print(round(trustworthiness(X, Z, n_neighbors=10), 3), round(knn_overlap(X, Z), 3))

Trace: NearestNeighbors(n_neighbors=11) returns 11 indices per row, the point itself in column 0; [:, 1:] drops self, leaving 10. For one point, if 8 of its 10 original neighbors are also among its 10 embedded neighbors, the intersection is 8 and the ratio is 0.8; the function averages that over all points. trustworthiness uses the same k and penalizes points that are close in the embedding but far in the original space; 1.0 means every embedded neighbor was also an original neighbor. Illustrative output on a 500-point, 50-dim set: PCA to 2D gives 0.91 0.62; t-SNE at perplexity 30 gives 0.97 0.81; t-SNE at perplexity 5 gives 0.88 0.55 while drawing 12 apparent clusters from data with 3 true groups.

Failure modes and how I catch them

  • t-SNE inventing clusters at low perplexity. Sweep perplexity {5, 30, 50} × 3 seeds; a cluster that appears only at 5 is an artifact. Confirm by computing silhouette on the original features, or the cross-validated accuracy of a classifier trying to separate the apparent clusters: near-chance means the split is not in the data.
  • Reading UMAP cluster sizes as quantities. A large blob is not "more" of anything; the embedding has no density guarantee. Check by comparing group counts in the original space.
  • PCA hiding the variance. If the first two components hold 20%, the plot omits 80%: state that rather than presenting the picture as the data.
  • Local structure distorted. Trustworthiness below ~0.9 or k-NN overlap below ~0.6 means the embedding is not faithfully showing neighborhoods; raise perplexity or n_neighbors and re-check.

When not to trust a projection

If the plot is going to drive a decision (a segment to target, a cluster to label) the projection is only a hypothesis generator. I validate on held-out original-space data with a quantitative outcome, and I never infer causal or categorical truth from visual separation alone.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

Design an anomaly-detection system when labels are scarce.

Answer

Core answer

Three things get pinned before any method: the cost of a miss versus a false positive, how many alerts a reviewer can clear per day, and what population and window "normal" means. With scarce labels, labels are not training data: they are a measuring instrument. I fit an unsupervised detector on the unlabeled bulk, then use the few hundred labels to choose the operating threshold and estimate precision and recall.

Assumptions stated up front: a few hundred labels at most, sampled non-randomly (usually from past alerts, so biased toward what the old rule already caught); base rate under 1%; scoring is per event, not per user.

Baseline first

Modified z-score: 0.6745·(x − median)/MAD, flag above 3.5 (Iglewicz–Hoaglin). It survives heavy tails where a mean/std z-score breaks: one outlier inflates std and hides itself. Trace: median 10, MAD 2. x=20 → 0.6745·10/2 = 3.37, not flagged. x=21 → 0.6745·11/2 = 3.71, flagged. The cut moves with the data, not with a fixed sigma.

Multivariate

Isolation Forest (sklearn 1.x: n_estimators=100, max_samples=256, contamination='auto'). Mechanism: random split trees isolate an anomaly in fewer splits, so its mean path length E[h(x)] is short; score = 2^(−E[h(x)]/c(n)). It assumes anomalies are few and different. It fails when anomalies form a dense cluster: they are not isolated early and the score collapses toward normal. Distance/density methods (kNN distance, LOF) catch local-density anomalies but need a distance metric that means something; LOF is O(n²) naively, so it is out above ~10⁵ rows without an index.

methodneedsfails whencost
modified z-scoreone numeric featuremultivariate, clustered anomaliesO(n)
Isolation Forestno labels, ~256-sample treesanomalies dense, not isolatedO(n log n)
LOF / kNN distancea meaningful metrichigh dim, n > 10⁵O(n²) naive
supervised classifier≥ ~1000 labels/classscarce labels: this question—

Threshold from capacity

Not a fixed percentile. Pick the score cut where audited precision meets the review budget. If reviewers clear 500/day and the stream is 5M/day, you can afford 0.01% flagged. Estimate precision from the labeled sample: 120 true out of 500 reviewed = 24%, Wilson 95% interval ±3.7 points. Sample below the cut too (200 random unflagged events, 2 true) to bound the miss rate; without that you cannot tell a quiet day from a blind detector.

Failure modes

  • Drift: input distribution shifts (new client, new deploy). Detect by tracking score-distribution PSI or KS against a frozen reference window; alert when PSI > 0.2.
  • Feedback loop: you only label what you flag, so the detector's blind spots never get labels. Fix with the below-threshold sample above.
  • Subgroup burden: flag rate per segment. If one tenant is 40% of alerts at 5% precision, the global cut is wrong for them: use per-segment thresholds.
  • Swamping/masking: a cluster of anomalies inflates MAD and hides the rest; recompute robust stats on a trimmed window.

Response

False positives cost reviewer time; false negatives cost the incident. Route high-score, high-cost events to paging, mid-score to a queue, and cap automated action (block/rollback) behind a second independent signal.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

How do you choose between supervised anomaly classification and unsupervised anomaly detection?

Answer

Clarify first, then answer. Two things decide this: do we have verified outcomes that cover the population we're scoring, and is the threat a known pattern or something we haven't seen? If labels cover the population and the threat is known-pattern, go supervised: it optimizes the thing you actually care about. If labels are missing or the threat is novel, go unsupervised, but treat it as a ranking signal, not a decision. Most real systems end up hybrid, and the split is deliberate, not a hedge.

Why supervised wins when it applies. You can train directly on the detection target: precision@k at your alert budget, or recall at a fixed review capacity. A gradient-boosted tree or logistic regression on confirmed-incident labels, then calibrated with isotonic regression or Platt scaling, gives you a score where 0.8 means roughly an 80% incident rate, so the threshold is a capacity decision, not a guess. Unsupervised methods optimize a surrogate. Isolation Forest minimizes the path length needed to isolate a point; LOF compares local density to neighbors; an autoencoder flags high reconstruction error. None of those is harm. A new region rollout is a density outlier and completely benign; slow credential stuffing sits inside normal login volume and never trips a density model.

The failure that bites supervised hardest: selective labels. Say you alert on the top 500 events a day and analysts review all 500. Yesterday 30 were confirmed incidents. The other 11,500 events were never reviewed: they are unlabeled, not benign. Train a classifier treating unreviewed as negative and you have taught it that everything the current detector missed is safe. It converges on reproducing the detector you already have, and recall on missed incidents stays at zero. Detect it by checking whether your model's top-k overlaps the incumbent detector's top-k almost perfectly. Fix it by sampling a few hundred below-the-line events a week for review, or by training only on the reviewed set and accepting the coverage limit.

Deciding criteria.

SignalSupervisedUnsupervised
LabelsVerified outcomes covering the populationNone, or only a biased slice
ThreatKnown patternNovel / unknown
ObjectivePrecision@k at alert budget, calibrated probabilityRanking by distance or density
DriftRetrain on fresh labelsBaseline shifts, threshold moves silently
ExplanationFeature attributionsUsually none

Other failure modes. Supervised: with a 3% base rate (illustrative), a model that always predicts benign scores 97% accuracy. Never report accuracy, report precision@k. Concept drift when the attacker changes tactics degrades it until you relabel. Unsupervised: alert fatigue from density outliers, an uncalibrated threshold that is a guess, and no way to explain a flag to an analyst.

The hybrid, concretely. Run a supervised known-pattern score, a small rule set for hard invariants, and an unsupervised novelty score as three separate signals with separate thresholds. Route the union to review, but keep the thresholds independent so a drift in the novelty model doesn't move your known-pattern alert line. When not to use each: don't run unsupervised when you have good labels and known threats. You're discarding signal. Don't run supervised when your labels only cover the alerted slice and the threat is novel; you'll launder the incumbent detector's blind spots into a confident score.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

When only positive examples are labeled and negatives are unlabeled, how do you frame the problem: positive-unlabeled learning, one-class classification, or unsupervised anomaly detection, and how do you evaluate the choice without clean negative labels?

Answer

Start by naming what the labels actually are. If I have a set of verified positives P and a pool U that contains both positives and negatives, that is positive-unlabeled (PU) learning, not one-class and not unsupervised. The unlabeled pool carries information: it tells me where negatives live, even if I cannot point at them individually. One-class classification is the right frame only when I have positives and no usable negative distribution at all: novel intrusion, a new fraud pattern with no historical negatives. Unsupervised anomaly detection is the frame when I have no labels and no reliable positive set; then scores are ranking signals, not decisions.

The choice turns on two questions: how many verified positives do I have, and do I believe U contains a non-trivial negative fraction? With 200 confirmed frauds and 9,800 unlabeled transactions, PU is the honest frame. I can train a classifier on P vs U with the unlabeled treated as negatives and reweighted by the estimated class prior, the Elkan-Noto adjustment, or use a non-negative PU risk estimator. scikit-learn does not ship a PU estimator; the practical approximation is LogisticRegression with sample_weight set to 1 for P and π/(1−π) for U, where π is the estimated positive rate in U. If π is small, that weight is small and the model mostly learns from P; if π is large, U dominates and the model collapses toward predicting everything positive.

Evaluation is where the frame gets tested. You cannot compute precision without negatives. Three things work:

  1. Held-out positives: recall@k at a fixed alert budget. E.g., top 1% of scores. Is estimable and comparable across frames.
  2. A small, randomly sampled, human-reviewed negative set from U. This is the only way to get a calibrated precision estimate. Report the sampling rate and the confidence interval; 200 reviewed items from a 9,800 pool gives a precision estimate with roughly ±7% at 95% confidence.
  3. PU-specific prior estimation: hold out a subset of P, estimate the label frequency c = P(s=1|y=1), and use it to convert the classifier's output to P(y=1|x). If c is misestimated, the threshold is wrong even when ranking is fine.

A worked check: 10,000 transactions/day, 200 confirmed frauds, π estimated at 0.5% (50 frauds in U). Weighted logistic regression gives a score. On a held-out 50 positives, recall@1% is 0.62. On 200 randomly reviewed unlabeled items, 3 are fraud → precision ≈ 1.5% with a wide interval. That precision is the number the business needs; the recall@k is the number the modeler needs. One-class SVM on the same data gives a boundary but no probability, so you cannot threshold it as if it were calibrated.

Failure modes: prior misestimation (detect by checking the predicted positive rate against π); unlabeled pool contaminated with too few negatives (detect by the reviewed negative sample coming back nearly all positive); and using reviewed alerts as negatives. That sample is biased by the current model and will overstate precision.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

How do you choose between collecting labels and using an unsupervised proxy?

Answer

Core answer (say this first)

Start with the proxy plus a small labeled anchor set, and let a two-week pilot decide whether labels earn their cost. Three checks, in order:

  1. Is the outcome measurable on a random sample at all? If you cannot get 100-200 ground-truth labels inside the latency you need, you are choosing the proxy by default: say that out loud rather than pretending it was a comparison.
  2. Does the proxy's ranking concentrate the outcome? Label the top 100 items the proxy ranks plus a stratified random 100. If precision@100 is 0.62 against a 0.005 base rate, the proxy carries signal. If it is 0.007, it does not, and no amount of staring at the embedding space will fix that.
  3. What does the next 1,000 labels buy? Fit the same model at n = 200, 500, 1,000, 2,000 labeled rows. A flat curve means stop; a steep one means keep labeling.

Collect labels when an automated action is taken and errors are asymmetric: a missed fraud at 50x the cost of a false alarm rarely tolerates a proxy you cannot validate against outcome. Stay unsupervised when the proxy only prioritizes humans for review, or when ground truth is structurally unavailable.

The pilot arithmetic (hypothetical numbers, but this is the shape the decision takes)

Prevalence 0.5%. A random 1,000 labels yields about 5 positives; the Wilson 95% interval on that rate is roughly 0.2% to 1.2%, too wide to fit anything on. Two fixes: stratify and oversample the rare strata, and label the top of the proxy ranking, where positive density is two orders of magnitude higher.

At $40/hour for an annotator averaging 60 items/hour, a label costs about $0.67; 2,000 labels is $1,340 before review overhead. Pair that with the learning curve the pilot produced: AUC 0.74 at n=200, 0.79 at 500, 0.81 at 1,000, 0.82 at 2,000. The last 1,000 labels bought 0.01 AUC. If reviewing a flagged item costs $0.50 and a miss costs $25, with 20,000 items/day flowing through, that 0.01 AUC moves too few decisions to pay $1,340 plus ongoing maintenance, unless the loss per miss is far larger, which is precisely when you buy the labels.

Failure modes and how each one shows up

failuremechanismdetection
Proxy driftInput distribution moves; distances in embedding space no longer rank the same wayPSI on the proxy score above 0.2, or a two-sample KS test at p < 0.01, week over week
Selection bias in labelsAnnotators work a queue the proxy already filtered, so the labeled set is the top of the rankingAdversarial validation: fit HistGradientBoostingClassifier to predict labeled vs unlabeled rows; AUC 0.9 means the labeled set is unrepresentative and your learning curve is optimistic
Proxy-outcome decouplingSpearman correlation held during development, died after a product or policy changeMonthly random 100-item audit; a fall in rho from 0.5 to 0.1 is decoupling, not noise
Label noise dominatesAnnotator disagreement means more labels add variance, not signalDouble-annotate 50 items; Krippendorff alpha below 0.6 means fix the guideline before buying more labels
Feedback loopActing on the proxy changes the population it scores: you block the fraud, the fraud movesRe-estimate precision@k on fresh data monthly; monotone decay is the signature

Choosing, in one line

Buy labels when an automated-decision cost model says the marginal AUC is worth more than $0.67 a label and the proxy cannot be validated against outcome; keep the proxy when it is stable, its top-k precision sits well above base rate, and a human remains in the loop. Weak supervision (Snorkel labeling functions) and semi-supervision (scikit-learn LabelSpreading) sit in between: they turn rules and unlabeled structure into supervision at near-zero marginal cost, but they inherit the same decoupling risk and need the same audit.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

How should label quality be measured and improved?

Answer

Clarify first: what decision does the label drive, and which error is expensive? Assume a supervised model, asymmetric error costs, and a fixed labeling budget.

The core answer: never report one overall agreement number. Double-label a sample stratified by class and by cohort, report agreement per class with prevalence attached, spend reviewer time adjudicating only the disagreements that sit on the decision boundary, and keep a small rotating gold set to catch rater drift. Aggregate agreement is dominated by the majority class, so it looks healthy while the class the model exists to find is noise.

Why per-class and per-cohort. Kappa corrects for chance, but skewed prevalence breaks it. Take 200 items at 10% positive; each rater marks 20 positive and 180 negative, overlapping on 12 positives and 172 negatives:

Po = (12 + 172) / 200 = 0.92 Pe = 0.10 * 0.10 + 0.90 * 0.90 = 0.82 kappa = (0.92 - 0.82) / (1 - 0.82) = 0.556

So 92% raw agreement, kappa 0.56, which lands in Landis and Koch's 0.41-0.60 "moderate" band. Positive-class agreement, both-positive over either-positive, is 12 / 28 = 0.43; the negative class is 172 / 188 = 0.91. The class you care about is at coin-flip agreement and the headline number hid it.

Cohorts work the same way. A cohort holding 2% of the corpus can move aggregate agreement by at most 2 points, realistically about one, and a 1,000-item check carries +/- 3.1 pp of sampling noise (1.96 * sqrt(0.25 / 1000)). The regression is real but invisible, which is why cohort-level numbers are a detection device rather than a reporting preference.

How adjudication separates ambiguity from error. A disagreement means one of two things: the guideline does not decide the case, or a rater did not follow it. The labels alone cannot tell you which. Send the pair to a third reviewer who writes one line: "guideline covers it, rater A missed condition 3" (error) or "guideline silent" (ambiguity). Errors go back to the rater. Ambiguity becomes the next guideline version, and the item plus its adjudicated label joins the gold set. Track the ratio: ambiguity-dominated means the guideline is underspecified and another training round will not help; error-dominated means it will.

On the statistic itself: Cohen's kappa is two raters on fully crossed items, Fleiss for more than two, and Krippendorff's alpha when items are only partially crossed or the scale is ordinal. Pick by the labeling design, not by habit.

Sizing, with the arithmetic. Per-class standard error is sqrt(p(1-p)/n), worst case at p = 0.5:

double-labeled per classworst-case 95% CIuse
200+/- 6.9 ppminimum to trust a class number
800+/- 3.5 ppgate on a benchmark set

That is 200 per class, not 200 overall, which means oversampling rare classes to reach the floor. Embed 3-5% gold items per batch, 10-20 per rater per week, and act when gold accuracy drops below 90%.

Where not to spend. If the label is programmatically derivable - a unit-test result, a click, a downstream conversion - generate it and review only the residual; human agreement buys nothing on those items. If the class is exploratory and throughput beats precision, single-label and spot-check 1-2% instead of double-labeling everything: adjudication is the expensive step and only pays on the boundary. Above roughly 99.5% prevalence, kappa is almost pure chance correction, so report label precision against a small adjudicated set instead, and say which number you are quoting.

Failure modes and detection. Kappa paradox: print Po, Pe and per-class agreement together, never kappa alone. Guideline drift: relabel a stored sample under the current guideline, and old-versus-new kappa below 0.80 means the corpus is mixed-version - which is why every label carries source, time, guideline version and confidence. Rater decay: plot per-rater gold accuracy weekly; a drop is a training event, not a firing event. Model-as-annotator: sampling only disagreements for adjudication biases the gold set toward hard items, so sample agreements in comparable counts.

Krippendorff's convention of alpha at or above 0.80 for reliable coding, below 0.667 unusable, is a defensible floor to argue against - unlike "we eyeballed it".

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

How do you use unsupervised outputs (cluster assignments, learned embeddings, or density scores) as features in a supervised model, and what leakage and overfitting risks does that introduce?

Answer

First I'd separate the three cases, because they fail differently. Cluster assignments are discrete, arbitrarily labelled and fold-dependent. Embeddings are a dense learned basis. Density scores are a scalar summary of where a row sits relative to a fitted distribution. All three are fitted transforms, so the invariant is the same one that governs a scaler: fit on the training fold only, apply to validation and test. The unit of correctness is the fold boundary, not the model.

The wrong version is common and looks fine in a notebook:

python

scikit-learn 1.4

km = KMeans(n_clusters=20, n_init=10, random_state=0).fit(X) # all rows X_aug = np.hstack([X, km.labels_[:, None]]) cross_val_score(LogisticRegression(), X_aug, y, cv=5) # optimistic, uninterpretable

Right: the clusterer is a pipeline step, refit per fold

pipe = Pipeline([ ("scale", StandardScaler()), ("km", KMeans(n_clusters=20, n_init=10, random_state=0)), ("clf", LogisticRegression(max_iter=1000)), ]) cross_val_score(pipe, X, y, cv=5)

Note what the correct pipeline actually feeds the classifier: KMeans.transform returns distances to the 20 centroids, not labels. That is usually the better feature anyway, because cluster 3 in fold 1 has no relationship to cluster 3 in fold 2: the ID is fold-local and a one-hot of it is not comparable across refits. If you need the label, you have to align centroids or accept the instability.

riskmechanismdetection
Unsupervised leakageCentroids, PCA components or density estimates fit on train+test; validation rows move the transformCV score drops sharply when the transform is refit inside each fold
Target proxyClustering or an autoencoder fit on columns that are consequences of the label (post-outcome events, resolution codes)Cluster purity against y; drop the post-outcome column, re-cluster, re-measure
Overfitting via cardinalityOne-hot cluster ID with small clusters, or a 256-dim embedding on few rowsCompare ID features against distance features; permutation importance on the cluster block

The cardinality risk is arithmetic, not vibes. 100k rows into k=500 clusters averages 200 rows each, but the size distribution is long-tailed: if the smallest 50 clusters hold 3 rows apiece, a one-hot ID hands a GBM a key that isolates three training rows, and it will memorize their majority label. Same shape for embeddings: 256 dimensions over 5k rows is ~20 rows per dimension, plenty of room to fit noise.

A cluster that predicts the target almost perfectly is a warning, not a win. Ask whether the clustering was fit on a column that only exists because the outcome happened. The unsupervised step did not create that leak; it laundered it into a dense representation that is harder to audit, which is why the ablation matters: drop the unsupervised block, refit, and see whether the gain survives. If it does not, the features were carrying the split, not the signal.

When not to do this: with enough labels, the unsupervised step adds a hyperparameter (k, embedding dimension), a second artefact to version alongside the classifier, and a refit path when centroids move. If the ablation shows no lift, delete it.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

How do you detect and prevent selective-label feedback loops?

Answer

Selective-label loops form whenever the model's own output decides which cases get a label. If you only review the alerts the model flags, only approve the loans it scores above threshold, only treat the patients it selects, your training set is a sample of P(x | action = 1), not P(x), and the action is a function of the model you're trying to train. The rejected region never gets labels, so errors there are invisible and never corrected; the accepted region gets labels and does get corrected. Retrain on that and the boundary becomes self-justifying: the model's past decisions become the ground truth. So the question isn't "is my model accurate", it's "what is the probability this case got observed, and does that probability depend on the score".

Detection, three signals I'd instrument:

  1. Coverage by score band and subgroup: P(action = 1 | score decile, group). If a decile's coverage collapses toward zero, you have no data there and no way to evaluate it.
  2. A randomized audit stream: a small fraction of traffic where the action is chosen at random, independent of the score. That is the only source of unbiased labels in the rejected region. Compare the model's ranking against audit outcomes; the gap is the loop's damage.
  3. Label-source lineage: what fraction of labels come from the policy's own action? If it's 100%, no correction is possible and I'd say so rather than pretend.

Correction. With propensities recorded, bounded away from zero, and the propensity model correctly specified, inverse propensity weighting makes the labeled sample representative: weight each example by 1/P(action = 1 | x). Doubly robust / AIPW combines that with an outcome model and is consistent if either is right, with better variance. Off-policy evaluation (IPS, DR) does the same for a candidate policy without deploying it.

The cost is variance, and it's brutal in the low-propensity region. Hypothetical: band A has propensity 0.5 with 1,000 labeled examples (weight 2); band B has propensity 0.02 with 100 examples (weight 50). Σw = 7,000, Σw² = 254,000, so effective sample size = 7,000²/254,000 ≈ 193. Eleven hundred labels buy you the statistical power of about 193, because the rare band carries the weight but almost none of the information.

Trade-offs. If you can randomize safely (ranking, ad placement, review-queue ordering) epsilon-greedy at 1–5% is cheap and gives you the audit stream. If you can't (credit denial, medical treatment, criminal justice) you cannot get unbiased labels for the rejected region. Then you record propensities, state the positivity assumption explicitly, and lean on delayed external outcomes (a default observed at 12 months, not the approval decision) and policy-independent cohorts. Retraining on looped data without correction makes it worse, not better.

Failure modes:

failurehow you see itcost
propensity collapsecoverage monitor per decile; IPW weights explode, ESS dropsdrop the region, or admit you can't evaluate it
label monoculturelineage check: 100% of labels from the policy's own actionno correction possible; you need a new label source
audit contaminationaudit rows show up in the training setaudit must be permanently held out; training data shrinks
metric illusionlabeled accuracy rises while audit-confirmed accuracy fallsthe classic signature: you're optimizing the loop
delayed-label driftlabel maturity differs across cohortswait, or train on immature labels

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

Design monitoring for a supervised model with delayed labels.

Answer

Clarify first. Is the label delay fixed (a 90-day default window) or event-driven (churn, readmission, fraud chargeback)? Fixed windows let me schedule cohort evaluation; event-driven ones need a maturity date per prediction. I'll assume a fixed 90-day window, predictions logged at serve time, labels landing in a warehouse table keyed by prediction_id. If the delay is variable, the same design works but the maturity date is per-row, not per-cohort.

The core split. Monitoring a delayed-label model is two planes that must not be confused. Plane one is operational and input health, available in seconds: schema, null rate, feature and score distributions, coverage, p99 latency, threshold volume, override rate, and per-slice counts. These are diagnostics: a score-distribution shift is a reason to look, not evidence the model is wrong. Plane two is outcome quality: calibration, error, cost, and subgroup metrics, computed only on cohorts whose labels have matured. The whole design is about keeping plane one honest and plane two unbiased.

Prediction logging. Every served prediction writes prediction_id, model_version, feature_version, score, threshold, served_at, and maturity_date = served_at + 90d. Without the version columns you cannot attribute a regression to a model or feature change later.

Cohort backfill and censoring. The trap is computing quality on partially matured cohorts. Take 1M predictions/day and a 90-day window: at any moment ~90M predictions are in flight with no label. Worse, the labels that have arrived are biased. In a 100k cohort, at day 30 you observe roughly 2% defaults, the early ones, against a true 4% at day 90. Precision and recall computed at day 30 are wrong in a direction you can't sign without knowing the hazard curve. So the backfill job only touches cohorts where maturity_date <= current_date:

SQL
-- daily job: score only fully matured cohorts
SELECT model_version, cohort_date,
       AVG(ABS(score - label)) AS mae,
       SUM(score >= 0.5 AND label = 1) / NULLIF(SUM(label = 1), 0) AS recall
FROM predictions p
JOIN labels l USING (prediction_id)
WHERE p.maturity_date <= CURRENT_DATE
GROUP BY model_version, cohort_date;

Alerting. Leading signals (PSI on the score distribution, KS on key features, null-rate jumps, latency) page on-call because they're fast. A PSI above 0.2 is the common convention for "investigate"; it is a heuristic, not a guarantee. Outcome alerts fire on matured cohorts only, and only when the cohort is large enough that the metric's confidence interval excludes the baseline: otherwise you page on noise. I'd set the minimum cohort size from the baseline metric's variance, not a round number.

Retraining. The training set is maturity_date <= today. Training on incomplete labels teaches the model the early-defaulter hazard, not the outcome.

Failure modes to name. Label pipeline lag (maturity dates silently drift: alert on label arrival vs expected); survivorship in slices (a subgroup with slow labels looks clean because it's under-observed); threshold drift when the score distribution moves but the threshold doesn't; and feedback loops where overrides change the labels the next model trains on. Detect the first with a freshness check on the label table, the last by logging override reasons and monitoring their rate per slice.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

Design monitoring for a deployed clustering system.

Answer

Assumptions and core answer

Setup I'll assume: k-means with k=64 over 768-dimensional embeddings, daily batch assignment of ~2M items, cluster IDs consumed by a ranking service and a weekly dashboard. I monitor two layers, because they fail independently:

  • Geometric health: is the partition still well-formed?
  • Application meaning: do the clusters still predict the outcome we act on?

A clustering can be geometrically perfect and semantically dead: tight, stable, and no longer aligned with anything the business cares about. So one layer's green light never covers the other.

Signals, thresholds, actions

SignalMetricAlert thresholdAction
Input driftPSI per feature vs 28-day reference> 0.25investigate upstream
Centroid movementcosine shift / median intra-cluster distance> 0.5refit candidate
Assignment stabilityARI between consecutive runs, same items< 0.7freeze IDs, investigate
Cluster sizemin cluster share of population< 0.5% or > 3x mediancheck k, empty clusters
Noise rate (HDBSCAN)unassigned fraction> 15% (baseline 8%)refit
Semanticoutcome spread across clusterstop-bottom ratio < 1.2refit

PSI bands are the standard ones: < 0.1 stable, 0.1–0.25 moderate, > 0.25 shift.

Why each signal moves

Centroid movement is the leading indicator. If a centroid travels more than half the typical intra-cluster distance, the cluster's membership has effectively been replaced even when its size looks unchanged. Size alone hides this: a cluster can keep 30k members while swapping most of them. That is why I pair size with ARI: ARI < 0.7 on the same items means the partition itself changed, not just the data feeding it.

Trade-off: refit vs frozen centroids

Frozen centroids keep IDs stable (no consumer migration, dashboards keep working) but drift accumulates and assignments degrade silently. Full refit adapts but renumbers everything, breaking stored IDs and per-cluster history. I take the middle path: refit weekly, then match new centroids to old by cosine similarity and renumber only clusters whose best match falls below 0.8. Clusters above that keep their ID; the rest get a new one plus a migration note. The matching step is O(k^2) = 4096 comparisons, negligible; the real cost is the migration contract with consumers.

Failure modes

  • Silent semantic drift: PSI > 0.25 after a new product category launches, but silhouette holds at 0.31 because the geometry is self-consistent. Only the outcome-spread check catches it.
  • Cluster collapse: k=64 but the data has ~40 real modes; empty clusters and a min share near zero. Detected by the size floor.
  • ID churn: a refit renumbers all 64 clusters, breaking per-cluster dashboards. Detected by ARI < 0.7 before the refit ships.
  • Feedback loop: we target cluster 7 with a promo, its composition shifts, the next refit moves it. Detected by monitoring composition drift after actions, not only before.

Artefacts

Arithmetic: median intra-cluster cosine distance 0.42; a centroid moves 0.31, so normalized shift = 0.31 / 0.42 = 0.74 > 0.5, flag for refit.

Python
from sklearn.metrics import adjusted_rand_score
import numpy as np

# same items, same order, consecutive daily runs
ari = adjusted_rand_score(labels_prev, labels_new)   # 1.0 = identical partition

def centroid_shift(C_old, C_new):
    # C_*: (k, d) unit-normalised centroids
    sim = C_new @ C_old.T          # (k, k) cosine similarity
    return 1.0 - sim.max(axis=1)   # per new centroid: distance to closest old

Checked against scikit-learn 1.4: adjusted_rand_score returns 1.0 for identical labelings regardless of label permutation.

Curated: · Written: · Reviewed:

Difficulty: Hard