Next-Month Purchase Model: Leak-Free Pipeline and AUC Evaluation
Machine LearningModel answerLast updated
Build a reproducible stratified-split pipeline with a gradient-boosted classifier for repeat-purchase prediction, report held-out AUC, and propose two ways to improve generalization.
Context
You have a cleaned table of retail customers. Each row describes one customer, and the binary label says whether that customer placed at least one order during the following month. Your job is to build a classifier for this label and judge it honestly.
Tasks
- Divide the data into training and test sets in an 80/20 ratio, stratifying on the label so both sets keep the same share of buyers.
- Create a single reproducible preprocessing-plus-model workflow in which numeric columns are standardized and categorical columns are one-hot encoded.
- Fit a gradient-boosted tree classifier (XGBoost or LightGBM) and report the AUC on the held-out test set.
- Suppose that AUC turns out to be disappointing. Name two techniques you would apply to improve how well the model generalizes, and explain which problem each one targets.
What to cover in your answer
- Why and where you split, and what is allowed to see which rows.
- How the pipeline prevents information from the test set leaking into preprocessing.
- How you obtain AUC (probabilities vs. hard predictions) and how you would use cross-validation.
- How you would diagnose the cause of a low score before choosing a remedy.
- Any leakage risks specific to predicting future behavior from historical data.
Include code (scikit-learn style is fine) and state the complexity or cost considerations where relevant.
Hints
Hint 1
Everything that learns from data (scaler, encoder, model) should be fit on training rows only; a Pipeline with a ColumnTransformer enforces this automatically, and OneHotEncoder needs a setting for categories it has never seen.
Hint 2
AUC is rank-based, so compute it from predict_proba, not predict. Compare train, cross-validation, and test AUC to tell overfitting (big gap) from weak features (all low) and from leakage (suspiciously high).
Hint 3
For improvements, pair each technique with a diagnosis: regularization and tuned hyperparameters for variance, and time-aware behavioral features computed only from data before the cutoff date for bias.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Goal of the exercise
The point is an honest estimate of performance on unseen customers. The choice between XGBoost and LightGBM matters much less than a clean evaluation setup and a reasoned response to a weak score.
1. Frame the problem and name the main risk
The label is "ordered in month t+1". Every feature must be computed only from information available up to the cutoff date t. Features such as "total lifetime orders" or "last order date" taken over the full history silently include the target month and produce an inflated AUC. In repeat-purchase problems this is the most common reason for a result that looks too good.
2. Stratified split
Use an 80/20 split with stratify=y and a fixed random_state.
- Stratification keeps the buyer rate equal in both sets, which matters when buyers are a minority and would otherwise make test AUC noisy.
- The fixed seed makes the split reproducible.
- Split first, before fitting anything, so the scaler, encoder, and model never see test rows.
3. Preprocessing in one pipeline
- Numeric columns go through
StandardScaler. Tree models are invariant to monotonic rescaling, so this has no effect on boosting; mention that, but keep it because it was requested and it makes the pipeline reusable with a linear baseline. - Categorical columns go through
OneHotEncoder(handle_unknown="ignore")so an unseen store or region at test or serving time does not crash the pipeline. - Add imputation if there are missing values (LightGBM and XGBoost can also handle NaNs natively).
- Wrap the
ColumnTransformerand the classifier in aPipeline. Callingfitthen learns scaling statistics and category lists from training data only, and the same transformation is applied at prediction time.
4. Training and evaluation
- Run stratified 5-fold cross-validation on the training portion to get a mean and spread of AUC. All tuning happens here.
- Refit on the whole training set.
- Score the test set once, using the predicted probability of the positive class.
from lightgbm import LGBMClassifier
from sklearn.compose import ColumnTransformer
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import StratifiedKFold, cross_val_score, train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
SEED = 42
def make_pipeline(num_cols, cat_cols):
prep = ColumnTransformer([
("num", StandardScaler(), num_cols),
("cat", OneHotEncoder(handle_unknown="ignore"), cat_cols),
])
clf = LGBMClassifier(
n_estimators=500, learning_rate=0.05, num_leaves=31,
min_child_samples=50, subsample=0.8, subsample_freq=1,
colsample_bytree=0.8, reg_lambda=1.0,
random_state=SEED, verbose=-1,
)
return Pipeline([("prep", prep), ("clf", clf)])
def run(df, target="ordered_next_month"):
X, y = df.drop(columns=[target]), df[target].astype(int)
num_cols = X.select_dtypes(include="number").columns.tolist()
cat_cols = X.select_dtypes(exclude="number").columns.tolist()
X_tr, X_te, y_tr, y_te = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=SEED)
pipe = make_pipeline(num_cols, cat_cols)
cv = StratifiedKFold(5, shuffle=True, random_state=SEED)
cv_auc = cross_val_score(pipe, X_tr, y_tr, cv=cv, scoring="roc_auc")
pipe.fit(X_tr, y_tr)
test_auc = roc_auc_score(y_te, pipe.predict_proba(X_te)[:, 1])
return cv_auc.mean(), cv_auc.std(), test_auc
Notes:
- AUC must be computed from probabilities (or scores). Hard labels collapse the ranking and understate it.
- Class weighting (
scale_pos_weight) changes AUC little because AUC is rank-based, and it distorts calibration, so skip it if calibrated probabilities matter. - For XGBoost, swap in
XGBClassifier(eval_metric="auc"); nothing else changes. - Cost is roughly O(trees x rows x features) per fit, so 5-fold CV multiplies training time by about five.
5. Diagnose before fixing
| Observation | Likely cause |
|---|---|
| Train AUC far above CV/test AUC | Overfitting (high variance) |
| Train and test AUC both low | Weak features or underfitting (high bias) |
| Test AUC above roughly 0.95 for behavioral prediction | Suspect leakage first |
| Random-split CV good, later-month test worse | Temporal drift; random splits were optimistic |
6. Two techniques to improve generalization
Technique 1: Regularize and tune with cross-validation (targets variance).
- Search tree size (
num_leavesormax_depth),min_child_samples, row and column subsampling, L1/L2 penalties, and learning rate with randomized search or Bayesian optimization on stratified folds. - Use early stopping on a validation fold to choose the number of rounds.
- Prefer shallower trees and a lower learning rate with more rounds.
- Never tune on the test set; it is used once at the end.
Technique 2: Better, leakage-safe features (targets bias).
- Build recency, frequency, and monetary features as of the cutoff: days since last order, order counts and spend over the last 30/90/180 days, recent-versus-previous-window trends, average gap between purchases and its variance, basket diversity, promotion and return rates, and calendar effects such as the cutoff month.
- For high-cardinality categoricals, replace one-hot with target encoding that is cross-fitted inside each fold (for example
sklearn.preprocessing.TargetEncoder) to avoid leaking the label.
Bonus: time-aware validation
Deployment predicts the future from the past, so validate that way: train on cutoffs up to month k and test on month k+1, using rolling cutoffs or TimeSeriesSplit. Also make sure the same customer does not appear in both train and test with overlapping windows if that would leak behavior.
Common mistakes
- Fitting the scaler or encoder on the full dataset before splitting.
- Reporting accuracy or AUC from hard labels on an imbalanced target.
- Tuning repeatedly against the test set.
- Using features that include the prediction month.
- Listing generic fixes without tying them to overfitting, weak features, or leakage.