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
A production model appears to perform worse for a small demographic segment. Describe which fairness metrics you would compute (demographic parity, equalized odds, predictive parity, calibration per group), how to visualize disparities, and propose remediation strategies such as reweighting, constrained optimization, or separate models.
Sample Answer
First, quantify the gap with multiple fairness metrics — each answers a different question:- Demographic parity (selection rate per group): P(Ŷ=1 | A=a). Useful if equal opportunity to receive positive outcome is required.- Equalized odds: TPR and FPR per group. Compute TPR(a)=P(Ŷ=1|Y=1,A=a) and FPR(a)=P(Ŷ=1|Y=0,A=a) to see whether errors are concentrated.- Predictive parity / PPV per group: PPV(a)=P(Y=1|Ŷ=1,A=a). Important when downstream decisions depend on predicted risk.- Calibration per group: Reliability curves / calibration-in-the-small to check if predicted probabilities match observed frequencies within each group.Visualizations:- Grouped bar charts for selection rate, TPR, FPR, PPV with confidence intervals.- Calibration plots: reliability curve per group (predicted vs observed) and Brier score by group.- ROC curves per group and difference-in-TPR/FPR plots across thresholds.- Disparity heatmap or waterfall showing contribution of base rate, threshold, and model to gaps.- Use sample size annotations and statistical tests (bootstrap CIs, permutation) to assess significance.Remediation strategies (with trade-offs):- Pre-processing / reweighting: up/down-weight examples from underperforming group (or use synthetic oversampling). Simple to implement; may help demographic parity but can distort calibration.- In-processing / constrained optimization: train with fairness constraints (e.g., equalized odds via constrained loss or Lagrangian methods). Gives direct control over metric but can reduce overall accuracy and requires careful hyperparameter tuning.- Post-processing: threshold adjustment per group to equalize TPR/FPR or PPV. Fast to deploy but may be legally/policy-sensitive and can break calibration.- Separate models or group-specific calibration: train group-specific models or apply isotonic/logistic calibration per group if distributional differences justify it. Improves fit but increases maintenance and risks overfitting for small groups.- Causal / feature inspection: check whether features proxy sensitive attribute; remove or adjust features, or incorporate fairness-aware representations.- Monitoring and governance: add per-group metrics to model monitoring dashboards, set alert thresholds, and document remediation plan + stakeholder review.Recommended workflow:1) Measure all metrics and visualize with uncertainty.2) Diagnose root cause (label quality, small-n noise, feature shift).3) Try least invasive (reweighting, calibration per group) and evaluate trade-offs on held-out data.4) If persistent, use constrained training or group models and deploy with monitoring and rollback criteria.Explain trade-offs clearly to stakeholders: fairness definitions conflict — pick the one aligned with business/legal objectives and measure impact on overall utility.
MediumSystem Design
83 practiced
Design a near-real-time evaluation and metric pipeline for a fraud detection model that scores 100k events/second. Include logging, aggregation windows, computation of metrics like precision/recall at thresholds, rolling AUC estimates, storage decisions (hot vs cold), latency SLAs, and trade-offs between streaming and batch processing.
Sample Answer
Requirements & constraints:- Ingest 100k events/sec, near-real-time (<30s) metric availability, compute precision/recall at multiple thresholds, rolling AUC, per-customer and global aggregates, retention hot (7–30 days) vs cold (months-years).- Low overhead on production path; avoid blocking scoring.High-level architecture:- Event producers → Kafka (partitioned by customer/user) → stream processors (Flink / Spark Structured Streaming / ksqlDB) → metric stores + cold lake.Key components & responsibilities:1. Logging: Immutable event log in Kafka with schema (event_id, timestamp, score, label if available, features metadata, source). Downstream consumers can reprocess.2. Streaming ingestion & enrichment: Lightweight Flink jobs that join labels (from delayed labeling system), assign event time, and route to appropriate windows.3. Aggregation windows: - Real-time micro-windows: tumbling 30s for SLA-sensitive dashboards. - Sliding windows: 5m / 1h windows with hop for smoother metrics. - Session/customer windows for churn/fraud investigations.4. Metric computation: - Precision/recall at configured thresholds computed via incremental counters (TP/FP/FN) per window. - Rolling AUC: approximate with incremental AUC sketches (e.g., streaming ROC via binned histograms or t-digest quantile summaries) updated per event to avoid storing all scores.5. Storage: - Hot store: time-series DB (Prometheus or ClickHouse) for aggregated metrics, recent raw events in fast object store (S3 + caching / Redis) for investigations; retention 7–30d. - Cold store: columnar lake (Parquet on S3) for full raw events and reprocessing; retention months–years.6. Latency SLAs: - Ingestion → metric visible in dashboard: <30s (30s tumbling window + processing). - AUC near-real-time estimate: updated every 1m using sketches.7. Monitoring & alerting: thresholds on metric drift, label lag, and processing lag; use dashboards + alerts (PagerDuty).Trade-offs streaming vs batch:- Streaming pros: low latency, continuous feedback, early drift detection. Cons: complexity, approximate metrics, harder exactly-once labeling joins.- Batch pros: exact computations (recompute AUC precisely), simpler correctness for historical analysis, cheaper for long-tail queries. Cons: higher latency.Recommendation: hybrid: streaming for near-real-time approximate metrics and alerts; periodic batch (hourly/daily) recompute for gold metrics, backfills, and model evaluation.Edge considerations:- Label delay: include label arrival time and compute metrics with watermarking; emit both "partial" and "finalized" metrics.- Scale: Kafka partitions >= throughput needs; Flink parallelism tuned; use sampling for heavy customers to bound state.- Consistency: use event-time processing, idempotent writes, and checkpointing for fault tolerance.This design gives fast feedback for model performance while preserving correctness via periodic batch recomputes and cold storage for full audits.
MediumTechnical
86 practiced
Implement a Python function roc_auc_score_manual(y_true, y_score) that computes ROC AUC without using sklearn. y_true contains binary labels and y_score contains predicted probabilities. Use the ranking/trapezoidal method: sort by score, compute TPR/FPR curve, then area via trapezoidal rule. Mention how to handle ties.
Sample Answer
Approach: sort predicted scores (descending), walk through them grouping equal scores (to handle ties), update cumulative true positive (TP) and false positive (FP) counts after each group to produce FPR/TPR points, then compute area under the curve with the trapezoidal rule.Key points:- Handling ties: aggregate all samples with identical scores and update TP/FP once per group — this produces the true step in ROC and avoids falsely inflating AUC by arbitrary ordering within ties.- Equivalent relation: AUC equals probability that a random positive ranks higher than a random negative (Mann–Whitney U).- Complexity: O(n log n) for sorting, O(n) for scan. Space: O(n) for paired list.- Edge cases: empty input, unequal lengths, all positives/negatives (AUC undefined — returned NaN). Alternative: use average rank / Mann–Whitney formula for slightly simpler implementation when ties handled by average ranks.
python
def roc_auc_score_manual(y_true, y_score):
"""
Compute ROC AUC using ranking / trapezoidal rule without sklearn.
y_true: iterable of 0/1 labels
y_score: iterable of scores/probabilities (higher => positive)
Returns: float AUC
"""
# Convert to lists
y_true = list(y_true)
y_score = list(y_score)
if len(y_true) == 0:
raise ValueError("Empty inputs")
if len(y_true) != len(y_score):
raise ValueError("y_true and y_score must have same length")
# Count positives and negatives
P = sum(1 for y in y_true if y == 1)
N = len(y_true) - P
if P == 0 or N == 0:
# AUC is undefined when only one class; return NaN or 0.5 by convention
return float('nan')
# Pair and sort by score descending
paired = sorted(zip(y_score, y_true), key=lambda x: (-x[0], -x[1]))
# Walk grouping ties to avoid artificial zig-zags
tps = [0.0] # cumulative true positives
fps = [0.0] # cumulative false positives
i = 0
while i < len(paired):
score = paired[i][0]
# aggregate group with same score
tp_inc = 0
fp_inc = 0
while i < len(paired) and paired[i][0] == score:
if paired[i][1] == 1:
tp_inc += 1
else:
fp_inc += 1
i += 1
tps.append(tps[-1] + tp_inc)
fps.append(fps[-1] + fp_inc)
# Convert to rates
tpr = [tp / P for tp in tps]
fpr = [fp / N for fp in fps]
# Trapezoidal integration over FPR (ensure monotonic)
auc = 0.0
for k in range(1, len(fpr)):
x0, x1 = fpr[k-1], fpr[k]
y0, y1 = tpr[k-1], tpr[k]
auc += (x1 - x0) * (y0 + y1) / 2.0
return aucHardSystem Design
72 practiced
Design a production monitoring and alerting system for ML models that tracks model performance metrics (AUC, calibration, precision/recall at thresholds), data quality, concept drift, latency, and business KPIs. Specify alert thresholds, severity levels, canary and shadow deployment strategy, automated rollback criteria, and include a sample runbook for triaging an alert.
Sample Answer
Requirements & constraints:- Track model performance (AUC, calibration, precision/recall at thresholds), data quality (missingness, schema, feature drift), concept drift, latency (p99, p95, mean), and business KPIs (conversion, revenue per user).- Low alert noise, tiered severity, automated canary/shadow deploys, safe rollback, explainability for triage.- Retention: metrics hourly/daily; raw inputs for 30 days. SLA: alert within 5 min of threshold breach.High-level architecture:- Inference service (model server) + sidecar metrics emitter → Metrics pipeline (Prometheus + Pushgateway or OpenTelemetry) → Time-series DB (Prometheus/Thanos) for infra/latency + Feature store + Model evaluation pipeline (Spark/Flink) that computes batch performance and drift → Alerting engine (Alertmanager) → Incident system (PagerDuty/Slack) + ML metadata store (MLflow) for model versions → Dashboarding (Grafana) + Automated orchestrator (Argo Workflows / Kubeflow) for canary/rollback.Core components & responsibilities:1. Metrics emitter: emits prediction, model_version, probability, latency, input hashes, feature stats.2. Real-time monitor: computes rolling-window AUC, precision@K, calibration (reliability diagram buckets), and data quality metrics per population segment.3. Drift detector: population-stability-index (PSI), KL-divergence, feature-level KS tests; triggers if sustained beyond lookback.4. Business KPI correlator: links drops in conversion/revenue to model outputs using causal windows.5. Alert manager: evaluates rules, applies dedupe, escalation, and suppression.6. Canary & shadow orchestrator: routes X% traffic to canary; shadow sends traffic to candidate without impacting responses.Alert thresholds & severity:- Sev-1 (Critical, page on-call): AUC drop > 5 absolute points vs baseline over 1 hour AND business KPI drop > 3% over same window OR latency p99 > 2x SLA (e.g., >1s) for >5 min OR unexplained increase in error-rate >1%.- Sev-2 (High, notify team): Calibration Brier score worsened >25% over 24h OR precision@threshold drop >10% over 6h OR PSI >0.2 for top features over 24h.- Sev-3 (Medium): Data schema change detected, missingness >10% for a feature, small drift (PSI 0.1–0.2), daily model-performance degradation <2 points.- Sev-4 (Info): Anomalies flagged in non-critical segments, dashboard alerts.Canary & shadow deployment strategy:- Canary: Gradual rollout 1% → 5% → 25% → 100% with health gates at each step: - Gates: no significant latency regression, no increase in error rate, AUC within -1 point of control on canary traffic, no PSI >0.1. - Hold time: 30–60 minutes at each stage; extend if marginal.- Shadow: send 100% traffic in parallel to candidate; only compare outputs offline to production to detect distributional differences and model output drift without affecting users.Automated rollback criteria:- Immediate rollback (automated) if during canary any Sev-1 condition observed OR latency p99 > SLA*2 for >5min OR error-rate doubles.- Conditional rollback if Sev-2 persists across two evaluation windows (e.g., 2 consecutive hours) after a stability period.- Rollback flow: Orchestrator triggers traffic switch to previous stable model version, marks candidate as failed in MLflow, and creates incident with diagnostics bundle (model version, recent metrics, sample inputs/outputs).Detection windows & smoothing:- Use rolling windows: real-time (5–15 min) for latency/errors; short-term (1–6h) for AUC/precision; medium-term (24–72h) for calibration/drift; weekly for strategic monitoring.- Use statistical significance tests (bootstrap confidence intervals) before alerting on performance deltas to reduce noise.Runbook for triaging an alert (sample Sev-1: AUC drop + business KPI drop)1. Triage (0–5 min) - Confirm alert source and scope in Alertmanager/Grafana. - Check model version, recent deploys, and canary status from MLflow/CI. - Verify latency and error-rate dashboards (if latency spike, prioritize infra).2. Gather evidence (5–15 min) - Pull last 1–6h of model metrics (AUC, precision@K, calibration) and traffic volumes. - Query feature distributions and PSI for top 10 features; run KS tests. - Retrieve sample input/output pairs (anonymized) for failed window. - Check upstream data sources for schema changes or missingness. - Correlate with business metrics via KPI correlator.3. Root cause hypothesis (15–30 min) - If data quality issue (schema/missingness): flag data team, roll back to previous model or serve default logic. - If concept drift (feature distribution shifted) but infra healthy: consider fast retrain on last N days or apply recalibration; if severe, rollback. - If model regression due to code or model artifact: rollback automated and start investigation with CI logs.4. Remediation (30–60 min) - If rollback criteria met: execute automated rollback and verify metrics return to baseline. - If mitigation: apply feature filters, threshold adjustments, or temporary rule-based fallback.5. Post-incident (within 24–72h) - Run postmortem: root cause, timeline, actions, and preventive measures (tests, data contracts). - Add new alerts or tighten thresholds as needed. - Schedule retrain or feature engineering task, and update playbook.Why this design:- Combines real-time and batch evaluation to capture fleeting and persistent issues.- Canary + shadow minimize user impact while validating candidate models.- Statistical checks, smoothing windows, and business KPI correlation reduce false positives and focus engineering effort on incidents that matter to the business.- Automations (rollback, metadata logging) shorten MTTR and preserve reproducibility for postmortem and retraining.
MediumTechnical
83 practiced
Describe methods and metrics to detect concept drift and feature distribution shift in production. Cover univariate statistics (Population Stability Index), divergence measures (KL divergence), model-signal detection (drop in AUC, calibration shifts), and how you would set thresholds and alerts for drift detection in practice.
Sample Answer
Approach summary:- Monitor both feature distribution shifts (input/data drift) and model-signal degradation (performance/calibration). Use a mix of univariate statistics, divergence measures, and model metrics; set thresholds using historical baselines, statistical tests, and business-impact tuning; alert only on sustained/significant changes to avoid noise.Univariate statistics (Population Stability Index, PSI)- Compute PSI per feature between a reference window (training or recent stable period) and current window by binning continuous features or using categorical counts.- Interpretation rule-of-thumb: PSI < 0.1 (no significant change), 0.1–0.25 (moderate), >0.25 (large).- Caveats: sensitive to binning and sample size; use consistent bin edges or quantile bins from reference.Divergence measures (KL, JS, Wasserstein)- KL divergence measures how one distribution diverges from reference; use with smoothed probability estimates to avoid zeros. KL is asymmetric; prefer Jensen-Shannon (JS) for symmetric bounded score or Wasserstein distance for continuous features.- Normalize or bootstrap to get significance: compute divergence on many bootstrap resamples of reference→current to estimate empirical null distribution and p-value.Model-signal detection (AUC drop, calibration shifts)- Track AUC, accuracy, precision/recall, Brier score, and calibration (reliability diagrams, expected calibration error). Use rolling windows and stratify by key slices.- Alert if performance drops beyond a threshold: e.g., absolute AUC drop > 0.02–0.05 or relative drop >5% sustained for N windows. For calibration, trigger if Brier score increases by X% or ECE increases beyond baseline CI.- Use cohort-level checks (e.g., by region, device) to find localized drift.Setting thresholds and alerts in practice- Baseline: derive metric distributions from a long stable period; compute mean and CI using bootstrap or time-series-aware methods.- Statistical thresholds: use z-scores, control charts (CUSUM, EWMA) to detect shifts while controlling false positives; choose significance (e.g., α=0.01–0.05) and require consecutive violations (e.g., 2–3 windows).- Business-aware tuning: map metric changes to expected business impact and set tiered alerts (informational → investigate → automatic retrain/block deployment).- Combine signals: require both input drift (e.g., PSI>0.1 on multiple features or JS divergence high) AND model degradation before high-severity alerts. Use ensemble drift score (weighted).- Operational considerations: enforce minimum sample sizes, add smoothing/decay for streaming data, implement alert cooldowns and annotations, and log drift events for root-cause analysis.Practical example (pseudo-steps)1. Weekly compute per-feature PSI and JS against training baseline.2. Daily compute AUC and Brier over last 7 days; maintain bootstrap CI.3. If PSI>0.1 for ≥3 features OR JS > bootstrapped 95th percentile AND AUC drop >0.03 sustained 2 days → open ticket and run targeted data-quality checks; if confirmed and impact high, trigger model rollback or retrain pipeline.This combined statistical + performance monitoring with conservative, business-tuned thresholds minimizes false alarms while ensuring timely detection and response to concept drift.
Unlock 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.