Binary Classification Pipeline for Rare Events
Machine LearningModel answerLast updated
Design a complete ML pipeline for severely imbalanced classification, including temporal splitting, calibration, threshold selection, and drift monitoring.
You're building a binary classifier for a dataset where the positive class occurs roughly 1% of the time. Your dataset contains:
- An identifier column
- A date field formatted as YYYY-MM-DD
- A categorical feature:
regionwith values {NA, EU, APAC, LATAM, MEA} - Fifty numerical features named f1 through f50
- A binary target variable (0 or 1)
Your task is to:
Part A: Pipeline Construction
Create a training pipeline that avoids data leakage and produces well-calibrated probability estimates. Your pipeline must:
- Split data by time: training data through 2025-06-01, validation from 2025-06-02 to 2025-08-01, and test from 2025-08-02 to 2025-09-01
- Standardize numerical features and one-hot encode the categorical feature
- Address the class imbalance appropriately during cross-validation without introducing leakage
- Train a model that produces calibrated probabilities (consider techniques like Platt scaling or isotonic regression applied to the validation set)
Part B: Evaluation Metrics
On the test set, compute and report:
- ROC-AUC and PR-AUC
- Recall when the false positive rate is fixed at 5%
- The threshold that maximizes F1 score while maintaining recall of at least 90%
Part C: Production Threshold Selection
Explain how you would select an operating threshold for deployment when there's a business requirement that no more than 2 false positives can occur per 1,000 predictions.
Part D: Calibration Monitoring
Describe how calibration quality might degrade over time in production and propose a monitoring approach that detects this degradation without requiring immediate access to ground truth labels.
Hints
Hint 1
Think about when each preprocessing step should be fitted—before or after splitting? What about synthetic sampling techniques?
Hint 2
For highly imbalanced data, consider whether accuracy or ROC-AUC alone tells the full story. What metric better reflects performance when positives are rare?
Hint 3
Reweighting or oversampling changes the predicted probability distribution. How do you restore proper calibration after training?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: Binary Classification Pipeline for Rare Events
This problem tests your ability to build production-grade ML pipelines while avoiding common pitfalls: data leakage, inappropriate metrics, and miscalibrated predictions.
Part A: Leak-Free Pipeline Design
Step 1: Temporal Splitting (First and Foremost)
Split chronologically before any data transformations. This prevents future information from leaking into training:
import pandas as pd
import numpy as np
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import TimeSeriesSplit, GridSearchCV
from sklearn.metrics import roc_auc_score, average_precision_score, roc_curve, precision_recall_curve
from sklearn.calibration import CalibratedClassifierCV
# Load and sort by date
df = pd.read_csv("data.csv", parse_dates=["event_date"]).sort_values("event_date")
# Temporal splits
train_mask = df["event_date"] <= "2025-06-01"
val_mask = (df["event_date"] >= "2025-06-02") & (df["event_date"] <= "2025-08-01")
test_mask = (df["event_date"] >= "2025-08-02") & (df["event_date"] <= "2025-09-01")
X_train, y_train = df.loc[train_mask, features], df.loc[train_mask, "y"]
X_val, y_val = df.loc[val_mask, features], df.loc[val_mask, "y"]
X_test, y_test = df.loc[test_mask, features], df.loc[test_mask, "y"]
Step 2: Preprocessing Pipeline
Use ColumnTransformer to handle different feature types. Crucially, fit transformations only on training data:
numeric_features = [f"f{i}" for i in range(1, 51)]
categorical_features = ["region"]
preprocessor = ColumnTransformer([
("numeric", StandardScaler(), numeric_features),
("categorical", OneHotEncoder(handle_unknown="ignore", sparse_output=False),
categorical_features)
])
Step 3: Handle Imbalance Without Leakage
For a 1% positive rate, use class_weight="balanced" in the classifier. This adjusts the loss function without creating synthetic data:
base_model = Pipeline([
("preprocessor", preprocessor),
("classifier", LogisticRegression(
class_weight="balanced",
max_iter=1000,
random_state=42
))
])
Alternatively, if using SMOTE, apply it only within each cross-validation fold using imblearn.pipeline.Pipeline to prevent synthetic samples from validation folds entering training.
Step 4: Hyperparameter Tuning with Time-Aware CV
Use TimeSeriesSplit to maintain temporal ordering within the training set:
tscv = TimeSeriesSplit(n_splits=5)
param_grid = {"classifier__C": [0.01, 0.1, 1.0, 10.0]}
grid_search = GridSearchCV(
base_model,
param_grid,
cv=tscv,
scoring="average_precision", # PR-AUC, better for imbalanced data
n_jobs=-1
)
grid_search.fit(X_train, y_train)
best_model = grid_search.best_estimator_
Step 5: Probability Calibration
Class reweighting distorts probability estimates. Recalibrate using the validation set:
# Get uncalibrated predictions on validation
val_scores = best_model.decision_function(X_val).reshape(-1, 1)
# Platt scaling (logistic regression on scores)
calibrator = LogisticRegression(C=1e10, max_iter=1000)
calibrator.fit(val_scores, y_val)
def calibrated_predict_proba(X):
scores = best_model.decision_function(X).reshape(-1, 1)
return calibrator.predict_proba(scores)[:, 1]
Use Platt scaling when validation positives number fewer than ~1,000. Isotonic regression requires more data but makes no parametric assumptions.
Part B: Comprehensive Evaluation
Metrics on Test Set:
test_probs = calibrated_predict_proba(X_test)
# ROC-AUC and PR-AUC
roc_auc = roc_auc_score(y_test, test_probs)
pr_auc = average_precision_score(y_test, test_probs)
# Recall at 5% FPR
fpr, tpr, _ = roc_curve(y_test, test_probs)
recall_at_5pct_fpr = np.interp(0.05, fpr, tpr)
print(f"ROC-AUC: {roc_auc:.3f}")
print(f"PR-AUC: {pr_auc:.3f} (baseline ~0.01)")
print(f"Recall @ 5% FPR: {recall_at_5pct_fpr:.3f}")
For rare events, PR-AUC is more informative than ROC-AUC. A random classifier achieves PR-AUC equal to the base rate (~0.01), while ROC-AUC stays near 0.5.
F1-Optimal Threshold with Recall Constraint:
Select the threshold on validation data, then evaluate on test:
def find_threshold_for_recall(y_true, y_probs, min_recall=0.90):
precision, recall, thresholds = precision_recall_curve(y_true, y_probs)
precision, recall = precision[:-1], recall[:-1]
f1_scores = 2 * precision * recall / np.maximum(precision + recall, 1e-10)
valid_indices = recall >= min_recall
if not np.any(valid_indices):
return None, 0, 0
best_idx = np.argmax(np.where(valid_indices, f1_scores, -np.inf))
return thresholds[best_idx], f1_scores[best_idx], recall[best_idx]
# Select on validation
val_probs = calibrated_predict_proba(X_val)
threshold, _, _ = find_threshold_for_recall(y_val, val_probs, min_recall=0.90)
# Evaluate on test
test_preds = test_probs >= threshold
test_recall = test_preds[y_test == 1].mean()
test_precision = y_test[test_preds].mean() if test_preds.any() else 0
test_f1 = 2 * test_precision * test_recall / (test_precision + test_recall)
print(f"Threshold: {threshold:.4f}")
print(f"Test Recall: {test_recall:.3f}, Precision: {test_precision:.3f}, F1: {test_f1:.3f}")
Part C: Production Operating Point (≤2 FP per 1,000)
Constraint Translation:
With 99% negatives, 2 FP per 1,000 predictions means:
- FP rate relative to total predictions: 0.002
- FP rate relative to negatives (FPR): 0.002 / 0.99 ≈ 0.20%
This is an extremely stringent requirement.
Conservative Selection Approach:
- Use confidence intervals: On validation data, compute empirical FP rates with 95% upper confidence bounds (e.g., Wilson score interval)
- Select threshold conservatively: Choose the lowest threshold where the upper confidence bound on FP rate stays at or below 0.002
- Accept the recall trade-off: This constraint will produce low recall—quantify and communicate this to stakeholders
from scipy import stats
def select_production_threshold(y_true, y_probs, max_fp_per_thousand=2):
# Try candidate thresholds
candidates = np.percentile(y_probs, [99, 99.5, 99.8, 99.9])
n_total = len(y_true)
target_fp_rate = max_fp_per_thousand / 1000
for thresh in sorted(candidates, reverse=True):
preds = y_probs >= thresh
fp_count = np.sum((preds == 1) & (y_true == 0))
# Wilson score interval for binomial proportion
observed_rate = fp_count / n_total
ci_upper = stats.binom.ppf(0.95, n_total, observed_rate) / n_total
if ci_upper <= target_fp_rate:
recall = preds[y_true == 1].mean()
return thresh, recall
return None, 0
threshold, expected_recall = select_production_threshold(y_val, val_probs)
Guardrail Monitoring: Since FP ≤ total flags, if the overall flag rate stays below 0.2%, the constraint is automatically satisfied regardless of label distribution.
Part D: Calibration Drift Monitoring
Why Calibration Degrades:
Over time, feature distributions shift, relationships change, and the model's probability estimates become unreliable even if discrimination (AUC) holds steady.
Label-Free Monitoring Technique:
Use prediction histogram stability as a proxy:
- Bin predicted probabilities (e.g., [0-0.1, 0.1-0.2, ..., 0.9-1.0])
- Track the distribution of predictions across bins over rolling windows
- Alert on distribution shifts using KL divergence or chi-squared tests
When labels arrive with delay:
- Compute calibration metrics like Expected Calibration Error (ECE) or Brier score on the labeled data
- Compare predicted vs. observed rates within probability bins
- Trigger recalibration (refit Platt scaling on recent labeled data) when ECE exceeds a threshold
Example Calibration Check:
def check_calibration(y_true, y_probs, n_bins=10):
bins = np.linspace(0, 1, n_bins + 1)
bin_indices = np.digitize(y_probs, bins[1:-1])
ece = 0
for i in range(n_bins):
mask = bin_indices == i
if mask.sum() > 0:
bin_mean_pred = y_probs[mask].mean()
bin_mean_true = y_true[mask].mean()
ece += mask.sum() * abs(bin_mean_pred - bin_mean_true)
return ece / len(y_true)
Recalibrate periodically (e.g., monthly) without retraining the full model—this is lightweight and preserves the learned decision boundaries while correcting probability estimates.
Common Mistakes to Avoid:
- Calibrating before threshold selection (order matters)
- Using accuracy as a primary metric (misleading at 1% base rate)
- Fitting scalers or encoders on the full dataset before splitting
- Applying SMOTE before cross-validation splits
- Selecting thresholds on test data