KatInterview

Gradient Boosting with Cross-Validation: Train, Evaluate, and Persist

Machine LearningModel answer
EasyModel answerMachine Learninggradient-boostingcross-validationsklearn

Last updated

Build a sklearn Pipeline with gradient boosting, measure generalization via stratified 5-fold ROC-AUC, then refit on all data and save to disk.

Scenario

You are wrapping up a classification project. The data has already been cleaned and split into features (X) and a binary target (y). Your final task is to produce a model file that can be loaded and used to score new rows immediately.

Your Task

Write a complete Python function (or script) that does all of the following:

  1. Wraps preprocessing and a GradientBoostingClassifier together in a single Pipeline.
  2. Evaluates the pipeline with 5-fold cross-validation and prints the mean ROC-AUC score (and its standard deviation across folds).
  3. Trains a final model on the full dataset and saves it to a file called model.pkl.

Input

  • X: a pandas.DataFrame of feature columns (may contain numeric and categorical columns, and some missing values).
  • y: a pandas.Series of binary labels (0/1).

Expected output

  • Console output showing per-fold AUC scores plus the mean ± std.
  • A file model.pkl that can be reloaded with joblib.load and used to call .predict_proba(X) on raw, unprocessed rows.

Constraints and rules

  • Preprocessing (imputation, encoding) must be contained inside the pipeline so that no information from held-out folds leaks into training.
  • The saved model must be the pipeline fitted on the full dataset, not one of the fold clones.
  • Use stratified splitting so class proportions are preserved in every fold and results are reproducible.
  • Use roc_auc as the scoring metric for binary targets.

Hints

Hint 1

Build the preprocessing as a ColumnTransformer inside the Pipeline — this is what prevents data leakage across CV folds. Fitting the imputer on all of X before calling cross_val_score is the most common mistake on this type of task.

Hint 2

cross_val_score fits temporary clones of your pipeline and discards them once scoring is done. The pipeline object you passed in remains unfitted, so you must call pipe.fit(X, y) separately after CV before saving.

Hint 3

Use StratifiedKFold with shuffle=True and a fixed random_state, and set the same random_state on GradientBoostingClassifier. Stratification keeps both classes present in every fold; shuffling guards against data that happens to be sorted by label.