Gradient Boosting with Cross-Validation: Train, Evaluate, and Persist
Machine LearningModel answerLast 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:
- Wraps preprocessing and a
GradientBoostingClassifiertogether in a singlePipeline. - Evaluates the pipeline with 5-fold cross-validation and prints the mean ROC-AUC score (and its standard deviation across folds).
- Trains a final model on the full dataset and saves it to a file called
model.pkl.
Input
X: apandas.DataFrameof feature columns (may contain numeric and categorical columns, and some missing values).y: apandas.Seriesof binary labels (0/1).
Expected output
- Console output showing per-fold AUC scores plus the mean ± std.
- A file
model.pklthat can be reloaded withjoblib.loadand 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_aucas 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.
Model answer
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This task is a checklist of four concrete steps. Getting all four right — especially step 3 — is what separates a strong answer from an average one.
- Pipeline with preprocessing inside — prevents leakage.
- StratifiedKFold +
cross_val_score— gives an honest generalization estimate. - Explicit refit on full data — the step most candidates miss.
- Save the whole pipeline — so
model.pklcan handle raw rows.
Why the pipeline matters for CV
When you call cross_val_score, scikit-learn clones your estimator five times and fits each clone on a different 80% split. If your imputer was fit on all of X before this call, the held-out 20% is no longer truly unseen — the imputer's medians already "saw" those rows. Putting everything inside a Pipeline means each clone refits the imputer only on its own training split, which is the only correct behavior.
The refit trap
cross_val_score returns an array of scores. It does not modify the pipeline object you passed in. After the call returns, pipe is still unfitted. Calling joblib.dump(pipe, "model.pkl") at that point saves a useless object. Always call pipe.fit(X, y) before dumping.
What to report
Report mean ± standard deviation, not just the mean. A mean AUC of 0.87 ± 0.01 is a stable result; 0.87 ± 0.07 means the model is sensitive to which fold it was evaluated on, which is worth investigating before shipping.
Complexity
Let n = rows, d = features after encoding, T = number of estimators, and max depth fixed at a small constant.
- Time per fit: roughly O(T · d · n log n) — gradient boosting sorts each feature for split search at every tree node. There are 6 total fits (5 CV folds + 1 final refit). The folds can be parallelized with
n_jobs=-1; the boosting itself is sequential across trees. - Space: O(n · d) for the encoded data plus O(T · 2^depth) for the tree structures. One-hot encoding high-cardinality columns can inflate d quickly, so use
max_categoriesor target encoding in production if that's a concern.
Edge cases and pitfalls
- Imbalanced classes: stratification maintains ratios per fold; ROC-AUC is threshold-free so it handles imbalance more gracefully than accuracy.
- Multiclass target:
"roc_auc"raises an error. Switch to"roc_auc_ovr"or"roc_auc_ovr_weighted". - Unseen categories at inference: set
OneHotEncoder(handle_unknown="ignore")so new categories silently become all-zeros rather than raising an exception. - NaN handling:
GradientBoostingClassifierdoes not handle NaN natively in older scikit-learn versions (unlikeHistGradientBoostingClassifier), so always include aSimpleImputerstep. - Pickle versioning: a
.pklfile is tied to the scikit-learn version it was created with. Pin your dependencies and document them alongside the saved file.
Python solution
import joblib
import numpy as np
import pandas as pd
from sklearn.compose import ColumnTransformer, make_column_selector
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.impute import SimpleImputer
from sklearn.model_selection import StratifiedKFold, cross_val_score
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder
RANDOM_STATE = 42
def build_pipeline(random_state: int = RANDOM_STATE) -> Pipeline:
"""Assemble a preprocessing + GBC pipeline."""
numeric_pipe = Pipeline([
("impute", SimpleImputer(strategy="median")),
])
categorical_pipe = Pipeline([
("impute", SimpleImputer(strategy="most_frequent")),
("onehot", OneHotEncoder(handle_unknown="ignore", sparse_output=False)),
])
preprocessor = ColumnTransformer([
("num", numeric_pipe, make_column_selector(dtype_include=np.number)),
("cat", categorical_pipe, make_column_selector(dtype_exclude=np.number)),
])
classifier = GradientBoostingClassifier(
n_estimators=200,
learning_rate=0.05,
max_depth=3,
subsample=0.8,
random_state=random_state,
)
return Pipeline([("preprocess", preprocessor), ("model", classifier)])
def train_and_save(
X: pd.DataFrame,
y: pd.Series,
model_path: str = "model.pkl",
n_splits: int = 5,
) -> float:
"""
Run stratified k-fold CV, print mean ROC-AUC,
refit on all data, and persist the pipeline.
Returns the mean CV AUC.
"""
pipe = build_pipeline()
# Adjust scoring for multiclass targets
scoring = "roc_auc" if y.nunique() == 2 else "roc_auc_ovr"
cv = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=RANDOM_STATE)
# CV scores only — pipe is NOT fitted after this call
scores = cross_val_score(pipe, X, y, cv=cv, scoring=scoring, n_jobs=-1)
print(f"Fold AUC scores : {np.round(scores, 4)}")
print(f"Mean ROC-AUC : {scores.mean():.4f} ± {scores.std():.4f}")
# Refit on the full dataset before saving
pipe.fit(X, y)
joblib.dump(pipe, model_path)
print(f"Pipeline saved : {model_path}")
return float(scores.mean())
# --- entry point -----------------------------------------------------------
if __name__ == "__main__":
# In a notebook X and y are already in scope; fall back to CSV otherwise.
try:
X, y # noqa: F821 — assume already defined in notebook scope
except NameError:
df = pd.read_csv("prepared_data.csv")
y = df["target"]
X = df.drop(columns=["target"])
mean_auc = train_and_save(X, y)
# Quick sanity check: reload and score a few rows
loaded_pipeline = joblib.load("model.pkl")
sample_probs = loaded_pipeline.predict_proba(X.head())[:, 1]
print(f"Sample probabilities: {np.round(sample_probs, 4)}")
How to walk through this in an interview
Start with the pipeline — one sentence: "I wrap preprocessing inside the pipeline so CV folds stay honest." Then name the refit trap explicitly: "cross_val_score only returns scores; the pipeline object is still unfitted, so I call pipe.fit(X, y) before saving." That single point demonstrates real experience. Finally, report mean ± std and mention that you'd switch to HistGradientBoostingClassifier if n is large (it bins features, handles NaN natively, and is significantly faster).
Common mistakes to call out
- Fitting the imputer on all of
Xbefore CV — classic leakage. - Saving the pipeline before the explicit refit — saves an unfitted object.
- Using plain
KFoldon data that happens to be sorted by class label — some folds end up with one class only, making AUC undefined. - Reporting only the mean AUC and ignoring variance across folds.