Leakage-Free Churn Model Pipeline Tuned for Average Precision
Machine LearningModel answerLast 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:
- Scale numeric columns with
StandardScalerand encode categorical columns withOneHotEncoder, combined through aColumnTransformer. - Chain the preprocessing and a
RandomForestClassifierinto a singlePipeline. - Compare candidate settings with a cross-validation scheme that preserves the class ratio in every fold (for example
StratifiedKFold). - 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_weightor 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
ColumnTransformerto 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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Treat this as a leakage-free model selection problem with four ingredients: one pipeline, imbalance handled inside it, stratified folds, and a scorer that matches the business goal.
1. One pipeline, no leakage
Anything that estimates statistics from data must be fit only on the training portion of each fold. Scaler means and variances, imputer medians, encoder vocabularies, and synthetic samples all qualify. If you preprocess the full dataset first and then cross-validate, validation rows influence the training transformations and the scores come out optimistic. Putting every step in a Pipeline and passing that pipeline to the search object guarantees a refit per fold.
2. Code
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.ensemble import RandomForestClassifier
from sklearn.impute import SimpleImputer
from sklearn.model_selection import StratifiedKFold, RandomizedSearchCV
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
def build_churn_model(X: pd.DataFrame, y, random_state: int = 42) -> Pipeline:
numeric = ["age", "tenure", "monthly_spend"]
categorical = ["region"]
num_tf = Pipeline([
("impute", SimpleImputer(strategy="median")),
("scale", StandardScaler()),
])
cat_tf = Pipeline([
("impute", SimpleImputer(strategy="most_frequent")),
("onehot", OneHotEncoder(handle_unknown="ignore")),
])
prep = ColumnTransformer([
("num", num_tf, numeric),
("cat", cat_tf, categorical),
])
pipe = Pipeline([
("prep", prep),
("clf", RandomForestClassifier(
n_estimators=300,
class_weight="balanced_subsample",
random_state=random_state,
)),
])
grid = {
"clf__max_depth": [None, 8, 16, 32],
"clf__min_samples_leaf": [1, 5, 20, 50],
"clf__max_features": ["sqrt", 0.3, 0.5],
}
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=random_state)
search = RandomizedSearchCV(
pipe, grid, n_iter=20, scoring="average_precision",
cv=cv, refit=True, n_jobs=-1, random_state=random_state,
)
search.fit(X, y)
return search.best_estimator_
Selecting columns by explicit lists (rather than by dtype) avoids accidentally scaling integer-coded categories. Note that random forests do not need scaling, so StandardScaler is harmless here but becomes important if you later swap in logistic regression or an SVM.
3. Handling the imbalance
Class weights (default choice). class_weight="balanced_subsample" reweights classes by inverse frequency within each tree's bootstrap sample, roughly 19:1 in favor of positives here. It is cheap, creates no synthetic rows, and needs no extra dependency.
SMOTE-style resampling. Use imblearn.pipeline.Pipeline (not the scikit-learn one), which applies samplers only during fit, so validation folds stay untouched. With mixed data, use SMOTENC or apply SMOTE after encoding. Two pitfalls:
- Oversampling the whole dataset before CV leaks: synthetic points are interpolated from rows that later appear in validation.
- Do not combine SMOTE with
class_weight="balanced"; that corrects the imbalance twice.
Either approach shifts predicted probabilities away from true churn rates. If calibrated probabilities are required, wrap the final model in CalibratedClassifierCV.
4. Cross-validation
StratifiedKFold keeps about 5% positives in each fold (roughly 1,000 positives per validation fold with 5 folds), so every fold gives a stable estimate. With much smaller data, use repeated stratified CV. If the logs span time, prefer a time-ordered split, since random folds let future behavior leak into training.
5. Why average precision instead of accuracy
A model that always predicts "not churned" gets 95% accuracy and catches no churners. Accuracy is dominated by the majority class and also depends on a fixed 0.5 threshold.
The precision-recall curve plots precision (of the users we flag, how many truly churn) against recall (of the true churners, how many we flag) over all thresholds, focusing entirely on the positive class. A random model's area equals the prevalence (0.05), so the baseline is explicit and improvements are easy to read. average_precision is a step-wise sum, avoiding the over-optimistic linear interpolation of trapezoidal PR-AUC. ROC-AUC is less informative here because the huge number of negatives keeps the false-positive rate small even when precision is poor.
Complexity
- Time: one forest fit is roughly O(T · m · n log n) (trees, features per split, rows). The search multiplies this by
n_iter × n_splits + 1= 101 fits. Parallelize withn_jobs, keepn_itermodest, or use successive halving. - Space: O(n · d) for the data, with a sparse one-hot output. Fully grown forests can reach hundreds of MB, so limiting depth or leaf size also helps memory.
Edge cases and common mistakes
- Unseen categories at inference:
handle_unknown="ignore"yields an all-zero encoding instead of an error. - Missing values: imputers inside the pipeline are fit per fold.
- Fitting the scaler or SMOTE on all data before CV (leakage).
- Reporting accuracy or a 0.5-threshold F1 as the headline number.
- Tuning the decision threshold on training data; use out-of-fold predictions instead.
Likely follow-ups
Feature importance with one-hot columns. Impurity importances align with prep.get_feature_names_out(), and a categorical's importance is spread across its dummies, so sum them per original column. They are also biased toward continuous and high-cardinality features. Prefer permutation_importance on the whole pipeline with scoring="average_precision" on held-out data, which permutes raw columns so region gets one score.
Targeting a given recall (say 90%). Keep the trained model and pick the threshold from out-of-fold scores (cross_val_predict(..., method="predict_proba") followed by precision_recall_curve): take the highest threshold whose recall is at least 0.90 and report the precision at that point. Confirm it on a final untouched test set.