Skip to content
Tech Interview Prep
Technical interview guide

Machine Learning in Computational Biology

Where ML is actually applied in genomics and drug discovery, and the specific data challenges (class imbalance, batch effects, limited labels) that make biological ML harder than typical tabular or image tasks.

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

Scope: scikit-learn 1.9 cross-validation, pipeline, evaluation and calibration guidance; DeepVariant, AlphaFold and Enformer source work; TRIPOD+AI, PROBAST+AI, Model Cards and Datasheets guidance reviewed 2026-09-04.

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-2

Design and defend a biological ML workflow for prediction target.

Answer

Clarify, then answer. A "prediction target" in biological ML is five decisions glued together - who, when, what outcome, over what horizon, driving which action - and any one left implicit silently changes the question. I'll fix a concrete one and defend it.

Assumptions: adult ICU, EHR-derived data, and the clinical job is to trigger a nephrology review before injury deepens. Prediction unit: one ICU stay, scored hourly. Target: P(KDIGO stage 2+ acute kidney injury within the next 48 h), using only data timestamped at or before the scoring hour. Time zero: ICU admission. Outcome: KDIGO stage 2+ - creatinine at or above 2.0x baseline, or creatinine at or above 4.0 mg/dL, or urine output below 0.5 mL/kg/h for 12 h or more. Baseline: lowest creatinine in the 7 days before ICU admission. Action: a positive prompts a nurse to re-check creatinine and fluid balance within 4 h. The model orders nothing.

elementdecisiondefended because
unitICU stay-hourmatches the hourly floor decision
populationage 18+, no chronic dialysis, first ICU staydialysis patients cannot express the creatinine endpoint
time zeroICU admissionunambiguous and charted
outcomeKDIGO stage 2+reproducible from two routine streams, creatinine and urine output
horizon48 henough lead time for a fluid and medication review
actionre-check within 4 hno action, no reason to build it

Alternatives I rejected: a 12 h horizon buys too little time to act; 7 days lets labels absorb unrelated physiology; admission-only static scoring misses the trajectory; and stage 1 as the endpoint is mostly transient, largely reversible creatinine bumps that would flood the same alerting capacity with lower-acuity events.

Worked trace of the label. Baseline 0.9 mg/dL. Creatinine at t=0 is 1.1 (ratio 1.22 - no); t=12 is 1.4 (1.56 - stage 1); t=30 is 1.9 (2.11 - stage 2, event). Event time 30 h sits inside the 48 h window, so the stay is positive. The same patient discharged at t=10 h with no further creatinine gives an unknown label, not a negative one - that is censoring, not a negative example.

Why the numbers force the design. At a 4% event rate across 12,000 ICU stays, sensitivity 0.75 and specificity 0.80 gives TP = 360, FP = 2304, precision = 360/2664 = 13.5%. Roughly seven of eight alerts are false. That is the price of a 48 h horizon; shortening the horizon raises prevalence and precision but buys less time to act, which is exactly the trade you make when you set the target.

Failure modes and how each is detected.

  • Post-outcome features: a creatinine drawn at t=35 h because the clinician already suspected AKI leaks into the t=24 h feature vector. Assert max(feature timestamp) <= scoring time on every row; leakage shows as AUROC dropping more than 0.1 once that assert is on.
  • Proxy label: billing ICD codes for AKI assigned at discharge instead of KDIGO labs. Cross-tab the code against the KDIGO label and read the kappa; a low kappa means you trained on a different target.
  • Ambiguous time zero: ICU admission versus hospital admission shifts the whole window by hours. Pin one and log it per row.
  • Target mismatch: training on "AKI at any point" while deploying as a 48 h warning. Label horizon and deployment horizon must be identical.
  • Selection bias: MIMIC-IV is one US academic centre, and stays with no creatinine measurement get dropped, which is informative missingness. Re-validate on eICU-CRD.
  • Out of scope: paediatrics, chronic dialysis, and ward patients. Name them and refuse to score them.

Validation: train on 2008-2016, test on 2017-2019 as a temporal split, and report precision at a fixed recall rather than AUROC alone.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

Design and defend a biological ML workflow for class imbalance.

Answer

I'd start by asking what a miss costs. In a clinical variant classifier, a false negative means a missed diagnosis; a false positive means an unnecessary confirmatory test. That asymmetry drives everything.

Assume binary classification: pathogenic vs benign variants, prevalence 0.5% (500 positives in 100,000 variants). Always predicting benign gives 99.5% accuracy, so accuracy is the first metric to throw out.

Pipeline:

  1. Split by patient and gene family, not random rows. Variants from the same patient share ancestry and sequencing batch; random splitting leaks. Use GroupShuffleSplit or stratified group k-fold.

  2. Resampling: I avoid SMOTE on genomic features. SMOTE interpolates between a pathogenic and benign variant, producing feature vectors like high conservation + high population allele frequency: biologically implausible. Instead, use class-weighted loss: scale_pos_weight = 199 in XGBoost 1.7, or focal loss (γ=2, α=0.25) for a neural net. If I must resample, I do it inside each training fold only, never before the split.

  3. Validation: 5-fold group cross-validation. Primary metric: PR-AUC, because ROC-AUC stays optimistic under imbalance. Secondary: recall at precision ≥ 0.5. Calibrate probabilities with isotonic regression on a held-out calibration fold.

  4. Threshold: choose on validation to hit 90% recall, then report the confusion matrix on the untouched test set.

Trade-offs:

| Method | Calibration effect | When to use | | SMOTE | shifts prior, needs recalibration | low-dim tabular, validated | | Class weights | preserves calibration if loss is proper | any weighted model | | Thresholding | no model change, needs validation set | post-hoc, model already good | | Focal loss | downweights easy negatives, may need tuning | deep learning, extreme imbalance |

Failure modes:

  • Resampling before split: synthetic positives leak into test, inflating PR-AUC. Detect by checking test prevalence equals true prevalence (0.5%).
  • Threshold optimized on test: overfits. Detect by comparing validation vs test threshold performance.
  • Rare subgroup ignored: overall recall 90% but 40% in an underrepresented ancestry group. Detect with subgroup confusion matrices.
  • No confidence intervals: PR-AUC 0.45 vs 0.48 may be noise. Use bootstrap (1,000 resamples).

Arithmetic: at 0.5% prevalence, a model with 90% recall and 10% false-positive rate gives TP=450, FP=9,950, precision=4.3%. That precision number is what a clinician needs to see.

Code for focal loss (PyTorch 2.0):

Python
import torch
import torch.nn.functional as F

def focal_loss(logits, targets, alpha=0.25, gamma=2.0):
    p = torch.sigmoid(logits)
    ce = F.binary_cross_entropy_with_logits(logits, targets, reduction='none')
    p_t = p * targets + (1 - p) * (1 - targets)
    loss = ce * ((1 - p_t) ** gamma)
    alpha_t = alpha * targets + (1 - alpha) * (1 - targets)
    return (alpha_t * loss).mean()

Defense: this workflow keeps the test set untouched, uses group splits to prevent leakage, and reports precision at the operating recall so the false-alarm burden is explicit. The main trade-off is that class weights can make the model overconfident on the minority class; isotonic calibration fixes that at the cost of a calibration fold.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-11

Design and defend a biological ML workflow for ROC and precision-recall.

Answer

Core answer (first 90 seconds). The decision here is which variants get sent for confirmatory testing, so the operating point is a cost-and-capacity problem, not an AUC problem. I state prevalence first, on a diagnostic gene panel roughly 2% of tested variants are pathogenic, because that one number decides whether ROC or PR is the honest curve. ROC's false-positive rate is prevalence-free; precision is not. Then I run the workflow: split by gene and by time, calibrate, report ROC AUC and AUPRC with bootstrap confidence intervals against named baselines, choose the threshold from the cost matrix and the lab's weekly capacity, and monitor prevalence and calibration monthly.

Workflow.

  1. Fix the decision and the cost matrix. A false negative is a missed diagnosis; a false positive is a confirmatory Sanger run at roughly $80 plus patient anxiety. Write both numbers down before touching a model.
  2. Split by gene family and by time. Homologous proteins leak across a random split and inflate AUPRC; use GroupKFold on gene ID, and hold out variants classified after your training cutoff.
  3. Fit, then calibrate with Platt scaling or isotonic regression (sklearn.calibration.CalibratedClassifierCV, scikit-learn 1.4). Report expected calibration error; target ECE < 0.05.
  4. Score with roc_auc_score and average_precision_score. Do not trapezoid the PR curve: scikit-learn's docs warn that linear interpolation between PR points is too optimistic; average precision is the step-wise estimator. Bootstrap 1,000 resamples for 95% CIs, and use DeLong's test for paired ROC AUC comparisons.
  5. Pick the threshold from the cost matrix and capacity, not from the curve's elbow.
  6. Monitor monthly: score-distribution PSI, positive rate, and PPV audited against chart review.

Worked arithmetic. 100,000 variants, 2% prevalence: 2,000 pathogenic, 98,000 benign. At a threshold giving 90% sensitivity and 95% specificity: TP = 1,800, FP = 0.05 × 98,000 = 4,900, FN = 200. Precision = 1,800 / 6,700 = 26.9%, against a prevalence baseline of 2%: a 13× lift, with ROC AUC around 0.95. Now deploy at 0.5% prevalence with the same TPR and FPR: TP = 450, FP = 4,975, precision = 8.3%. ROC AUC is unchanged; precision fell 3.2×. If the lab confirms 500 variants a week, finding 450 pathogenic calls at 8.3% precision needs 5,425 positives, eleven weeks of capacity, so the threshold has to rise.

Failure modes and detection.

FailureMechanismDetection
Prevalence shiftPrecision scales with prevalence; ROC does notMonthly positive-rate and PPV audit; PSI > 0.2 triggers retrain
Case-control trainingBalanced sampling makes precision wildly optimistic at 2% deploymentRecalibrate on a prevalence-representative holdout; check Brier score
Homology leakageSame protein family in train and testGroup split by gene; AUPRC drop when you switch splits
Interpolation artifactTrapezoidal PR AUC overstates performanceCompare average_precision_score to auc(precision_recall_curve)
AUC hiding the operating pointHigh AUC, unusable thresholdReport precision, recall and counts at the deployed threshold

Trade-offs. ROC is the right curve for ranking and for comparing models across cohorts with different prevalence; PR is the right curve for the deployed decision. If the cost of a false negative is 100× a false positive, you accept low precision and high recall, but only if capacity absorbs the confirmations. When it cannot, raise the threshold and state the recall you gave up.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9

In extreme class imbalance settings like virtual screening hit identification (e.g., 1 active per 10,000 inactives), how do you choose loss functions and ranking metrics to avoid deceptive evaluation?

Answer

In high-throughput virtual screening where active hit rates are 0.01% (1 in 10,000), standard metrics and standard cross-entropy loss produce deceptive models. ROC-AUC is misleading because the false positive rate (FPR = FP / (FP + TN)) is dominated by the colossal TN denominator; a model can score an ROC-AUC > 0.95 while flooding the top 500 compounds tested in the wet lab with zero genuine hits.

Metric Selection

  1. Early Enrichment & Retrieval: In discovery, wet-lab assay capacity is bounded (e.g., screening 50 to 500 candidates). Evaluate using BEDROC (Boltzmann-Enhanced Discrimination of ROC) or Enrichment Factor at top $k%$ (EF@k%), rather than global ROC-AUC: $$\text{EF@k%} = \frac{\text{Hits in top } k%}{\text{Total compounds in top } k%} \times \frac{\text{Total compounds in library}}{\text{Total hits in library}}$$ A model with high global PR-AUC that places all true hits between ranks 2,000 and 3,000 yields EF@0.1% = 0, failing the assay campaign.
  2. Precision-Recall Area (PR-AUC / Average Precision): Unlike ROC-AUC, PR-AUC baseline equals the prevalence ($10^{-4}$). An AP of 0.15 represents a 1,500x enrichment over random.
  3. Top-k Precision / Hit Count at $N$: Measure exact positive yield at wet-lab plate budget (e.g., Precision@100, Precision@384).

Loss Function Strategy

Standard Binary Cross-Entropy (BCE) gradients are swamped by easy inactives. Three mechanisms address this:

  1. Asymmetric/Focal Loss: Modulate standard cross-entropy with a focusing factor $\gamma \ge 2$ and balancing factor $\alpha$: $$\mathcal{L}_{\text{focal}} = -\alpha_t (1 - p_t)^\gamma \log(p_t)$$ This dynamically down-weights well-classified inactives ($p_t \approx 1$), allowing gradients from rare hits to dominate backpropagation.
  2. Ranking & Contrastive Losses: Pairwise ranking losses (e.g., Margin Ranking Loss, InfoNCE) explicitly optimize $f(x_{\text{active}}) - f(x_{\text{inactive}}) > m$, training the network on relative ordering rather than uncalibrated classification probabilities.
  3. Hard Negative Mining: Sample inactive negatives dynamically from near-misses (e.g., high chemical similarity to hits but experimentally validated as inactive) rather than random decoys.

Metric vs. Operational Reality

Evaluation MetricMathematical MechanismOperational Vulnerability at 1:10,000 Imbalance
ROC-AUCIntegral of TPR vs. FPR across all thresholdsFalse security: 10,000 false positives still yield FPR $\approx 0.01$, showing ROC-AUC $> 0.95$ while top ranks contain zero actives.
PR-AUC (Average Precision)Precision weighted by recall increments across full curveHides rank displacement within the wet-lab purchase/testing threshold (e.g., compounds ranked 500–5,000).
BEDROC / EF@1%Exponentially weights ranks using parameter $\alpha$, concentrating score on top-ranked compoundsSensitive to parameter $\alpha$ choice; can overfit to a single active cluster without diversity constraints.
Precision@NTrue positives divided by assay capacity $N$High variance when test set active count $N_{\text{pos}} < 10$.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

Design and defend a biological ML workflow for threshold selection.

Answer

I'd start by clarifying the decision. In a biological ML setting, say predicting sepsis from EHR data, the threshold isn't a hyperparameter you tune for accuracy. It's a clinical decision rule. So the workflow is: define the decision and its costs, calibrate the model, use decision curve analysis on development data to pick a threshold, freeze it, then evaluate on a held-out test set with subgroup analysis and an abstention zone. Finally, monitor in production.

The default 0.5 assumes equal misclassification costs and balanced classes. In biology, prevalence is often low, say 1% for a rare cancer, and missing a case is far worse than a false alarm. If a false negative costs 100 times a false positive, the optimal threshold on a calibrated probability is C_FP/(C_FP+C_FN) = 1/101 ≈ 0.01. So you'd flag 1% risk as positive. That's a concrete number.

Alternatives: you could use a fixed threshold like 0.5, but that's rarely defensible. You could use cost-sensitive learning, but that changes the model, not just the threshold. Decision curve analysis is better because it incorporates prevalence and preferences without retraining. But it requires calibrated probabilities. If your model isn't calibrated, you can use rank-based thresholds, but then you need to map to costs via a separate calibration step.

The workflow steps: First, define the decision and costs. What is a false negative worth? What is a false positive worth? Second, calibrate the model. Use CalibratedClassifierCV with method='isotonic' or 'sigmoid' from scikit-learn. Check calibration with a calibration plot and Brier score. Third, compute net benefit across thresholds on development data. The net benefit formula is:

Python
import numpy as np

def net_benefit(y_true, y_prob, threshold):
    y_pred = (y_prob >= threshold).astype(int)
    tp = np.sum((y_pred == 1) & (y_true == 1))
    fp = np.sum((y_pred == 1) & (y_true == 0))
    n = len(y_true)
    return tp/n - fp/n * (threshold/(1-threshold))

This is the standard formula from Vickers and Elkin (2006). Checked against Python 3.10 and NumPy 1.24.

Suppose a development set of 1,000 patients, 10% prevalence. We compute net benefit at different thresholds:

ThresholdTPFPNet benefit
0.1952000.073
0.280900.0575
0.365500.0436
0.455300.035
0.550200.03

The maximum net benefit is at 0.1, but if capacity limits you to 100 alerts per day, you might choose 0.2. So the threshold is not just statistical; it's operational.

Fourth, freeze the threshold before test. If you select on test, you overfit. For example, trying 100 thresholds on 1,000 test patients can inflate net benefit by about 0.02. Detect by comparing development and test net benefit; if test is much higher, suspicious.

Fifth, evaluate on test with subgroup analysis and abstention. On test, net benefit overall is 0.05. In patients over 65, it's 0.02. That's a red flag. You might need a different threshold for that subgroup or an abstention zone. Allow abstention when probability is between 0.4 and 0.6. That's 20% of patients. Refer to human. Reduces errors.

Failure modes: Test-set optimization. Detect by comparing development and test net benefit. Capacity overload, if threshold too low, too many alerts. Detect by monitoring alert volume and clinician override rate. Undertreatment: threshold too high, miss cases. Detect by auditing false negatives. Prevalence drift, if prevalence shifts from 10% to 5%, a fixed threshold on an uncalibrated score becomes wrong. Detect by monitoring prevalence and recalibrating. Group-specific harm: threshold may perform differently across subgroups. Detect by subgroup analysis. Uncalibrated probability: threshold on probability is meaningless. Detect by calibration plot and Brier score. Threshold changed silently: detect by version control and logging.

Finally, monitor in production. Track prevalence, calibration, alert volume, override rate, and subgroup performance. If prevalence drops to 5%, recalibrate and re-evaluate threshold.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

Design and defend a biological ML workflow for probability calibration.

Answer

I'd design calibration as a separate stage after training, with its own data and metrics. Assume a binary variant pathogenicity classifier that outputs a score. Deployment prevalence may differ from training. I have a calibration set of at least 200 events per class if possible.

Core answer: Split data by time or gene family into train, calibration, test. Fit model on train. On calibration set, compute reliability diagram with 15 quantile bins, ECE, Brier, log loss, calibration slope and intercept. Choose calibrator: Platt scaling if calibration set has 200+ events per class and scores are roughly sigmoid; temperature scaling if the model is a neural net and I have logits; isotonic only if I have >1000 events and the reliability diagram shows non-sigmoid miscalibration. Fit calibrator on calibration set, evaluate on test. Deploy with monitoring of ECE and calibration slope on rolling windows. Never calibrate on training data or on case-control data without prevalence adjustment.

Why calibrator leaks: if calibration set shares patients or batches with training, the model has memorized those examples, so its scores are overconfident but correct on that set. A calibrator fitted there learns to sharpen further; on new data it's wrong. Sparse bins: ECE with 15 bins on 200 samples gives ~13 per bin; a bin with 5 samples can show 0 or 1 observed frequency, so ECE variance is huge. Use quantile bins or at least 200 samples per bin. Prevalence shift: if training prevalence is 50% and deployment is 5%, the odds shift is (0.05/0.95)/(0.5/0.5)=0.0526, log-odds shift = ln(0.0526) = -2.94. So model logits need a -2.94 offset; without it, predicted probabilities are inflated.

Table comparing calibrators:

CalibratorParametersSample sizeAssumptionWhen to use
Platt (sigmoid)2100-200 events/classSigmoid miscalibrationSmall calibration set, neural net or SVM
IsotonicNon-parametric>1000 eventsMonotonicLarge calibration set, non-sigmoid
Temperature150-100 eventsLogits, ranking preservedDeep nets, small calibration set

Code for ECE (Python 3.11, numpy):

Python
import numpy as np

def ece(y_true, y_prob, n_bins=15):
    bins = np.linspace(0.0, 1.0, n_bins + 1)
    bin_ids = np.digitize(y_prob, bins[1:-1])
    ece = 0.0
    for b in range(n_bins):
        mask = bin_ids == b
        if mask.sum() == 0:
            continue
        acc = y_true[mask].mean()
        conf = y_prob[mask].mean()
        ece += (mask.sum() / len(y_true)) * abs(acc - conf)
    return ece

Failure modes with detection and cost:

  • Leakage: calibration set from same batch as training. Detection: calibration slope >1.5 or ECE on test >0.15 while calibration ECE <0.02. Cost: false high-risk alerts.
  • Sparse bins: ECE on 100 samples with 15 bins. Detection: wide confidence intervals on bin frequencies; use 5 bins or quantile bins. Cost: wrong calibrator choice.
  • Prevalence shift: case-control training. Detection: calibration intercept deviates from 0; predicted mean probability differs from observed prevalence. Cost: threshold 0.5 flags 40% instead of 10%.
  • Temporal drift: model trained on 2015-2018, deployed 2024. Detection: rolling ECE >0.1 for two windows of 1000 predictions. Cost: missed diagnoses.

Defence: I'd defend this because it separates ranking from reliability, uses proper scores, and monitors the right thing. If the decision only uses ranking (AUC) and not absolute probabilities, I would not calibrate. If calibration set is too small, I'd use temperature scaling or collect more data. If prevalence shift is extreme, I'd reweight or recalibrate on deployment-like data.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

Design and defend a biological ML workflow for calibration shift.

Answer

What I'd say first. Assume a frozen binary risk model, say 30-day sepsis onset, trained at site A and now alerting at site B, with a threshold that triggers a blood culture. Calibration shift means the map from the model's linear predictor to observed risk has moved: prevalence, case-mix, measurement, or the feature–outcome relationship changed. AUROC is invariant to any monotone transform of the score, so it can hold at 0.78 while every predicted probability is wrong. Monitor and defend calibration, not AUROC.

The workflow.

  1. Prospective shadow window. Score every admission for 8 weeks without acting on it. Retrospective recalibration on data the model already influenced is circular.
  2. Fit weak calibration. Logistic regression of observed outcome on the frozen linear predictor: logit(p) = a + b·LP. a is calibration-in-the-large (a < 0 → risks over-predicted); b is the calibration slope (b < 1 → predictions too extreme). Report both with 95% CIs, a loess calibration plot, and the Brier score.
  3. Decide by rule. CI for b contains 1 and |a| < 0.2 → leave it. a shifted, b ≈ 1 → intercept-only update. b's CI excludes 1 → full logistic recalibration. AUROC dropped > 0.05 absolute → retrain; recalibration cannot fix a broken ranking.
  4. Recalibrate under governance. Fit on months 1–3, evaluate on months 4–6. Version the calibration artifact, pre-register the protocol, clinical owner signs off.
  5. Re-check discrimination and decision utility. AUROC before/after, and net benefit at the operating threshold.
Python
# Python 3.11, statsmodels 0.14
X = sm.add_constant(lp)          # lp = frozen model's linear predictor
fit = sm.Logit(y, X).fit(disp=0)
a, b = fit.params                # calibration intercept, slope
lo, hi = fit.conf_int()[1]       # 95% CI on the slope

Worked example (hypothetical). Site B, 4,500 admissions, 180 events (4%). Mean predicted risk 7.5%. Fit: a = −0.67 (95% CI −0.79 to −0.55), b = 0.82 (0.70–0.94). Both CIs exclude their nulls, so full logistic recalibration.

At a 0.20 alert threshold:

flaggedevents caughtnet benefit
before560100100/4500 − 460/4500 × 0.25 = −0.003
after2909090/4500 − 200/4500 × 0.25 = +0.009
treat all4500180180/4500 − 4320/4500 × 0.25 = −0.20
treat none000

Before recalibration the model is worse than treating nobody at that threshold; after, it beats treat-none. That is the defence: recalibration changed who crosses the threshold, not the ranking.

Trade-offs. Intercept-only is one parameter, needs few events, and is safe when only prevalence moved. Full logistic recalibration fixes spread but needs roughly 200 events for a usable slope CI (Riley et al.'s external-validation criteria); below that the CI is too wide to act on. Isotonic regression is flexible but overfits small local samples and destroys monotone interpretability. Retraining can recover discrimination but needs a fresh development cohort and full re-validation: weeks, not days. Recalibration is the wrong call when AUROC has fallen materially, or when the shift is in the feature–outcome relationship: a slope fit will absorb concept shift and hide it.

Failure modes and how I'd catch them.

  • Small local sample. Compute the slope CI before deciding; if it spans 0.7–1.3, you are recalibrating on noise.
  • Delayed labels. Sepsis labels land 3–7 days post-admission, so a monthly report is stale. Track label latency and completeness; use a rolling window.
  • Feedback loop. Alerts trigger cultures and antibiotics, changing who gets labelled. Compare calibration in alerted vs non-alerted strata; divergence means the label is contaminated.
  • Outcome definition mismatch. Site B bills, site A used Sepsis-3: the "shift" is in the label. Audit 50 charts.
  • Recalibration hiding feature shift. Run per-feature drift tests (KS, PSI) alongside the calibration fit; a slope that absorbs a changed relationship looks like a fix.
  • Stale baseline. Re-baseline on a fixed cadence and version it.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

Design and defend a biological ML workflow for uncertainty.

Answer

Assume the model triages missense variants for wet-lab follow-up: labels come from conflicting clinical assertions, the test set spans gene families unseen in training, and a missed pathogenic variant costs more than an extra assay. Under those assumptions I'd ship a deep ensemble wrapped in split conformal prediction, abstain on wide prediction sets and out-of-distribution inputs, and monitor coverage per gene family.

Why that stack and not a Bayesian neural net: conformal gives a finite-sample, distribution-free coverage guarantee. With a calibration set of n variants and α = 0.1, the prediction set contains the true label at least 90% of the time, and it wraps any base model, so I don't pay MCMC or a bespoke variational approximation. The ensemble supplies the epistemic signal conformal doesn't: disagreement across members flags inputs where the model has no basis to answer.

Concretely: five models, different seeds and architectures (a GNN over the protein structure, a CNN over the sequence), trained on gene-disjoint folds. Calibration on 2,000 held-out variants. Score is 1 − p(true class); the conformal quantile is the ⌈(n+1)(1−α)⌉/n empirical quantile.

Python
import numpy as np
alpha = 0.1
n = len(cal_scores)                      # 2000
q = np.quantile(cal_scores,
                np.ceil((n + 1) * (1 - alpha)) / n,
                method="higher")         # 1801/2000 = 0.9005
# test set: {k : 1 - p_k(x) <= q}

Trace: with q = 0.62, a variant scored p_pathogenic = 0.55 (score 0.45) and p_benign = 0.30 (score 0.70) yields the set {pathogenic}. Call it. A variant at p_pathogenic = 0.45 (0.55) and p_benign = 0.40 (0.60) yields {pathogenic, benign}: set size 2, abstain and send to assay. Set size is the uncertainty the downstream team acts on.

methodgivescostfails when
MC dropoutcheap epistemic approx1 model, 30 passesdropout rate is arbitrary; no coverage guarantee
deep ensemble (5)epistemic via disagreement5× trainingmembers share data → correlated errors
split conformalfinite-sample coverageheld-out calibration setexchangeability breaks under shift
GPcalibrated posteriorO(n³), ~10⁴ pointskernel misspecified

When not to use it: if the decision is a single threshold and you only need a point estimate, conformal sets are overhead. If the label is continuous (binding affinity, say), swap classification conformal for conformalized quantile regression and report intervals, not sets.

Failure modes and how I'd catch them:

  • Coverage collapse under shift. Exchangeability fails when test genes are new. Monitor empirical coverage per gene family on the ~200 variants assayed each month; a family below 0.85 triggers weighted conformal (reweight calibration scores by density ratio) or retraining.
  • Ensemble members not independent. Compute pairwise prediction correlation; above 0.95 the ensemble is one model in five costumes: compare its variance to a single model's MC dropout variance to confirm.
  • Uncalibrated confidence. Reliability diagram and ECE; ECE above 0.05 on the calibration set means recalibrate before shipping.
  • Abstention that never fires. Track abstention rate; 0% means the set-size threshold is wrong, not that the model is certain.

The defense in one line: conformal buys the coverage guarantee, the ensemble buys the shift signal, and the monitoring loop is what keeps both honest after deployment.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

Design and defend a biological ML workflow for missing data.

Answer

Core answer (first 90 seconds)

I'd refuse to pick an imputation method until I know why each value is missing, because in biological data missingness is rarely random. A protein absent from a mass-spec run is absent because it sits below the limit of detection: missingness is a function of the value itself (MNAR, left-censored). A lab test absent from an EHR is absent because a clinician chose not to order it: missingness is a function of suspicion, which may be a function of the target. Neither is MCAR, and mean-imputing either one bakes a false value into the model.

The workflow I'd defend: (1) classify missingness per feature as assay-driven, workflow-driven, or random; (2) split train/val/test before any imputation; (3) fit the imputer inside the training fold only, so it's structurally impossible to leak; (4) decide per feature whether a missingness indicator is computable at inference time; (5) evaluate at the missingness rates production actually shows, and define an abstention rule.

Why the split matters: a worked trace

Suppose a feature has 1000 rows, 800 train and 200 test, and the test cohort is a later, sicker batch whose observed values run higher. Train observed mean is 5.0; test observed mean is 7.0. Impute globally and every training row with a missing value gets (800×5.0 + 200×7.0)/1000 = 5.4 instead of 5.0. The training rows now carry 0.4 units of information about the test cohort. That's the leak, and it's invisible unless you look for it.

The fix is a pipeline, not discipline:

Python
# scikit-learn 1.4
from sklearn.experimental import enable_iterative_imputer  # noqa: F401
from sklearn.impute import IterativeImputer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline

pipe = Pipeline([
    ("impute", IterativeImputer(max_iter=10, random_state=0)),
    ("clf", LogisticRegression(max_iter=1000)),
])
pipe.fit(X_train, y_train)      # imputer statistics come from X_train only
pipe.score(X_test, y_test)      # test rows are transformed, never fitted

IterativeImputer is still behind the experimental import in scikit-learn 1.4; that's a real constraint, not a typo.

Choosing the imputer by mechanism

  • Left-censored (below LOD): substituting LOD/√2 is the common proteomics convention, but it's a point estimate for a censored value. A censored (Tobit-style) likelihood is more honest if you can afford it.
  • MAR given observed covariates: IterativeImputer (MICE) is reasonable, but it can emit physically impossible values. Negative concentrations, values above the assay ceiling.
  • Tree models: XGBoost and LightGBM handle NaN natively by learning a default direction. Cheap, no leakage risk, but that default direction is learned from training missingness, which is exactly the shortcut you're trying to avoid.

Failure modes and how I'd detect them

failurewhat it looks likedetection
future informationimputer or scaler fit on all rowsfit inside pipeline; compare CV score to a deliberately leaky run: a large gap means leakage
site-specific shortcutmodel routes on "missing at site B"leave-one-site-out CV; per-site AUC collapses
complete-case selectiondropping any row with a NaNcompare age/severity distributions of complete vs incomplete rows
impossible imputed biologynegative concentration, above ceilingrange-check imputed values against assay bounds, count violations
no abstentionconfident output from 90% missing featuresbin test accuracy and confidence by missing fraction
global imputationone imputer across sites/assaysper-site residual distributions diverge

Defence and when not to

Missingness indicators are free information if they're computable at inference. "Test not ordered" is: you know it wasn't ordered. "Sample failed QC" often isn't, because a failed sample doesn't reach the model. Include the indicator only when the deployment path can produce it.

I'd drop a feature rather than impute it once missingness exceeds roughly half the rows: at that point the imputed values dominate the column and the model is fitting the imputer. And I'd set an abstention threshold, if more than some fraction of the top-importance features are missing for a given patient, return "insufficient data" rather than a probability.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-7

How do you handle noisy labels, assay variance, and discordant replicate measurements when training models on high-throughput screening (HTS) or functional genomics data?

Answer

High-throughput biological screens (e.g., cell viability, CRISPR screens, fluorescence binding assays) do not yield ground-truth ground states; they produce noisy, heteroskedastic surrogate measurements. Binarizing continuous readouts using arbitrary thresholds (like 50% inhibition) destroys assay variance and mislabels compounds near the boundary, while simple arithmetic averaging over replicates masks well-to-well artifacts.

My approach operates in three stages: continuous target modeling, replicate concordance weighting, and grouped split hygiene.

1. Reject Premature Binarization: Model Continuous Affinities with Heteroskedastic Loss

Instead of thresholding into active/inactive classes, retain continuous endpoints (e.g., $pIC_{50}$ or normalized fold-change log2 counts). Train models to predict both the target mean $\hat{y}_i$ and the assay variance $\hat{\sigma}_i^2$ using a Gaussian negative log-likelihood (heteroskedastic loss):

$$\mathcal{L}(\theta) = \frac{1}{2N} \sum_{i=1}^N \left( \frac{(y_i - \hat{y}_i)^2}{\hat{\sigma}_i^2} + \ln(\hat{\sigma}_i^2) \right)$$

If the objective strictly requires binary triage, generate calibrated posterior probabilities rather than hard labels by fitting isotonic regression or sigmoid calibration (CalibratedClassifierCV) on out-of-fold validation sets, avoiding deterministic labels on borderline readouts.

2. Quality Control & Replicate Aggregation

Biological replicates provide a direct measure of measurement noise. Do not collapse replicates before QC:

  • Concordance Filtering: Compute the intra-assay replicate standard deviation $\sigma_{rep}$ or Pearson/Spearman $r$ across replicates per plate/batch. Discard plate runs failing QC ($Z'\text{-factor} < 0.5$).
  • Sample Weighting by Replicate Agreement: Aggregate replicates via median or Huber M-estimators rather than the mean to suppress outlier wells (e.g., edge effects, dispensing bubbles). Pass the inverse replicate variance $w_i = 1 / (\sigma_{rep, i}^2 + \epsilon)$ as sample_weight into model training.
  • Multi-task Replicate Output: Alternatively, retain individual replicates as parallel prediction tasks sharing representation layers. High-concordance signals drive shared latent features, while uncorrelated noise stays in the task-specific heads.

3. Trace & Comparison: Handling Discordance

StrategyMechanismFailure ModeWhen to Use
Hard BinarizationCutoff at arbitrary threshold (e.g., $IC_{50} < 10,\mu M$)Label flipping near threshold; high false-positive rateNever for training; only as business rule downstream of calibrated probabilities
Median Aggregation + WeightingHuber/Median aggregation; $w_i = 1 / (\sigma_i^2 + \epsilon)$Over-weights under-sampled singular replicatesStandard HTS pipelines with 2–4 replicates per compound
Heteroskedastic HeadPredict $(\hat{\mu}, \hat{\sigma}^2)$ directlyModel exploits high variance as shortcut to minimize lossLarge-scale genomics (e.g., Enformer-style coverage/count data)
Soft Labels / Label SmoothingReplace $y \in {0, 1}$ with continuous empirical probabilityCan over-regularize confident extremesWhen assays report probabilistic readouts (e.g., hit confirmation rates)

4. Split Hygiene

Never split individual replicates between train and test sets. Ensure compound scaffolds, cell lines, or genomic loci are grouped entirely into train or test (GroupKFold), preventing the model from memorizing biological replicates of the same perturbation across folds.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

How do you detect and mitigate technical batch effects and plate artifacts in transcriptomic or imaging phenotypic screens without stripping true biological signal?

Answer

To remove technical batch effects and plate artifacts without erasing true biological variance, you must distinguish between confounder-aligned variance and independent biological signal through experimental design, explicit modeling, and group-aware cross-validation.

1. Detection: Finding Artifacts Before Modeling

Before training downstream models, quantify technical variation across three levels:

  • Spatial plate trends: Wells along plate edges often exhibit evaporative loss (edge effects), altering cellular morphology or fluorescence intensity. Compute well-level median profiles across non-treated negative controls (e.g., DMSO) and flag correlation between well coordinate $(r, c)$ and feature z-scores.
  • Batch clustering: Run PCA or UMAP on raw normalized read counts or CellProfiler morphology embeddings. Compute the silhouette score or k-nearest neighbor batch effect test (kBET) comparing clustering by batch_id / plate_id versus clustering by biological perturbation (e.g., compound, knock-down target). If the top 3 principal components correlate strongly ($R^2 > 0.30$) with plate run date or instrument ID rather than perturbation class, batch effects dominate.
  • Replicate concordance: Measure the cosine similarity or Pearson $r$ between biological replicates across different plates versus distinct biological treatments within the same plate. True biological signal demands higher intra-treatment inter-plate correlation than inter-treatment intra-plate correlation.

2. Mitigation Strategies and Trade-offs

Correction depends on whether you have randomized plate layouts and reliable reference controls:

Correction LevelTechniqueMechanismTrade-off / Risk
Spatial (Within-Plate)2D B-spline / Median PolishFits smooth spatial surface $y_{rc} = ext{plate_median} + ext{row}_r + ext{col}_c + ext{resid}$ across control wellsCan over-correct if active compounds are clustered geometrically on the plate.
Linear ParametricControl-based Normalization / ComBatCenters and scales by negative controls ($z = (x - ar{x}{\text{ctrl}}) / s{\text{ctrl}}$) or uses empirical Bayes location-scale modelFails when biological condition is confounded with batch (e.g., all disease samples on Plate A).
Non-linear LatentConditional VAE (e.g., scVI) / Adversarial DebiasingModels count dispersion with plate indicator as conditioning covariate; or adds gradient reversal layer penalizing plate predictionHigh parameter count; can suppress true biological variation if perturbation classes are unevenly distributed across plates.

3. Pipeline Implementation and Preventing Leakage

A common failure is computing normalization parameters globally across the entire dataset, which leaks validation batch distributions into training. Any transformation fitted on control wells or batch parameters must be structured within a scikit-learn pipeline or fit strictly on training partitions:

Python
import numpy as np
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.model_selection import LeaveOneGroupOut

class PlateControlStandardizer(BaseEstimator, TransformerMixin):
    """Standardize features using negative control wells (DMSO) per plate."""
    def __init__(self, plate_col=0, is_ctrl_col=1):
        self.plate_col = plate_col
        self.is_ctrl_col = is_ctrl_col
        self.plate_stats_ = {}

    def fit(self, X, y=None):
        # Compute mean and std strictly on negative controls within each plate
        plates = np.unique(X[:, self.plate_col])
        for p in plates:
            p_mask = (X[:, self.plate_col] == p)
            ctrl_mask = p_mask & (X[:, self.is_ctrl_col] == 1)
            feat_data = X[ctrl_mask, 2:].astype(float)
            self.plate_stats_[p] = {
                'mean': np.nanmean(feat_data, axis=0),
                'std': np.nanstd(feat_data, axis=0) + 1e-6
            }
        return self

    def transform(self, X):
        X_out = np.empty((X.shape[0], X.shape[1] - 2), dtype=float)
        for i, row in enumerate(X):
            p = row[self.plate_col]
            stats = self.plate_stats_.get(p)
            feats = row[2:].astype(float)
            if stats:
                X_out[i] = (feats - stats['mean']) / stats['std']
            else:
                # Unseen plate at inference: fallback to global reference
                X_out[i] = feats
        return X_out

4. Validation Architecture

Never evaluate batch-corrected models using standard random k-fold cross-validation. Use LeaveOneGroupOut or GroupKFold grouped by plate_id or run_batch_id. If the test set consists of held-out batches and classification AUROC drops from 0.94 (random split) to 0.61 (plate-grouped split), the model was exploiting batch artifacts as shortcuts rather than learning phenotypic biology.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6

How do you evaluate and prevent batch effects when training representation learning models on single-cell RNA-seq (scRNA-seq) or multi-omics data?

Answer

Batch effects in single-cell and multi-omics assays are technical confounders introduced by sequencing chemistry, platform, reagent lot, library prep, or operator differences that correlate with target biology.

Core Mitigation Architecture

Preventing batch effects requires decoupling biological signal from technical acquisition metadata across model architecture, data preprocessing, and training objectives:

  1. Conditioned Latent Encoders: In variational models (such as scVI or scANVI architectures), feed the batch indicator $s \in {1, \dots, B}$ directly into the decoder $p(x \mid z, s)$ rather than the bottleneck $z$. The latent representation $z$ is forced to encode batch-invariant transcriptomic states while library size $l$ and batch confounders parametrize count distributions (e.g., negative binomial parameters $\mu_{s, g}, \theta_{s, g}$).
  2. Adversarial Latent Disentanglement: For unconditioned latent representations or multi-modal fusion, train a gradient reversal layer (GRL) or adversarial discriminator on $z$ minimizing mutual information $I(z; s)$. The latent encoder maximizes prediction of biological state while minimizing an adversary's ability to classify donor or run identity.
  3. Batch-Stratified Partitioning: Never split cells randomly across train/test splits. Use GroupKFold or LeaveOneGroupOut grouped strictly by donor or sequencing run to evaluate zero-shot generalization across unseen technical batches.
Python
# PyTorch GRL snippet for scRNA-seq batch-invariant representation
import torch
import torch.nn as nn
from torch.autograd import Function

class GradReverse(Function):
    @staticmethod
    def forward(ctx, x, alpha=1.0):
        ctx.alpha = alpha
        return x.view_as(x)

    @staticmethod
    def backward(ctx, grad_output):
        return grad_output.neg() * ctx.alpha, None

class BatchInvariantEncoder(nn.Module):
    def __init__(self, in_features=2000, latent_dim=32, num_batches=6):
        super().__init__()
        self.encoder = nn.Sequential(
            nn.Linear(in_features, 256), nn.BatchNorm1d(256), nn.ReLU(),
            nn.Linear(256, latent_dim)
        )
        self.batch_classifier = nn.Sequential(
            nn.Linear(latent_dim, 64), nn.ReLU(),
            nn.Linear(64, num_batches)
        )
    def forward(self, x, alpha=1.0):
        z = self.encoder(x)
        z_rev = GradReverse.apply(z, alpha)
        batch_logits = self.batch_classifier(z_rev)
        return z, batch_logits

Quantitative Evaluation Framework

Model evaluation must balance two competing objectives: technical batch mixing versus biological conservation. Optimizing one at the expense of the other leads to under-correction (clusters remain separated by batch) or over-correction (rare cell types or treatment conditions are collapsed).

MetricMetric TargetFormula / LogicDesired Production Range
kBET (k-nearest neighbor Batch Effect Test)Batch Mixing$\chi^2$-test comparing local neighborhood batch distribution against global prior for $k=30$Rejection rate $< 0.15$ (high acceptance)
Batch ASW (Average Silhouette Width)Batch Mixing$1 -\text{ASW}_{\text{batch}}
Cell Type ASWBiology ConservationClassic silhouette width across annotated labels: $(b_i - a_i)/\max(a_i, b_i)$$> 0.65$
Graph cLISI / iLISIBio & Batch BalanceLocal Inverse Simpson's Index on $k$-NN graph; effective number of labels in neighborhoodiLISI $\approx \text{Num Batches}$; cLISI $\approx 1.0$

Production Failure Modes & Detection

  • Over-Correction (Biological Erasure): When experimental treatments or rare lineages (e.g., $0.1%$ circulating dendritic subsets) exist only in one batch, adversarial or integration loss forces them to overlap with abundant controls. Detection: Verify cLISI and cell-type preservation metrics drop sharply even as kBET rejection rate improves.
  • Confounded Experimental Design: If Case is assayed strictly in Batch A and Control in Batch B, separating biological variance from technical variance is mathematically ill-posed. Address upstream via balanced multiplexing (cell hashing across pools) before model training.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-1

Design and defend a biological ML workflow for biological independence.

Answer

The decision unit is the donor, not the cell. Split by donor ID, aggregate cell-level predictions to donor-level scores, and report donor-level confidence intervals. Cells from one donor share genetics, environment, batch, and preparation; treating them as independent inflates precision by roughly the square root of cells per donor. With 5,000 cells per donor, a cell-level CI is about 70× narrower than the donor-level CI. That is the arithmetic that decides the design.

Assume a single-cell RNA-seq study: 20 donors, 5,000 cells each, 100,000 cells total, binary outcome (responder vs non-responder). Hypothetical but typical. Use scikit-learn 1.4 GroupKFold with n_splits=5 on donor IDs. Preprocess with scanpy 1.10. Aggregate test predictions per donor by mean predicted probability, then compute donor-level AUC.

Python
import numpy as np
from sklearn.model_selection import GroupKFold
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import roc_auc_score

# X: cells x genes, y: cell-level labels, donors: donor ID per cell
gkf = GroupKFold(n_splits=5)
donor_aucs = []
for train_idx, test_idx in gkf.split(X, y, groups=donors):
    clf = RandomForestClassifier(n_estimators=100, random_state=0)
    clf.fit(X[train_idx], y[train_idx])
    test_donors = donors[test_idx]
    preds = clf.predict_proba(X[test_idx])[:, 1]
    donor_preds = {d: preds[test_donors == d].mean() for d in np.unique(test_donors)}
    donor_true = {d: y[test_idx][test_donors == d][0] for d in np.unique(test_donors)}
    donor_aucs.append(roc_auc_score(list(donor_true.values()), list(donor_preds.values())))
print(f"Donor-level AUC: {np.mean(donor_aucs):.3f} +/- {np.std(donor_aucs):.3f}")

On a 20-donor dataset this prints donor-level AUC 0.72 ± 0.08; a cell-level random split on the same data prints 0.94 ± 0.01. The gap is donor leakage, not signal.

StrategyIndependenceTraining donorsWhen to use
Cell-level randomFails20Never for donor-level claims
Donor-level k-foldPasses16≥10 donors
Leave-one-donor-outPasses19<10 donors, expensive
Family-level splitPassesvariesRelated donors

Trade-offs: donor-level splits reduce effective training size. With 20 donors, 5-fold gives 16 training donors and 4 test donors. If the effect size is small, power is low. With 5 donors, leave-one-donor-out gives 4 training donors: often too few to train a deep model. Then you either collect more donors or switch to within-donor prediction (e.g., predict cell type from cells within the same donor), where biological independence is not the goal. Deciding criteria: number of donors, within-donor correlation (ICC), and whether the claim is donor-level or cell-level.

Failure modes and detection:

  • Pseudoreplication: test cells share a donor with training cells. Detect by checking donor overlap between train and test. Symptom: test accuracy 0.95 vs donor-level 0.65. Cost: false discovery, wasted wet-lab validation.
  • Donor leakage: same as pseudoreplication but via preprocessing (e.g., batch correction fit on all cells). Detect by refitting preprocessing inside each fold. Symptom: fold AUC drops from 0.90 to 0.70.
  • Plate leakage: donors span plates, and plate ID predicts label. Detect by checking plate overlap between train and test. Symptom: plate ID alone gives AUC 0.80.
  • Cell-type imbalance: donor-level aggregation hides rare cell-type failures. Detect by per-cell-type donor-level AUC. Symptom: overall donor AUC 0.75, rare cell type 0.55.
  • Family overlap: related donors in train and test. Detect by checking family overlap. Symptom: test AUC 0.85 vs family-level 0.60.
  • Confidence intervals based on cells: CI width 0.01 vs donor-level 0.15. Detect by comparing cell-level and donor-level bootstrap CIs. Cost: overconfident decisions.

What would change the decision: if donors < 10, use leave-one-donor-out and report that power is limited. If within-donor correlation is low (ICC < 0.1), a cell-level split may be acceptable, but you must still report donor counts and donor-level CIs.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-3

Design and defend a biological ML workflow for homology leakage.

Answer

The 90-second answer

Leakage here means a test sequence the model can score by memorizing a near-identical training sequence. So the split is by homology cluster, not by sequence, and the identity threshold is fixed before you look at test performance.

Assumptions: labeled sequences, MMseqs2 available, and the deployment target is remote homology (new folds), so I cluster at 30% identity / 80% coverage. If you only care about new variants of known families, use 50–70%.

Step 1: cluster everything together

Shell
mmseqs easy-cluster all.fasta clusters tmp --min-seq-id 0.3 -c 0.8 --cov-mode 1

--cov-mode 1 requires 80% coverage of the representative (the target). Output clusters_cluster.tsv has two columns: representative, member.

Step 2: split by cluster, then verify the guarantee

MMseqs2's default clustering is greedy set-cover: each member is within threshold of its representative, but two members of one cluster can be far from each other, and, the part that bites, a test sequence can be within 30% of a train sequence while landing in a different cluster. Splitting by cluster is necessary but not sufficient. Close it two ways: cluster with connected components (--cluster-mode 1), which makes clusters transitive so no cross-cluster pair is above threshold; and after splitting, run an all-vs-all search between train and test and move any test sequence with a hit above threshold into train. I do both: connected components for the split, the search as an assertion.

Python
import pandas as pd
from sklearn.model_selection import GroupShuffleSplit

clusters = pd.read_csv('clusters_cluster.tsv', sep='\t', header=None,
                       names=['rep', 'member'])
labels = pd.read_csv('labels.tsv', sep='\t', names=['member', 'label'])
df = clusters.merge(labels, on='member')

gss = GroupShuffleSplit(n_splits=1, test_size=0.2, random_state=0)
tr, te = next(gss.split(df, groups=df['rep']))
train, test = df.iloc[tr], df.iloc[te]
assert set(train['rep']).isdisjoint(set(test['rep']))

Caveat: test_size counts sequences, so one 5,000-member family can dominate the test set. For a balanced split, dedupe to one row per rep, split clusters, then map members back.

Shell
mmseqs easy-search test.fasta train.fasta hits.m8 tmp --min-seq-id 0.3 -c 0.8 --cov-mode 1

Any line in hits.m8 is a leak; move that sequence to train and re-split.

Step 3: the leakage your own clustering can't see

  • Pretrained encoders. ESM-2 was trained on UniRef50; ProtBert on BFD plus UniRef100. Search your test set against that corpus at the same 30%/80% and drop hits. Confirm the corpus against the model card for your exact checkpoint.
  • Labels propagated by homology. If GO terms or Pfam labels were transferred from homologs, a test label can encode a training label. Keep only experimentally verified test labels, or split by annotation source.
  • Species. Random sequence splits leak orthologs (often >80% identity) across species. If cross-species generalization is the goal, split by species or taxonomic group.
  • Domains. A multi-domain protein can share one domain with train and be novel in another. Cluster per Pfam domain, or use Foldseek on domain structures, if domain novelty is what you're testing.

Trade-offs

Novelty testedIdentityCoverageTool
New variants50–70%80%MMseqs2, CD-HIT
Remote homologs20–30%80%MMseqs2
New fold<20%—Foldseek (structures)

Lower threshold = harder, more honest test; too low and you may have no positives left. CD-HIT is faster but tuned for ≥40% identity: below that use MMseqs2. Foldseek needs structures, so it applies only where you have them.

Failure modes and detection

  • Threshold picked after seeing results. Pre-register it. If test AUC drops when you lower the threshold, you had leakage.
  • Silent contamination from a pretrained model. Detect by searching test against the model's training corpus, not by trusting the model card alone.
  • A cluster split that isn't a homology split (greedy set-cover). Detect with the train-vs-test search; the assert only checks cluster IDs, not sequence identity.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-4

Design and defend a biological ML workflow for genomic window leakage.

Answer

Core answer

The split has to mirror deployment, and the grouping key is the deployment unit. Ask first: will the model score new individuals at known loci, new loci, or new chromosomes/species? Then:

  • New individuals → group by individual (donor/sample ID).
  • New loci → group by locus or gene, and buffer the boundary.
  • New chromosomes or clades → hold out whole chromosomes (leave-one-chromosome-out) or whole clades.

Random window splits are only defensible when deployment is interpolation within the same loci, and even then they overstate performance. State that assumption out loud; it is the thing the interviewer is testing.

Why leakage happens

Three mechanisms, all spatial:

  1. Overlap. Adjacent windows share bases, so a test window can be a near-copy of a train window.
  2. Linkage disequilibrium. Common human variants stay correlated (r² > 0.2) out to roughly 10–100 kb, and to ~1 Mb in some regions. A test window's features are then proxies for a train window's.
  3. Label autocorrelation. Conservation, regulatory activity and constraint scores are smooth over similar scales, so nearby labels are not independent.

A random split therefore measures memorization of locus context, not generalization.

Design with numbers

Assume human germline, GRCh38 primary assembly, 1 kb windows, a regulatory-activity predictor.

  • Buffer ≥ LD decay. Default 100 kb; use 1 Mb for fine-mapped eQTL or long-range regulatory targets. Prune with plink --indep-pairwise 50 5 0.2.
  • Grouping. sklearn.model_selection.GroupKFold with groups=chromosome (cross-chromosome) or groups=gene_id (cross-locus).
  • Boundary enforcement. Buffer the test set and assert zero overlap with train:
Shell
bedtools slop -i test_windows.bed -g hg38.genome -b 100000 > test_buffered.bed
bedtools intersect -a train_windows.bed -b test_buffered.bed -wa | wc -l   # must be 0
Python
from sklearn.model_selection import GroupKFold
gkf = GroupKFold(n_splits=5)
for tr, te in gkf.split(X, y, groups=groups):  # groups = chromosome or gene_id
    ...

Defence: criteria and cost

SplitValid when deployment isCostLeakage risk
Random windowsSame-locus interpolationCheapestHigh unless buffered
Blocked + bufferNew lociBuffer tuningLow if buffer ≥ LD decay
Leave-one-chromosome-outNew chromosomesDiscards ~1/23 per foldLowest, conservative
Group by individualNew donorsNeeds many donorsLow

Report both random-split and blocked-split metrics; the gap is your leakage estimate. If the gap is small, the cheaper split suffices. If it is large, the random number was never real.

Failure modes and detection

  • Boundary overlap: detect with the bedtools intersect count above; must be 0.
  • LD leakage: compute max r² across train/test pairs inside the buffer; if > 0.2, widen it.
  • Chromosome-specific distribution: per-chromosome metric spread; chrX, chrY and MHC are usual outliers.
  • Paralogs / segmental duplications: self-chain alignments or liftOver; exclude or group them.
  • Assembly patches: alt contigs, decoys, unplaced scaffolds; keep primary assembly only.
  • Test chromosomes used for tuning: audit hyperparameter logs; hold out a second chromosome set to confirm.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-5

Design and defend a biological ML workflow for nested model selection.

Answer

Assumptions I'd state first. 240 samples from 60 donors, 4 samples per donor, binary label at 30% positive, metric AUROC, and n small enough that fold variance dominates any model difference. Donor is the grouping unit because samples from one donor are not independent.

The workflow. Group by donor. Outer loop is GroupKFold(n_splits=5); inside each outer training fold, GridSearchCV runs GroupKFold(n_splits=4) over the hyperparameter grid. Every transform lives in a Pipeline, so the scaler is fit on inner-training rows only. Report the mean and standard deviation of the five outer AUROC values. Keep a separate external cohort frozen until the end for one confirmation look.

Why the split bounds the bias. Choosing the max over K configs selects the config whose noise happened to be favourable on the folds you looked at. Expected optimism grows with K and with per-config fold variance. Nested CV removes it because the outer fold is never used to pick anything: selection happens on inner folds, scoring happens on data the selection never touched. Illustratively, if each config's inner-fold AUROC has std 0.04 and you take the max of 4 configs, the winner sits roughly 0.6σ ≈ 0.024 above the true mean: that gap is what a single non-nested CV would report as skill.

Python
# scikit-learn 1.4
from sklearn.model_selection import GroupKFold, GridSearchCV
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score
import numpy as np

pipe = Pipeline([("scale", StandardScaler()),
                 ("clf", LogisticRegression(max_iter=1000))])
grid = {"clf__C": [0.01, 0.1, 1.0, 10.0]}

outer = GroupKFold(n_splits=5)
inner = GroupKFold(n_splits=4)
scores = []
for tr, te in outer.split(X, y, groups=donor):
    gs = GridSearchCV(pipe, grid, scoring="roc_auc", cv=inner)
    gs.fit(X[tr], y[tr], groups=donor[tr])
    scores.append(roc_auc_score(y[te], gs.predict_proba(X[te])[:, 1]))
print(np.mean(scores), np.std(scores))

Trace. 5 outer folds × (4 inner folds × 4 configs) = 80 fits, plus 5 refits of the winning config on each full outer-training set = 85 fits. predict_proba on the outer test fold uses the refit model, so the reported score never saw the test rows.

Alternatives and when to pick them.

ApproachCostWhen it decides
Nested CV85 fitsSmall n, real group structure, you must report an unbiased estimate
Repeated CV + single holdout~20 fitsLarge n, cheap refits, holdout big enough to trust
Single split1 fitNever for a claim; only for a smoke test

If donors number fewer than ~10, 5 outer folds leave too few groups per fold and the outer std swamps the signal: switch to LeaveOneGroupOut and report per-donor scores instead of a mean.

Failure modes and how I'd catch them. A scaler or feature-selection step fit outside the pipeline leaks label information; detect it by shuffling labels: a leaky pipeline still scores above 0.5. Reusing outer results to pick the final model reintroduces the bias; detect it by checking that the chosen config is fixed before the outer loop runs. Too few groups shows up as outer std comparable to the mean. Unstable folds show up as one outer fold far from the rest. Calling the nested score prospective performance is wrong: it is still retrospective; only the frozen external cohort is prospective.

What would change the decision. If the external cohort is large and representative, a single holdout plus repeated CV is defensible and cheaper. If donors are few or the label is imbalanced within donors, use StratifiedGroupKFold and keep the nested loop regardless of cost.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

Design and defend a biological ML workflow for external validation.

Answer

Core answer (first 90 seconds). External validation asks one question: does a frozen model, applied to data it never influenced, still discriminate and calibrate in the target setting? My answer is a three-step discipline (freeze, predeclare, run once) with calibration as the primary endpoint, not AUROC.

Assumptions I'd state up front: a binary outcome (say 30-day mortality), EHR-derived predictors, a model already developed and internally validated, and one genuinely independent site available. If the "external" cohort is a random split of the development data, none of this applies: that is internal validation.

Freeze before you look. Hash the model artifact and pin the serving container by digest, not tag:

Python
# Python 3.11
import hashlib
digest = hashlib.sha256(open("model.pkl", "rb").read()).hexdigest()
# deploy as registry.example.org/mortality@sha256:<digest>, never :latest

Freeze the preprocessing too (imputation medians, category encodings, normalization statistics) because those were fit on the development cohort and carry its distribution. And freeze the decision threshold. This matters statistically: the threshold is a fitted parameter. If you pick the threshold that maximizes F1 on the external set, you have used the external set to make a modeling decision, and the reported performance is optimistic by construction. The threshold should come from the development data or a predeclared clinical rule (e.g. the cut that catches 90% of true sepsis alerts).

Predeclare the analysis. Primary metric, subgroups, exclusions, and the recalibration plan, written before the first run, and reported against TRIPOD+AI (2024). Riley et al. (2021) put the minimum at 100 events for external validation and 200 when calibration is the target; the calibration slope's standard error scales roughly as 1/√n_events, so at 100 events the 95% CI on the slope is about ±0.2: wide enough that you cannot distinguish a slope of 0.8 from 1.0.

Run once and report everything. Compute calibration slope and intercept by regressing the outcome on the logit of the predicted risk:

Python
# Python 3.11, statsmodels 0.14
import numpy as np, statsmodels.api as sm
lp = np.log(p / (1 - p))
m = sm.Logit(y, sm.add_constant(lp)).fit(disp=0)
intercept, slope = m.params          # ideal 0 and 1

Worked example (hypothetical figures): development AUROC 0.84, calibration slope 1.00. External site: AUROC 0.79, slope 0.72, intercept +0.31. Read it as: slope < 1 means the predictions are too extreme. The model is overfit to development; intercept > 0 means observed events exceed predicted risk, so the model under-calls risk at this site. AUROC barely moved, which is exactly why calibration is the primary endpoint: AUROC is rank-based and survives miscalibration, but the admit/discharge decision depends on the absolute number.

Trade-offs. Three options, decided by the numbers: if slope ≈ 1 and intercept ≠ 0, update the intercept only (recalibration-in-the-large). If slope < 1, fit a recalibration slope on a predeclared slice. If AUROC also drops materially, the predictors do not transport: refit with site-specific features. Do not silently recalibrate and then report the original numbers.

When not to use it. If the external site shares the same lab vendor, analyzer version and patient population, you are testing reproducibility, not transport: say so rather than claiming external validity. If the cohort has fewer than 100 events, report the validation as underpowered rather than as a pass.

Failure modes and detection.

failuredetection signalcost
duplicate patients across cohortsoverlap on hashed (site, MRN) or admission IDinflated AUROC; the model has seen the patient
shared lab pipelinesame analyzer + assay version in both cohortstransport claim is false
tuning on the external setmore than one evaluation run logged against the frozen setexternal set becomes a validation set; results optimistic
outcome definition drift30-day mortality from discharge date vs. death registrylabel noise; intercept shifts
tiny subgroups< 100 events in the subgroupCI too wide to act on

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

Design and defend a biological ML workflow for subgroup evaluation.

Answer

Core answer (first 60–120 seconds). Assume a binary classifier trained on retrospective multi-site biological data: e.g., predicting pathologic complete response from tumor RNA-seq plus clinical variables: with patient IDs, site, assay batch, and a clinical decision threshold. I would not report a single overall AUC. I predefine subgroups with clinical stakeholders, split by patient and site, require minimum cell sizes, report per-subgroup discrimination and calibration with confidence intervals, and pre-specify intersectional and acquisition analyses. If a subgroup has too few events, I report “insufficient evidence,” not a point estimate. I defend this because overall metrics can hide a subgroup where the model is miscalibrated or below clinical utility.

Workflow.

  1. Predefine groups before looking at test data: receptor status, sex, age band, self-reported race/ethnicity as a social variable, genetic ancestry principal components, site/scanner, RNA-seq batch. Never use race as a genetic proxy.
  2. Split with GroupKFold by patient and site; use leave-one-site-out for external validation. Random splits leak patient and site signal.
  3. Minimum cell size: require at least 20 positives and 20 negatives per subgroup for a point estimate; for calibration slope, at least 100 samples and 20 events. Below that, report “insufficient evidence” and the CI.
  4. Metrics: AUROC, sensitivity at the fixed clinical threshold, specificity, PPV, calibration slope, intercept, Brier score, expected calibration error. Bootstrap 1,000 resamples stratified by subgroup for 95% CIs.
  5. Intersectional: only pre-specified two-way cells (e.g., sex × site) with n ≥ 50 per cell; otherwise use hierarchical shrinkage or label exploratory.
  6. Acquisition: include site/scanner as a covariate or stratify; test site × prediction interaction.
  7. Multiplicity: pre-register subgroups; Benjamini–Hochberg FDR at q = 0.10; report effect sizes and CIs, not just p-values.
  8. Privacy: suppress cells with n < 11 before sharing subgroup tables.

Artefacts. Group-aware split and subgroup AUROC:

Python
from sklearn.model_selection import GroupKFold
from sklearn.metrics import roc_auc_score
import numpy as np

gkf = GroupKFold(n_splits=5)
for train_idx, test_idx in gkf.split(X, y, groups):  # groups = patient_id or site_id
    model.fit(X[train_idx], y[train_idx])
    y_prob = model.predict_proba(X[test_idx])[:, 1]
    for g in np.unique(groups[test_idx]):
        mask = groups[test_idx] == g
        if mask.sum() >= 20 and len(np.unique(y[test_idx][mask])) == 2:
            print(g, mask.sum(), roc_auc_score(y[test_idx][mask], y_prob[mask]))

Hypothetical held-out results:

Subgroupn (pos/neg)AUROC (95% CI)Sensitivity at 0.5Calibration slopeBrier
Overall2000 (400/1600)0.91 (0.89–0.93)0.820.950.12
Site A1200 (240/960)0.93 (0.90–0.95)0.851.020.10
Site B300 (60/240)0.72 (0.63–0.80)0.610.580.21
ER+/HER2−800 (160/640)0.88 (0.84–0.91)0.780.910.13
ER−/HER2+1200 (240/960)0.92 (0.89–0.94)0.840.970.11

Overall AUC 0.91 hides site B. At the same sensitivity 0.80 and specificity 0.90, PPV falls from 67% to 30% when prevalence drops from 20% to 5%: (0.8×0.2)/(0.8×0.2+0.1×0.8)=0.667; (0.8×0.05)/(0.8×0.05+0.1×0.95)=0.296. That is why a single threshold is unstable across subgroups.

Trade-offs. Stratified reporting increases variance and privacy risk. If a subgroup has n < 20, the CI is too wide to act on; partial pooling or overall drift monitoring is better. Do not stratify a subgroup that is neither actionable nor large enough to estimate.

Failure modes and detection.

  • Tiny-cell overclaim: AUC 0.95 on n = 8. Detect: flag n < 20; report CI and “insufficient evidence.”
  • Race as biology: race used as a feature or genetic proxy. Detect: audit features; replace with ancestry PCs or social determinants.
  • Multiple subgroup fishing: testing 50 subgroups until one is significant. Detect: pre-registration and FDR; report number of tests.
  • Privacy exposure: small cell counts in shared tables. Detect: n < 11 suppression.
  • Unstable thresholds: threshold chosen on test or overall. Detect: nested CV; report threshold sensitivity.
  • Disparities dismissed by overall average: overall AUC 0.91 hides site B 0.72. Detect: report minimum subgroup AUC and calibration slope.

Defense against the objection “overall AUC is 0.91, why worry?” Because site B has AUROC 0.72 and calibration slope 0.58: predicted risk 0.30 versus observed 0.18. I would not deploy until site B is recalibrated or excluded, and I would monitor subgroup calibration after deployment.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

Design and defend a biological ML workflow for feature attribution.

Answer

Assume the model is a sequence-to-function predictor: an Enformer-style chromatin-track model, a splice predictor, or a protein fitness model, and the target is one scalar or one track. Attribution is model dependence under a baseline, not causality. I'd defend this workflow.

1. Fix the estimand and baseline. For a variant effect, the baseline is the reference allele; for global importance, it is a dinucleotide-shuffled sequence preserving GC and CpG, not uniform random. That choice changes rankings because the model is nonlinear: a GC-rich motif gets inflated attribution against uniform background. State the baseline in every report.

2. Pick the method by model and input.

methodcostuse whendo not use when
In silico mutagenesis (ISM)O(L×A) forward passesDNA, black-box model, L ≤ ~1 kblong sequences or combinatorial epistasis
Integrated GradientsO(steps) forward+backwarddifferentiable model on continuous embeddings, e.g. protein language modelone-hot DNA with a straight-line path: fractional bases are invalid sequences
TreeSHAPexact O(TLD²) for treesk-mer or epigenomic tabular featuressequence models
DeepLIFT / DeepSHAPfast, reference-baseddifferentiable model with a defensible referencereference choice dominates the result

For DNA, ISM is the default because it stays on valid sequences. L=1000 bp, A=4 gives 4000 forward passes per sequence. At 2 ms per pass that is 8 s per sequence; 10,000 sequences is about 22 hours. Integrated Gradients at 32 steps is 64 passes, about 0.13 s per sequence, or 21 minutes for 10,000: cheaper, but only if the path is valid.

3. Run and aggregate. For ISM, mutate each position to the other three bases, score Δoutput, and take the max absolute effect per position. For protein IG, use 32 steps from a masked or evolutionary background. Then group correlated features: DNA motifs are redundant, so sum attribution within a motif or cluster positions by TF motif similarity. Otherwise credit splits across redundant bases and no single position looks important.

4. Sanity-check before believing it. Randomize model weights: attributions should collapse to noise. Randomize labels: no consistent signal. Compare ISM against IG or DeepLIFT; if Spearman ρ < 0.8, inspect the disagreement. For IG, increase steps from 16 to 32 and require ρ > 0.95. If top attributed positions do not change the prediction when mutated, the attribution is unfaithful.

5. Validate causally. Take the top 10 positions by ISM and test them in an MPRA, CRISPRi, or deep mutational scan. Attribution alone cannot support a causal claim; perturbation can.

Failure modes I would gate in production:

failuredetectioncost if missed
background choicererun with dinucleotide shuffle, compare rank correlationwrong motif ranking
shortcut explanationchromosome holdout, random-sequence controlsfalse wet-lab follow-up
impossible sequencefilter N's and out-of-distribution inputsmeaningless attribution
sign misreadcompare ISM sign to effect directionwrong hypothesis
attribution instabilityseed and step-size convergenceunreproducible result
training leakagetrain/test chromosome overlap checkinflated performance
sensitive feature proxyprivacy review of attributed genotypespatient re-identification

Defense: no single method is faithful everywhere. ISM is exact for single-base effects and model-agnostic, but expensive and blind to epistasis. IG is cheap but baseline-dependent and invalid on one-hot DNA. SHAP is exact for trees but not for sequence models. The workflow reports method, baseline, convergence, and causal validation, so a reviewer can reproduce the claim and see where it could fail.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

Design and defend a biological ML workflow for sequence models.

Answer

Core answer

Assume the task is sequence → label (enzyme function, fitness, or binding), that labels are inherited by homology, and that deployment will see sequences novel relative to training. If any of those is false, the split changes.

The answer: split by homology cluster at the identity threshold that matches deployment novelty, audit the test set against the pretrained model's training data, and report accuracy stratified by distance to the nearest training sequence. A random split measures memorization, not generalization.

Why cluster first

Two proteins at 40% identity usually share an ancestor and usually share function. A random split puts near-duplicates in both train and test, so the model wins by retrieving a neighbor. Cluster, then assign whole clusters to train or test: never split a cluster.

With MMseqs2 (flags below are stable across recent releases):

Shell
mmseqs easy-cluster all.fasta clu tmp --min-seq-id 0.3 -c 0.8 --cov-mode 1

30% identity is the twilight-zone boundary where sequence homology detection starts to fail; below it, alignment-based label transfer is unreliable. If deployment will see remote homologs, hold out at 30%. If it will see close variants of known proteins, hold out at 50–70%, or split by mutation position instead.

Overlap audit

ESM-2 was trained on UniRef50. If your test set overlaps it, you are measuring recall of training data.

Shell
mmseqs easy-search test.fasta uniref50.fasta hits.m8 tmp --min-seq-id 0.5 -c 0.8

Illustrative: 2,000 test sequences, 340 hit UniRef50 at ≥50% identity → 17% potentially memorized. Report metrics with and without those.

Stratify

Bucket test sequences by max identity to any training sequence: <25%, 25–40%, 40–70%, >70%. Report per-bucket accuracy. If it is 0.95 in the >70% bucket and 0.55 below 25%, the headline number is a lie.

Alternatives, and when to use them

  • Random split: fine when deployment is itself a set of close homologs. Predicting fitness of point mutants of one enzyme you already have. Then split by position, not by cluster.
  • Temporal split: train on pre-2020 deposits, test on 2021+. Required when the deployment stream is new depositions; databases grow, so a 2023 snapshot cannot fairly evaluate a 2018 model.
  • Fold-level split (CATH/SCOP, or Foldseek structural clustering): use when function follows structure more than sequence, e.g. remote homologs below 20% identity.

Failure modes

  • Remote homology leakage: a test protein is a distant homolog of a training protein. Detected by the identity-bucket table.
  • Multidomain overlap: two proteins share one domain. Cluster on Pfam domains, not full chains.
  • Threshold hindsight: tuning the identity cutoff after seeing test results. Pre-register it.
  • Family imbalance: one Pfam family is 40% of the test set. Report macro-average per family, not micro.
  • No truly novel test: if the median test sequence has a 60% identity neighbor in train, you have no novelty claim. Report the distribution.

Model selection and monitoring

Frozen ESM-2 embeddings plus logistic regression is the baseline to beat; fine-tuning wins only with roughly 10k+ labelled examples in the target family. In production, log embedding distance to the training manifold and alert on drift: a drifting test set is the same leakage problem arriving late.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

Design and defend a biological ML workflow for genomics models.

Answer

What I say first (60–120 seconds). I'd pin the task and the deployment unit before designing anything, because the split follows from them. Assumptions I'd state out loud: human genome on GRCh38, supervised prediction of a per-bin signal (regulatory tracks, variant effect, expression), and the deployment unit is a chromosome or locus the model has never seen. If deployment is instead a new assay on the same cell line, the split changes and I'd say so. The workflow then has five stages: data and splits, baseline, model, evaluation, monitoring.

Splits. Random splits leak in genomics because neighbouring windows share LD, regulatory context and often the same label. Three options:

splitleakagewhen it's right
randomhigh: same locus in train and testnever, for a transfer claim
locus-blocked (e.g. 1 Mb blocks)low within block, moderate acrossdeployment is a new locus on a known chromosome
leave-chromosome-outlowestdeployment is a new chromosome

I'd default to leave-chromosome-out and name the chromosomes up front. Enformer (Avsec et al., 2021) held out chr8 and chr21 for test and chr20 for validation; reusing that convention makes results comparable to published numbers.

Buffer. With 196,608 bp input windows and 128 bp output bins, a window whose centre sits 100 kb from the held-out boundary still reads held-out bases. So the exclusion zone is the held-out chromosome plus one input length (196,608 bp) on each side, and I drop any training window that overlaps it. Without that buffer a model can score well by copying the boundary.

Individuals. If the data has donors (GTEx, 1000 Genomes), keep every donor in exactly one split. The same donor in train and test inflates correlation by memorising donor-specific expression rather than sequence.

Baseline. Run a cheap baseline first: k-mer counts plus ridge regression, or elastic net on PWM scores. If a CNN doesn't beat it by a margin I can defend, the complexity isn't paying for itself.

Metrics. Per-track Pearson r for continuous tracks; AUPRC for peaks, always reported against the prevalence baseline. TF peaks cover roughly 1–2% of bins, so AUPRC 0.05 can be at chance while AUROC reads 0.95. Prune correlated variants at r² > 0.2 within 1 Mb (PLINK --indep-pairwise 50 5 0.2) and report both the pruned and full sets.

Failure modes and how I'd detect them. (1) Test chromosome used in feature engineering: normalisation stats or PCA computed genome-wide; detect by rebuilding features from train only and re-scoring. (2) Assembly mismatch: hg19 coordinates against GRCh38; detect with a liftover round-trip and check what fraction of variants return to their original position. (3) Sparse positives: AUROC hides it, so print prevalence next to every AUPRC. (4) Distribution shift at deployment: track per-chromosome residuals and input drift, and re-run the held-out benchmark on every release.

When chromosome holdout is the wrong choice. If deployment is imputing a missing assay on the same cell line, chromosome holdout overstates the difficulty and throws away data; use locus-blocked splits instead. The deciding criterion is whether the deployment unit is a new chromosome or a new locus on a chromosome already seen.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

Design and defend a biological ML workflow for data documentation.

Answer

Assumptions I'd state first: human genomic data under controlled access (dbGaP/EGA), labels pulled from clinical records, model retrained quarterly, and a data steward plus a pipeline owner who can be paged. If any of those is false the workflow shrinks, but the shape holds.

The answer: documentation is not a PDF written once. It is a versioned, machine-checkable manifest that travels with the data and is validated in CI. Three layers, each with an owner and a trigger:

  1. Ingest (data steward). Every raw sample gets an immutable accession (BioSample SAMN…), assay, instrument, reference build (GRCh38), and a consent term from GA4GH DUO (GRU, HMB, DS-…). Nothing enters without a DUO term.
  2. Build (pipeline owner). Features are produced by a DVC stage; dvc.lock pins the md5 of every input and output, so lineage from raw sample to feature matrix is a hash chain, not a narrative.
  3. Split and label (ML lead). Splits are patient-level, seeded, and written to splits.csv with participant_id, split, seed. Labels record their source and version (pathology_review_v3, not label).

All three collapse into one JSON-LD file, Croissant or RO-Crate, that CI reads. The manifest is the artefact; the prose datasheet (Gebru et al., arXiv:1803.09010) is generated from it for reviewers.

Triggers that bump the dataset version: new cohort, label source change, consent change, or an upstream source hash mismatch. Any bump re-runs the CI checks and flags the model for retraining.

The check that earns its keep: patient leakage:

Python
import pandas as pd
splits = pd.read_csv("splits.csv")  # participant_id, split
splits["participant_id"] = splits["participant_id"].str[:12]  # TCGA barcode prefix
train = set(splits.loc[splits.split == "train", "participant_id"])
test  = set(splits.loc[splits.split == "test",  "participant_id"])
overlap = train & test
assert not overlap, f"patient leakage: {len(overlap)} participants in both splits"

Trace: the barcode prefix collapses multiple samples per donor to one ID; the intersection is empty on a clean split and non-empty the moment someone splits by sample instead of patient. That single assertion catches the most common biological-ML leak.

Trade-offs. A full datasheet per cohort costs hours of steward time and rots fast; a bare manifest is cheap but under-documents. The criterion that decides: document any field that can change a split, a permitted use, or a label. Automate the rest. Fields that cannot flip a decision (instrument serial, freezer ID) go in the raw archive, not the manifest. The alternative to a manifest-plus-generated-datasheet is a hand-written datasheet reviewed quarterly; it drifts because nothing fails when it is wrong. The manifest wins because CI fails.

Failure modes and how each is detected:

FailureDetection
Patient leakageParticipant-overlap assertion above
Duplicate subjectsGenotype concordance > 0.9 or repeated participant barcode
Consent driftDUO term vs intended use checked at access time
Mutable public sourcePinned md5 mismatch on re-pull
Label provenance lossMissing label_source/label_version field
Undocumented exclusionsExclusion reason code absent from manifest

Closing criterion: if a field cannot be checked by CI or read by a downstream consumer, it is documentation theatre. Ship the manifest, generate the prose, and let the assertion, not the reviewer, decide when the dataset is safe to train on.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

Design and defend a biological ML workflow for model documentation.

Answer

What a strong candidate says first

Assume a regulated clinical model: a sepsis-risk classifier retrained quarterly and surfaced in the EHR order set. The workflow is four gates, and the card is a build artifact, not a document: CI generates it, hashes it, and binds it to the exact model binary and dataset commit. At deploy, the admission controller recomputes the model hash and refuses to ship on mismatch. That binding is what makes the rest of the card defensible.

GateArtifactBlocking check
1 DataDatasheet (Gebru et al., 2018) plus a DVC commit recording assay version, reference build (GRCh38), and site/plate batchpatient-level split; no train/eval pair above 0.95 embedding cosine
2 ModelModel Card (Mitchell et al., 2019) sections, aligned to TRIPOD+AIevery eval slice with n ≥ 200 reports AUROC with a 95% CI; ECE ≤ 0.05
3 ReleaseSigned manifest: SHA-256 of the ONNX file, dataset version, threshold, calibration methodSigstore signature and SLSA provenance present
4 Post-marketDrift and subgroup monitor; card revision ticketPSI > 0.2 on any monitored feature, or slice AUROC drop > 0.05 vs. release

The manifest is small enough to generate in CI:

Python
import hashlib, json
manifest = {
    "model_sha256": hashlib.sha256(open("sepsis.onnx", "rb").read()).hexdigest(),
    "dataset_version": "dvc://data/sepsis-v3.2",
    "threshold": 0.37,
    "calibration": "isotonic, fit on holdout n=4812",
    "slices": ["age_band", "sex", "site", "race_ethnicity"],
}
card_hash = hashlib.sha256(json.dumps(manifest, sort_keys=True).encode()).hexdigest()

sort_keys=True makes the digest reproducible; the registry stores card_hash next to model_sha256, and a nightly job fails the build when they diverge.

Why the threshold and prevalence must be on the card

A card reporting AUROC 0.90 without the operating point and the prevalence it was measured at is not usable. At 1% prevalence, sensitivity 0.90, specificity 0.95, per 10,000 patients: 100 diseased → 90 TP, 10 FN; 9,900 healthy → 495 FP, 9,405 TN. PPV = 90/585 = 15.4%, NPV = 9,405/9,415 = 99.9%. The same model at 20% prevalence has PPV 81.8%. A clinician reading "AUROC 0.90" over-trusts the alert; the card has to state the prevalence band the metric was computed in and the calibration method, because isotonic regression fitted on 4,812 holdout cases does not transfer to a site with a different case mix.

Defending the design against the alternatives

  • Static PDF card vs. machine-readable manifest: the PDF is easier to write and is what most vendors ship, but it cannot be diffed or gated. The manifest costs one CI job and makes staleness detectable.
  • Full re-approval per retrain vs. a Predetermined Change Control Plan: FDA's PCCP guidance (final, December 2024) lets you pre-authorize bounded updates. Retraining on new data within a stated distribution, threshold moves within a stated range, so the quarterly retrain does not need a new submission. The card's update-policy section is where those bounds are written down.
  • Card authored by the modeling team vs. an independent documentation owner: the modeling team writes faster but tends to omit the slices it did not evaluate. Independent sign-off is the control that catches omitted subgroups.

The risk-management file (ISO 14971) and the software lifecycle records (IEC 62304) reference the same card hash, so a design-history audit resolves to one artifact.

Failure modes and how each is detected

  • Stale card: card_hash ≠ model_sha256 in the registry; nightly job fails.
  • Scope creep: the model fires on an excluded indication; detected by PSI > 0.2 on the age band plus an order-set audit of the firing indication.
  • Benchmark contamination: train/eval near-duplicates; detected by MinHash or embedding cosine > 0.95 between splits, reported as an overlap count on the card.
  • Omitted subgroup failure: aggregate-only metrics; detected by the gate in row 2. Any slice with n ≥ 200 and AUROC < 0.75, or a CI wider than 0.15, blocks release.
  • Unverifiable artifact: no signature or provenance; the admission controller rejects unsigned artifacts.
  • Unsupported clinical claim: the card says "risk stratification", marketing says "detects sepsis"; a lint diffs the intended-use section against the label text.

For EU deployment the same manifest feeds the Annex IV technical documentation; high-risk obligations phase in from August 2026 for Annex III systems and August 2027 for AI embedded in regulated products such as medical devices.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

Design and defend a biological ML workflow for deployment monitoring.

Answer

Core answer (first 90 seconds)

Clarify before designing: what decision does the model drive, what is the label, how late does it arrive, and what does a false negative cost? I'll assume a targeted NGS panel model that scores each sample for MSI-high to triage confirmatory PCR: roughly 200 samples/week across 12 sites, labels from the orthogonal assay arriving 3–10 days later, and a false negative costing a missed immunotherapy eligibility.

The workflow has four layers, each with a named owner and a runbook: an input contract that rejects or flags before scoring, drift monitors on inputs and scores, outcome linkage on a lagged window, and an action policy that decides alert, abstain, recalibrate, retrain or roll back.

LayerMonitorThresholdAction
Input contractcoverage ≥100x, tumor fraction ≥10%, panel version in allowlistany failabstain, route to manual review
Score driftKS on score vs frozen reference, 4-week windowp<0.001 and KS>0.10page owner, check lot metadata
CalibrationECE on 30-day lagged labels, n≥200ECE>0.05 or slope outside 0.8–1.2recalibrate (isotonic on last 500 labels)
DiscriminationAUROC, 12-week rollingdrop >0.03 vs reference for 2 windowsretrain
SubgroupAUROC per site and ancestry group, n≥30 positivesdrop >0.05investigate, consider site threshold
Label pipelinemedian label lag, % model-positives with confirmatory resultlag>14d or coverage<95%freeze recalibration, audit ordering
Python
# Python 3.11, scipy 1.11
from scipy.stats import ks_2samp

def score_drift(ref, cur, alpha=0.001, ks_min=0.10):
    ks, p = ks_2samp(ref, cur)
    return {"ks": round(ks, 3), "p": p, "alert": bool(p < alpha and ks > ks_min)}

# ref = 2,000 scores from the frozen validation window
# cur = last 4 weeks of production scores (n ~ 800)

Why not just watch AUROC weekly? Because labels lag 3–10 days and the smallest site runs 3 samples/week: a 4-week window there holds ~2 positives at a 15% MSI rate, so no metric is estimable. Per-site AUROC therefore uses a 12-week window and only sites with ≥30 positives; smaller sites pool into a regional stratum. Input and score drift are the leading indicators; outcomes are the lagging confirmation. On alert budget: 40 monitors at alpha=0.05 would fire ~2 false alerts/week, so alpha=0.001 plus a two-consecutive-window rule cuts that to roughly one per 25 weeks.

Trade-offs. Recalibrate when ranking holds but the score scale moved (new reagent lot, prevalence shift): 500 labels, minutes, no new model. Retrain when AUROC drops >0.03 for two consecutive windows: needs ~1,000 labels and a fresh validation split. Abstain when input QC fails or the score sits in 0.35–0.65; that costs a manual review on ~5% of volume. Do not retrain on labels the model influenced: if triage changes who gets confirmatory testing, the label set is missing-not-at-random. Train only on protocol-mandated confirmatory results and track the confirmatory rate for model-positives, which should stay near 100%.

Failure modes and detection. A silent assay upgrade, reagent lot or panel version change, shifts feature medians; catch it with lot-stratified KS on five sentinel features and require a 30-sample bridging study before switching lots, or expect ~2 weeks of degraded AUROC before outcome labels catch up. Label delay makes calibration look healthy because it is scored against stale labels; track the label-arrival lag distribution and freeze recalibration when the median exceeds 14 days. Alert fatigue shows up as alert volume and acknowledgement rate: above 5 alerts/week or below 50% acknowledged, raise thresholds. Sensitive logging is prevented by logging hashed sample IDs and derived features only, with a PII regex scan in CI against the log schema. Drift without an action owner is caught by requiring a named owner per monitor row: an unassigned alert is itself an alert.

Rollback. Pin the previous model version. Roll back if AUROC drops >0.05 or the calibration slope leaves 0.8–1.2 within a 2-week window.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

Design and defend a biological ML workflow for reproducible governed operations.

Answer

What I'd say first (90 seconds). Pin the decision before the model: this classifier ranks missense variants for a clinical genetics review queue. A geneticist sees the top 20 per patient and decides. It never calls pathogenicity on its own. That one fact sets the bar: the decision is human-gated and reversible, so I spend on prospective validation and provenance, and skip real-time serving guarantees.

Assumptions I'd state out loud: ~12,000 labeled variants, labels from ClinVar at ≥2-star review status, batch nightly scoring, GRCh38, CLIA/CAP environment, one named model owner on the on-call rotation.

Why reproduction fails without pinning. It fails silently. Three mechanisms:

  1. Reference drift. Resolve transcripts against a newer Ensembl release and a few percent of variants map to a different consequence and score differently. Same VCF in, different score out, no exception raised.
  2. Split leakage. Regenerate the split each run and the same protein change can sit in train and test. Internal AUC reads 0.94; re-split by gene and it falls to 0.87. That 0.07 gap is the leak, not signal. (Illustrative figures.)
  3. Seed and class balance. Positives run about 1 in 10, so the negative draw dominates the loss; a different seed moves the operating threshold.

So the versioned artifact is the manifest, not the model file:

Python
# Python 3.11, pandas 2.2
import hashlib
def manifest(cfg):
    h = hashlib.sha256()
    for k in ("genome_build", "ensembl_release", "vcf_sha256",
              "split_sha256", "seed", "code_git_sha"):
        h.update(f"{k}={cfg[k]};".encode())
    return h.hexdigest()[:16]

Change ensembl_release from 110 to 111 and the digest changes: that is the point: a run is identified by its inputs, and a re-run that produces a different digest is a different experiment, not a reproduction.

Trade-offs. Three options, and the criterion is the cost of a false negative.

optioncostcatchesmisses
Container + hash pinninglow per run, slow to updatepreprocessing drift, leakagedistribution shift
Reproduce metrics within tolerancecheapgross breakagesilent drift inside tolerance
Prospective shadow runexpensive, weeksshift, calibration decaynothing structural

For a review queue where a miss delays a diagnosis, I take pinning plus a prospective shadow run, and reserve the tolerance path for cheap re-runs. I would not take tolerance-only: a 2-point AUC tolerance hides exactly the drift that matters.

Failure modes and how I'd detect them.

  • Leakage: assert no shared gene or protein change across splits; alert if re-split AUC drops more than 0.03.
  • Cohort drift: PSI on feature distributions weekly; alert above 0.2.
  • Nonreproducible preprocessing: re-run in a clean container and diff the feature-matrix hash.
  • Consent violation: block the pipeline when the data-use agreement tag does not match the cohort.
  • Subgroup harm: per-ancestry sensitivity; alert if the gap exceeds 5 points.
  • Uncalibrated threshold: reliability curve and Brier score each release.
  • No abstention: report the fraction of scores in the 0.4–0.6 band and route those to manual review.
  • No owner: the model card names the owner and the rollback trigger.

Closing logic. Ship when the manifest reproduces the metrics bit-for-bit, external and prospective checks hold, and a monitored rollback exists. Otherwise it stays a research artifact.

Curated: · Written: · Reviewed:

Difficulty: Hard