Leakage-Safe Binary Classifier Workflow: From EDA to Monitoring
Machine LearningModel answerLast updated
Design and implement an end-to-end binary classification workflow in Python, covering time-aware splits, imbalance, tuning, calibration, error analysis, explainability and production safeguards.
You are handed a labeled tabular dataset with a binary target and a timestamp column. Your job is to build, evaluate and document a classifier in Python so that the offline numbers you report would still hold up after deployment.
Walk through the following ten stages, giving code snippets and explaining the reasoning behind each design choice:
- Data exploration. Check missing values, outliers, possible target leakage, and how both the label rate and the feature distributions change over time.
- Splitting. Produce train, validation and test sets that respect time ordering and keep class proportions sensible, and describe a suitable cross-validation scheme for the training portion.
- Models. Build a solid, simple baseline and at least one stronger model.
- Imbalance. Explain how you would deal with a rare positive class (weighted loss, resampling, decision threshold) and what each option does to probability estimates.
- Tuning. Tune hyperparameters in a way that cannot leak information from validation or test data.
- Metrics. Compute and compare ROC-AUC, PR-AUC, F1, Brier score and a confusion matrix at the threshold you select, and assess calibration.
- Error analysis. Break performance down by data slice and by feature to find where the model fails.
- Reproducibility. Provide a training script driven by a command-line interface and a config file, with full control of random seeds.
- Explainability. Report which features matter (permutation importance and/or SHAP) and confirm the findings with ablation experiments.
- Production readiness. Document risks, fairness checks and monitoring hooks you would put in place.
You are expected to justify why each choice protects the validity of the final test estimate, not just to list library calls.
Hints
Hint 1
Decide first what order data flows in: fit on earlier periods, select on a later one, and report on the latest. Then put every data-dependent step (imputation, encoding, scaling, resampling) inside a single Pipeline so cross-validation refits it per fold.
Hint 2
Separate ranking quality from the decision rule: compare models with a threshold-free metric suited to rare positives (PR-AUC, read against the base rate), then choose the operating threshold on validation using error costs. Remember class weighting skews probabilities, so check Brier score and consider recalibration.
Hint 3
Correlated features split importance between them, so a single importance chart can mislead. Confirm it by removing feature groups and refitting, and run the same slice-level metrics on sensitive attributes to compare TPR and FPR gaps.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Guiding principles
Three rules drive almost every decision:
- Time only moves forward. Fit on the past, select on the next period, and report on the most recent one. Shuffled splits let the model peek at the future and inflate scores.
- Anything learned from data lives inside a
Pipeline. Imputers, encoders, scalers and resamplers are refit within each CV fold, so nothing leaks across folds. - Ranking and deciding are separate steps. Pick the model on a threshold-free metric, pick the threshold on validation using a cost, and touch the test set once.
Stage by stage
1. EDA.
- Missing rate per column; add missing-indicator features if missingness is informative.
- Outliers via a 3×IQR rule (flag, usually do not drop, for tree models).
- Target drift: positive rate by month. Feature drift: PSI between first and last period (PSI above 0.25 is a common "investigate" line).
- Leakage: compute single-feature AUC and flag anything above about 0.95. Then review by meaning: fields recorded after the label event, IDs, "status" or "outcome" columns.
2. Splits. Sort by timestamp. Last 15% is test, the 15% before is validation, the rest is train. Verify positive rates are comparable and that each CV fold contains both classes. Use TimeSeriesSplit (expanding window) on train. If the same entity appears repeatedly, ensure an entity's future rows are not in train when its earlier rows are in test (group-aware splitting).
3. Models.
- Baseline: logistic regression with median imputation plus missing indicators, one-hot encoding, standard scaling.
- Improved:
HistGradientBoostingClassifier, which captures nonlinearity and interactions and handles NaNs natively.
4. Imbalance.
- Cost-sensitive loss (
class_weight="balanced"or sample weights) is the cheapest first step. - Resampling (e.g. SMOTE) is an alternative but must be inside an
imblearn.Pipelineso only training folds are resampled. - Threshold moving: choose the cutoff that minimizes expected cost (or meets a recall/precision target) on validation.
- Weighting and resampling distort probabilities. Check Brier score and recalibrate (isotonic if data is plentiful, Platt otherwise) on held-out data if probabilities are consumed downstream.
5. Tuning. RandomizedSearchCV with TimeSeriesSplit on train only, scoring average_precision. Validation is used only to compare tuned models and choose the threshold. Test is used for neither.
6. Metrics. Report ROC-AUC, PR-AUC (always beside the base rate, since a random model scores PR-AUC equal to prevalence), F1 at the chosen threshold, Brier score, a reliability curve, and the confusion matrix at the threshold. ROC-AUC can look flattering under heavy imbalance, which is why PR-AUC drives selection.
7. Error analysis. For each categorical level and numeric quartile, compute PR-AUC, recall and FPR, then sort by worst PR-AUC. Ignore tiny slices (e.g. under 200 rows) or show confidence intervals. Inspect the highest-confidence mistakes for label noise or missing signals.
8. Reproducibility. A CLI (argparse) takes a JSON config path and a seed; the script sets random.seed, np.random.seed, and random_state on every estimator and splitter, logs library versions and the data hash, and writes a JSON report (metrics, threshold, config) as an artifact.
9. Explainability. Permutation importance on validation (model-agnostic, on raw columns, scored with PR-AUC) gives global ranking. shap.TreeExplainer provides per-row explanations. Then validate with ablation: drop each feature group, refit, and record the PR-AUC change. Correlated features share credit, so permutation importance alone can understate each one; ablation by group exposes that.
10. Risk, fairness, monitoring.
- Fairness: run the slice report on sensitive attributes and compare TPR and FPR gaps (equalized odds) and calibration per group. Note that the sensitive attribute may be proxied by other features.
- Monitoring: log input and score PSI, the positive-prediction rate, latency and null rates; compute delayed-label PR-AUC and calibration once labels arrive; alert on thresholds and define a retrain trigger.
- Document intended use, known failure slices and the date range the model was validated on.
Core code sketch
import numpy as np
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import OneHotEncoder, StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.model_selection import TimeSeriesSplit, RandomizedSearchCV
from sklearn.metrics import average_precision_score, roc_auc_score, brier_score_loss
def time_split(df, ts, val=0.15, test=0.15):
df = df.sort_values(ts)
n = len(df)
a, b = int(n * (1 - val - test)), int(n * (1 - test))
return df.iloc[:a], df.iloc[a:b], df.iloc[b:]
def make_pre(num, cat):
return ColumnTransformer([
("num", Pipeline([("imp", SimpleImputer(strategy="median", add_indicator=True)),
("sc", StandardScaler())]), num),
("cat", OneHotEncoder(handle_unknown="ignore"), cat)])
def best_threshold(y, p, cost_fp=1.0, cost_fn=5.0):
ts = np.unique(np.quantile(p, np.linspace(0.01, 0.99, 99)))
costs = [cost_fp * ((p >= t) & (y == 0)).sum() + cost_fn * ((p < t) & (y == 1)).sum() for t in ts]
return ts[int(np.argmin(costs))]
def run(train, val, test, num, cat, y, seed=42):
Xtr, ytr = train[num + cat], train[y]
base = Pipeline([("pre", make_pre(num, cat)),
("m", LogisticRegression(class_weight="balanced", max_iter=1000, random_state=seed))])
gbm = Pipeline([("pre", make_pre(num, cat)),
("m", HistGradientBoostingClassifier(class_weight="balanced", random_state=seed))])
search = RandomizedSearchCV(
gbm,
{"m__learning_rate": [0.03, 0.05, 0.1], "m__max_depth": [3, 5, None],
"m__l2_regularization": [0, 0.1, 1.0]},
n_iter=10, scoring="average_precision",
cv=TimeSeriesSplit(5), random_state=seed).fit(Xtr, ytr)
base.fit(Xtr, ytr)
out = {}
for name, m in [("baseline", base), ("gbm", search.best_estimator_)]:
p = m.predict_proba(val[num + cat])[:, 1]
out[name] = dict(pr_auc=average_precision_score(val[y], p),
roc_auc=roc_auc_score(val[y], p),
brier=brier_score_loss(val[y], p))
return out, search.best_estimator_
Pick the winner by validation PR-AUC, set the threshold with best_threshold on validation, then score test once.
Complexity
Cost is dominated by tuning: roughly n_iter × n_folds model fits. Permutation importance adds features × repeats predictions, and ablation adds one refit per feature group.
Common mistakes
- Fitting imputers or scalers on the full dataset before splitting.
- Shuffled CV on time-ordered data.
- Tuning the threshold or hyperparameters on the test set.
- Quoting ROC-AUC or accuracy alone on a rare-positive problem.
- Applying SMOTE before cross-validation, which leaks synthetic neighbors of validation rows into training.
- Trusting probabilities after class weighting without checking calibration.
- Reading permutation importance on correlated features as exact.
- Skipping a leakage review because a feature "has high importance".