ML System Evaluation and Metrics Questions
Design comprehensive evaluation strategies including offline metrics (precision, recall, F1, AUC, calibration), online metrics (A/B test setup, statistical significance), and business metrics. Understand metric limitations and how to avoid gaming metrics.
MediumTechnical
58 practiced
Given historical logs containing model scores, user exposures, and downstream purchase amounts, design an offline evaluation method to estimate expected revenue lift from switching to a new scoring model. State required assumptions, common biases (position bias, confounding), and how you'd use an experiment to validate offline estimates.
Sample Answer
Approach summary- Treat this as a counterfactual estimation problem: we want E[revenue | expose under new model] using logs collected under the historical (logged) policy. Use importance-weighted estimators and doubly-robust (DR) methods to get unbiased / lower-variance estimates, plus diagnostics and sensitivity checks.Offline procedure (practical steps)1. Define the policy mapping: simulate the new model on historical feature vectors to produce new scores and implied exposures (e.g., top-K, thresholds, or probabilities).2. Estimate propensities p_0(a | x) — probability historical policy exposed item a given context x — from logs (if randomized exposure exists use that; otherwise fit a model using features + position to predict exposure).3. Compute importance weights w = p_new(a | x) / p_0(a | x). Use IPS estimator for expected revenue: E_hat_IPS = sum(w * revenue) / sum(w). Prefer doubly-robust: DR = outcome_model(x,a) + w*(observed_revenue - outcome_model(x,a)).4. Regularization and robustness: clip weights, use weight truncation or self-normalized IPS, and bootstrap to get CIs. Use outcome model (regression) trained on logs for DR to reduce variance.5. Diagnostics: check overlap (common support) between p_new and p_0; histogram of weights; bias-variance tradeoff with clipping; calibration of outcome model.Required assumptions- Unconfoundedness (no unobserved confounders): given observed features x, exposure assignment is independent of potential outcomes.- Positivity/overlap: p_0(a|x) > 0 wherever p_new(a|x) > 0.- SUTVA: one user's exposure doesn't change another's outcome (no interference).- Correctly specified propensity or outcome models (DR protects if one is correct).Common biases & how to handle them- Position bias: revenue (or clicks leading to revenue) depends on position; include position in x and model position propensities; if position was systematically assigned, estimate position-specific p_0 or use randomized position logs / click models to de-bias.- Selection/confounding: historical model may have targeted high-value users; control with rich covariates, use outcome regression, or use instrumental variables if available.- Coverage bias: new model recommends items never or rarely exposed historically → lack of support; avoid extreme extrapolation, or run small randomized test to collect needed data.- Survivorship and censoring: consider time windows and right-censoring for delayed purchases; use appropriate survival models.Validation experiment- Run an A/B test (online randomized experiment) comparing current model vs new model on a representative traffic slice. Key elements: - Randomize at the same unit used offline (user or session). - Pre-specify primary metric (revenue per user, ARPU) and secondary metrics (CTR, conversion rate, position-level lift). - Use ramped rollout: small percentage first to validate safety and confirm offline estimate, then scale. - Compare observed uplift to offline point estimate and CI; if mismatch, run post-hoc stratified analysis to find segments where offline model failed (e.g., due to unobserved confounding).- If full A/B is expensive, run a small randomized logging experiment where exposure is randomized to gather unbiased propensities for improved offline estimation.Reporting & action- Report IPS and DR estimates with bootstrap CIs, weight diagnostics, segment-level lifts, and sensitivity analysis for hidden confounding.- If offline and online estimates align within CIs, proceed to rollout; if not, iterate: collect randomized data, improve covariates/outcome model, or constrain new policy to supported regions.
MediumTechnical
68 practiced
You operate two models: one optimized for short-term CTR and another optimized for long-term retention. Propose an offline evaluation protocol and an experiment design to understand combined impact and trade-offs, and outline a safe deployment strategy for a combined policy.
Sample Answer
Situation & goal: We have two policies — CTR-optimized (short-term engagement) and retention-optimized (long-term value). We must estimate combined impact, surface trade-offs (immediate clicks vs. future retention/revenue), and deploy a safe combined policy.Offline evaluation protocol- Define primary metrics: short-term CTR, 7/30/90-day retention, LTV proxy (e.g., revenue or session minutes), and business guardrails (no severe CTR drop, no negative revenue delta).- Log randomized data with full propensities (exploration policy or randomized score buckets) so we can do unbiased counterfactuals.- Use IPS / self-normalized IPS and Doubly Robust estimators to estimate policy value for any linear blend or learned mixture of the two models. Estimate per-cohort effects (new vs. returning users, content buckets).- Simulate combination strategies offline: - Deterministic rule-based (e.g., weighting by user segment) - Contextual gating (model selector trained to maximize a reward that mixes short and long-term signals) - Stochastic mixture (sample policy with probabilities)- Compute confidence intervals, and run sensitivity analysis to propensity misspecification and delayed rewards.Experiment design (online)- Start with A/B/n: - Control: current production - Arm A: CTR-only - Arm B: Retention-only - Arm C: Combined policy (best offline candidate)- Use stratified randomization (new vs. existing users, geography, device).- Primary analysis window: short-term metric (CTR) at 1-7 days; long-term: retention/LTV at 30/90 days. Use interim checks with pre-specified sequential testing to avoid peeking.- If multiple combined candidates, run multi-armed bandit / adaptive allocation after initial burn-in to allocate more traffic to promising arms while preserving power.- Power calculation: ensure sample size large enough to detect minimum business-relevant deltas (e.g., 1–2% CTR, 0.5% retention).Safe deployment strategy- Shadow/Logging mode: deploy combined policy in parallel (no serving) to validate logged predictions and compare offline estimates to production behavior.- Canary rollout: 1% → 5% → 25% → 100% with rollback thresholds tied to guardrail metrics (e.g., CTR drop > X%, revenue decline > Y%).- Monitoring & alarms: real-time dashboards for CTR, retention leading indicators (session length, repeat visits), error rates, and system metrics. Automated rollback when thresholds exceeded.- Incremental learning: if selector is learned, freeze model weights for a period, then retrain with production data; consider conservative regularization to avoid drift.- Human-in-the-loop: manual review for edge cohorts flagged by offline sims (e.g., new users where combined policy hurts retention).- Documentation & kill-switch: feature flags and runbooks for immediate rollback and postmortem.Why this works- Counterfactual estimators let us evaluate many combinations without full A/Bs.- Stratified online experiments and adaptive allocation speed up learning while protecting users.- Progressive rollout with guardrails ensures business continuity and quick recovery from negative surprises.
MediumTechnical
65 practiced
Design a metric framework for a model where you must balance prediction accuracy, inference latency (milliseconds), and per-inference cloud cost. Propose composite metrics or multi-objective strategies suitable for product decisions and CI/CD gating, including how to pick weights or present Pareto frontiers to stakeholders.
Sample Answer
Start by clarifying hard constraints vs. trade-offs: which metric(s) have SLOs (e.g., 99th‑pct latency ≤ 50 ms, max $0.002/inference) and which are flexible (accuracy). Then capture all three on a common scale (higher = better) so they can be combined or compared.Normalization examples:- Acc_norm = (Acc - Acc_min) / (Acc_max - Acc_min)- Lat_norm = 1 - (Latency_ms - Lat_min)/(Lat_max - Lat_min) (so higher is better)- Cost_norm = 1 - (Cost - Cost_min)/(Cost_max - Cost_min)Composite (weighted utility):Utility = w_a * Acc_norm + w_l * Lat_norm + w_c * Cost_normPick weights (w_a+w_l+w_c=1) by stakeholder workshops, e.g. translate business value: how much revenue lift per 0.1% accuracy vs. cost savings vs. SLA penalties. Use sensitivity analysis: show how rank ordering changes when weights vary ±20%.Alternative: Multiplicative utility to penalize low values:Utility = Acc_norm^α * Lat_norm^β * Cost_norm^γCI/CD gating:- Hard gates: enforce SLOs (reject if 99th‑pct latency > threshold or cost > budget).- Soft gates: require composite Utility ≥ threshold OR model on Pareto frontier.- Run automated benchmark suite: accuracy on holdout, latency distribution at target throughput, measured per-inference cost.Pareto presentation to stakeholders:- Plot Accuracy vs Latency (color by cost) and show Pareto frontier points.- Provide a short table: model, utility score under baseline weights, SLO pass/fail, cost per 1M inferences.- Provide trade-off scenarios: "If we accept +5 ms latency, accuracy improves +0.4% and cost increases $0.0003 — ROI = ..."How to pick weights practically:- Map outcomes to business metrics (revenue, penalties, ops cost).- Use historical experiments/A/B tests to estimate marginal revenue per accuracy point.- If mapping uncertain, pick multiple weight sets (accuracy-first, latency-first, cost-first) and show robustness of decisions.Monitoring & evolution:- Recompute normalized ranges periodically, monitor drift, and re-run sensitivity weekly.- CI: include reproducible benchmark harness, dataset seeds, and cost/latency simulators.This approach gives both a simple, explainable composite for automated gating and Pareto visuals for product trade-off decisions.
MediumSystem Design
86 practiced
Design a continuous validation strategy for model releases that includes canary testing, shadow mode evaluation, progressive percentage rollouts, and automatic rollback triggers. Specify which metrics to monitor at each stage, safety guardrails, and how to ensure reproducible comparisons.
Sample Answer
Requirements & goals:- Safety: avoid user impact from regressions.- Observability: detect small deviations quickly.- Reproducibility: deterministic comparisons between baseline and candidate.- Automation: progressive rollout + automatic rollback when thresholds breached.High-level flow:1. Shadow mode (100% traffic mirrored, no user impact)2. Canary testing (small % of real traffic routed to candidate)3. Progressive percentage rollout (e.g., 1% → 5% → 25% → 100%)4. Full release or automatic rollbackMetrics to monitor (per stage):- Data / input checks (all stages): input schema conformity, feature drift (KS/Population Stability Index), missing rate.- Shadow mode (offline + real inputs): model quality metrics (accuracy, AUC, MSE depending on task), calibration (Brier score), latency distribution, resource usage; compare candidate vs baseline on identical inputs.- Canary (small live traffic): user-facing metrics (error rate, latency P95/P99), business KPIs (conversion, CTR, revenue per user), model KPIs on labeled feedback (if available): precision, recall; monitor upstream system errors.- Progressive rollout: same as canary but also cohort comparisons (new vs baseline) using statistical tests (e.g., sequential A/B test with confidence intervals), and monitor drift over time.Safety guardrails & automatic rollback triggers:- Hard rollback triggers (immediate): increase in user-facing error rate > X% absolute (e.g., +0.5% if baseline 1%), latency P99 increase > Y ms, service errors (5xx) spike above threshold, failed schema validations.- Soft rollback / pause triggers (require human review): statistically significant degradation (p < 0.01) on key business metric or model metric sustained for N minutes/requests; resource exhaustion approaching capacity.- Canary timeout: if no labeled feedback available within TTL, abort rollout.Reproducible comparisons:- Deterministic logging: store request id, input features, model versions, model deterministic seeds, model artifacts hashes, environment metadata (container image, libs).- Use same preprocessing and feature pipelines for baseline and candidate; snapshot feature engineering code and data transforms.- Run paired-evaluation: for each request in shadow mode and canary, compute baseline and candidate outputs and persist predictions and raw inputs to a validation store for offline statistical tests.- Use synthetic/recorded replay tests periodically to validate behavior on identical inputs.- Versioning: model artifacts, training dataset snapshot, config, and evaluation script in a single release bundle.Implementation notes:- Platform: deploy via CI/CD with gated pipelines that run shadow evaluation and automatic metric checks; use feature flags and traffic routers (service mesh / API gateway) to control rollout percentages.- Monitoring: metrics in time-series DB (Prometheus) + analytical store for prediction logs (BigQuery/S3). Automated alerting via PagerDuty for hard triggers and dashboards for reviewers for soft triggers.- Statistical rigor: use sequential testing (alpha spending) to avoid false positives during progressive rollout.- Post-release: automated postmortem and root-cause traces on any rollback; record lessons as part of release metadata.This strategy balances safety and velocity by validating candidate models on identical inputs, monitoring both technical and business signals at each stage, and enforcing automatic, well-defined rollback rules.
MediumTechnical
63 practiced
Given K-fold cross-validated predicted probabilities and true labels (predictions from folds are correlated), implement (or describe) a Python method to compute a confidence interval for the overall AUC that accounts for correlation between folds (stratified or aggregated bootstrap). State assumptions and complexity implications.
Sample Answer
Approach summary:- Use bootstrap to produce a CI for the overall AUC while accounting for correlation induced by K-fold CV. Two practical options: 1. Observation-level (aggregated) bootstrap: resample the original observations (with their CV-predicted probability and true label) with replacement. If class imbalance is concern, do stratified resampling within classes. 2. Fold-cluster bootstrap: treat each CV fold as a cluster and resample folds (with replacement), concatenating all observations from selected folds — preserves intra-fold correlations from shared training. Use percentile or BCa intervals.Both methods assume that resampling unit (observation or fold) captures dependence structure. Percentile CI from bootstrap is simple; BCa is more accurate but costlier.Python implementation (aggregated + stratified option):Key points and assumptions:- Aggregated bootstrap assumes observations are exchangeable; stratified resampling preserves class ratio and reduces variance in imbalanced settings.- Cluster (fold-level) bootstrap assumes folds capture dependence induced by CV sharing; requires enough folds to resample meaningfully.- Use percentile CI for simplicity; BCa or bias-corrected methods are preferable if high accuracy needed.Complexity:- Each bootstrap AUC is O(m log m) due to sorting inside ROC/AUC; overall O(B * n log n) (n = sample size). Memory O(n + B) to store results.Edge cases:- Very small n or very few positive/negative samples -> bootstrap unreliable.- If cluster_by_fold=True but K is small (e.g., 5), bootstrap variability may be large; consider repeating CV with different splits (repeated CV) to better estimate uncertainty.
python
import numpy as np
from sklearn.metrics import roc_auc_score
def auc_bootstrap_ci(y_true, y_pred, fold_ids=None, B=2000, alpha=0.05, stratified=True, cluster_by_fold=False, random_state=None):
"""
Compute bootstrap CI for AUC.
- y_true, y_pred: arrays aligned per-observation (CV predicted prob for each obs)
- fold_ids: required if cluster_by_fold=True
- B: bootstrap samples
- stratified: when True and cluster_by_fold=False, resample within classes
- cluster_by_fold: when True, resample folds (fold_ids required)
Returns: (auc_point_estimate, lower, upper, all_bootstrap_aucs)
"""
rng = np.random.default_rng(random_state)
y_true = np.asarray(y_true)
y_pred = np.asarray(y_pred)
n = len(y_true)
# point estimate
auc0 = roc_auc_score(y_true, y_pred)
boot_aucs = []
if cluster_by_fold:
if fold_ids is None:
raise ValueError("fold_ids required for cluster bootstrap")
folds = np.unique(fold_ids)
fold_to_idx = {f: np.where(fold_ids == f)[0] for f in folds}
for _ in range(B):
sampled_folds = rng.choice(folds, size=len(folds), replace=True)
idx = np.concatenate([fold_to_idx[f] for f in sampled_folds])
# allow duplicates -> keep duplicated indices to reflect sampling
boot_aucs.append(roc_auc_score(y_true[idx], y_pred[idx]))
else:
pos_idx = np.where(y_true == 1)[0]
neg_idx = np.where(y_true == 0)[0]
for _ in range(B):
if stratified:
s_pos = rng.choice(pos_idx, size=pos_idx.size, replace=True)
s_neg = rng.choice(neg_idx, size=neg_idx.size, replace=True)
idx = np.concatenate([s_pos, s_neg])
else:
idx = rng.choice(np.arange(n), size=n, replace=True)
boot_aucs.append(roc_auc_score(y_true[idx], y_pred[idx]))
boot_aucs = np.array(boot_aucs)
lower = np.percentile(boot_aucs, 100 * (alpha/2))
upper = np.percentile(boot_aucs, 100 * (1 - alpha/2))
return auc0, lower, upper, boot_aucsUnlock Full Question Bank
Get access to hundreds of ML System Evaluation and Metrics interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.