Leak-Free Pipeline for a Rare-Event Classifier
Machine LearningModel answerLast updated
Build a scikit-learn and imbalanced-learn workflow for a rare-positive dataset that avoids leakage, tunes the decision threshold, and reports precision, recall and F1 on untouched data.
You are given a tabular dataset with a binary label in which the positive class is very rare (roughly 1-2% of rows). Features are a mix of numeric columns (some with missing values) and low-cardinality categorical columns.
Using scikit-learn and imbalanced-learn, design and implement an end-to-end training and evaluation workflow that:
- Applies standard preprocessing (imputation, scaling, categorical encoding).
- Uses a suitable resampling or reweighting technique to cope with the imbalance.
- Trains a classifier and tunes it sensibly.
- Reports precision, recall and F1 for the positive class on a held-out set, ideally together with a threshold-independent metric.
In your answer, please:
- State the assumptions you would confirm first (imbalance ratio, relative cost of errors, feature types, whether the data is time-ordered).
- Explain where each step sits relative to the train/validation/test boundaries and why.
- Justify your choice of metrics, sampler and model, and say how you would check that resampling actually helps.
- Provide working code and note the common ways this kind of workflow goes wrong.
Hints
Hint 1
Where does resampling have to happen relative to the train/test split and to each cross-validation fold? Think about which pipeline class guarantees samplers only act during fitting.
Hint 2
Accuracy is useless at a 1-2% positive rate. Pick a scoring metric for model selection that does not depend on a threshold, then choose the operating threshold separately.
Hint 3
Compare SMOTE against simple class weighting as a baseline, and choose the decision cutoff from out-of-fold probabilities on the training data, not from the test set.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
What a strong answer shows
This looks like a coding task but is mostly judged on methodology. Calling SMOTE().fit_resample() is easy; doing it without contaminating your evaluation is the real test.
Assumptions to state up front
- Imbalance and size. "Severe" often means 1:50 to 1:1000. With fewer than about 100 positives, SMOTE interpolates between very few points and gets noisy, so class weighting is safer.
- Cost of errors. Are false positives or false negatives more expensive? This decides whether to optimize F1, F-beta, or recall at a fixed precision.
- Feature types. Mixed types affect encoding and sampler choice (SMOTENC handles categoricals natively; plain SMOTE on one-hot columns creates fractional values).
- Time structure. If rows are time-ordered, use a chronological split, since random splits leak future information.
Design
raw X -> ColumnTransformer -> SMOTE (fit only) -> classifier
numeric: median impute -> StandardScaler
categorical: mode impute -> OneHotEncoder
The key choice is imblearn.pipeline.Pipeline rather than the sklearn one. Samplers in it run only during fit and are skipped at predict/predict_proba. Inside each CV fold, the preprocessor and sampler are fit on that fold's training part only, so validation folds keep the true class ratio.
Protocol
- Stratified hold-out split (e.g. 80/20) so the rare class appears in both parts. Do not touch the test set until the end.
- Hyperparameter search on train only with
StratifiedKFoldandscoring="average_precision". PR-AUC reflects performance on the rare class; ROC-AUC looks flattering when negatives dominate. - Threshold selection from out-of-fold predicted probabilities on train, maximizing F1 or the relevant business metric.
- One final evaluation on the test set at that threshold: precision, recall, F1 for the positive class, plus PR-AUC.
Choosing the sampler and model
| Option | Use when |
|---|---|
class_weight="balanced" | Strong first baseline, no synthetic data; best when positives are very scarce |
| SMOTE / BorderlineSMOTE | Moderate positive count, continuous features; tune k_neighbors |
| SMOTENC | Mixed categorical and numeric features |
| RandomUnderSampler | Huge datasets where training time dominates; discards information |
| SMOTEENN / SMOTETomek | Noisy, overlapping class boundaries |
Logistic regression is an interpretable baseline; gradient boosting (e.g. HistGradientBoostingClassifier with sample weights) is usually stronger on tabular data. Always benchmark resampling against plain class weighting. After threshold tuning, SMOTE frequently adds little.
Code
import numpy as np
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.datasets import make_classification
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import (average_precision_score, precision_recall_curve,
precision_recall_fscore_support)
from sklearn.model_selection import (GridSearchCV, StratifiedKFold,
cross_val_predict, train_test_split)
from sklearn.pipeline import Pipeline as SkPipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
from imblearn.over_sampling import SMOTE
from imblearn.pipeline import Pipeline
SEED = 42
def make_data(n=20000, pos_rate=0.02):
X, y = make_classification(n_samples=n, n_features=12, n_informative=6,
weights=[1 - pos_rate], flip_y=0.005,
random_state=SEED)
df = pd.DataFrame(X, columns=[f"num_{i}" for i in range(X.shape[1])])
rng = np.random.default_rng(SEED)
df["venue"] = rng.choice(["A", "B", "C"], size=len(df))
df.loc[rng.random(len(df)) < 0.01, "num_0"] = np.nan
return df, y
def build(num_cols, cat_cols):
num = SkPipeline([("imp", SimpleImputer(strategy="median")),
("sc", StandardScaler())])
cat = SkPipeline([("imp", SimpleImputer(strategy="most_frequent")),
("oh", OneHotEncoder(handle_unknown="ignore"))])
prep = ColumnTransformer([("num", num, num_cols), ("cat", cat, cat_cols)],
sparse_threshold=0.0)
return Pipeline([("prep", prep),
("smote", SMOTE(random_state=SEED)),
("clf", LogisticRegression(max_iter=2000))])
def best_f1_threshold(y, p):
pr, rc, th = precision_recall_curve(y, p)
f1 = 2 * pr[:-1] * rc[:-1] / np.clip(pr[:-1] + rc[:-1], 1e-12, None)
return th[np.argmax(f1)]
def main():
X, y = make_data()
num_cols = [c for c in X.columns if c.startswith("num_")]
X_tr, X_te, y_tr, y_te = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=SEED)
cv = StratifiedKFold(5, shuffle=True, random_state=SEED)
search = GridSearchCV(
build(num_cols, ["venue"]),
{"smote__sampling_strategy": [0.1, 0.3, 1.0],
"smote__k_neighbors": [3, 5],
"clf__C": [0.1, 1.0, 10.0]},
scoring="average_precision", cv=cv, n_jobs=-1)
search.fit(X_tr, y_tr)
model = search.best_estimator_
oof = cross_val_predict(model, X_tr, y_tr, cv=cv,
method="predict_proba")[:, 1]
thr = best_f1_threshold(y_tr, oof)
proba = model.predict_proba(X_te)[:, 1]
pred = (proba >= thr).astype(int)
p, r, f, _ = precision_recall_fscore_support(
y_te, pred, average="binary", zero_division=0)
print(f"threshold={thr:.3f} precision={p:.3f} recall={r:.3f} F1={f:.3f} "
f"PR-AUC={average_precision_score(y_te, proba):.3f}")
if __name__ == "__main__":
main()
Complexity. Cost is dominated by the grid: 18 configurations x 5 folds = 90 fits, each with SMOTE's k-NN search over the minority class plus a logistic regression fit. This is fine at tens of thousands of rows; for larger data, prefer class weights or undersampling and a randomized search.
Common mistakes
- Resampling before splitting or before CV. Synthetic points derived from validation or test rows leak into training and inflate metrics.
- Fitting scalers or imputers on all data. Keep them inside the pipeline.
- Reporting accuracy. Predicting all negatives already scores about 98%.
- Leaving the threshold at 0.5. Resampling and class weights distort probabilities, so choose the cutoff deliberately, on out-of-fold data.
- Tuning on the test set. Use it once, at the end.
- Oversampling the evaluation data. Evaluate on the natural class distribution, or the numbers will not reflect production.
- Random splits on time-ordered data. Use a forward-chaining split instead.
Extensions worth mentioning
- Calibrate probabilities (isotonic or Platt) if downstream consumers need real risk scores.
- Report confidence intervals for recall via bootstrap, since few positives make the test estimate noisy.
- Monitor positive rate, score distribution and precision at the chosen threshold in production, and retune as prevalence drifts.