KatInterview

Leakage-Free Churn Model Pipeline Tuned for Average Precision

Machine LearningModel answer
MediumModel answerMachine Learningscikit-learnclass-imbalancepipelines

Last updated

Build a scikit-learn pipeline for a 5%-positive churn dataset: mixed-type preprocessing, imbalance handling, stratified CV, and tuning on precision-recall area instead of accuracy.

Predicting subscriber churn with a rare positive class

A product team keeps 100,000 rows of per-user activity data. The label is_churned is positive for only about 5% of users. You are asked to produce a trustworthy classifier using scikit-learn.

Assume X is a pandas DataFrame with the columns age, tenure, monthly_spend (numeric) and region (categorical), and y is the binary label.

Task

Write a function with this interface:

from sklearn.pipeline import Pipeline

def build_churn_model(X, y) -> Pipeline:
    """Return a fitted pipeline."""

It should:

  1. Scale numeric columns with StandardScaler and encode categorical columns with OneHotEncoder, combined through a ColumnTransformer.
  2. Chain the preprocessing and a RandomForestClassifier into a single Pipeline.
  3. Compare candidate settings with a cross-validation scheme that preserves the class ratio in every fold (for example StratifiedKFold).
  4. Select the model using the area under the precision-recall curve rather than accuracy.

What to explain

  • Show the pipeline code.
  • Describe how you would deal with the imbalance, using either class_weight or resampling such as SMOTE, and where in the workflow it must be applied.
  • Name the evaluation metric you use and argue why it is a better choice than accuracy for this dataset.

Constraints

  • Use ColumnTransformer to treat numeric and categorical features differently.
  • No information from validation data may influence preprocessing, resampling, or model fitting (no data leakage).

Hints

Hint 1

Everything that learns from data (scaler statistics, encoder categories, imputers, resampling) should be a step inside the Pipeline, so a search object refits it on each training fold only.

Hint 2

Compute what a trivial 'nobody churns' model would score on accuracy when 5% are positive, and compare it to the baseline value of a precision-recall curve for a random model.

Hint 3

In scikit-learn, the scorer string `average_precision` estimates the area under the precision-recall curve. If you use SMOTE, you need the imbalanced-learn pipeline so that sampling happens only while fitting, and you should not stack it with class weights.