KatInterview

Leak-Free Pipeline for a Rare-Event Classifier

Machine LearningModel answer
MediumModel answerMachine Learningimbalanced-learnsmotescikit-learn

Last 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:

  1. Applies standard preprocessing (imputation, scaling, categorical encoding).
  2. Uses a suitable resampling or reweighting technique to cope with the imbalance.
  3. Trains a classifier and tunes it sensibly.
  4. 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.