End-to-End Pipeline
This page brings the section together into one workflow: load a dataset, compare four models with cross-validation, evaluate the best on a held-out test set, and inspect its feature importances.
Every code block runs in a container in the companion repository, so the numbers and figures are real.
1. Load and explore
Section titled “1. Load and explore”from pathlib import Path
import lightgbm as lgbimport matplotlib.pyplot as pltimport numpy as npimport pandas as pdimport xgboost as xgbfrom sklearn.datasets import make_classificationfrom sklearn.ensemble import RandomForestClassifierfrom sklearn.linear_model import LogisticRegressionfrom sklearn.metrics import RocCurveDisplay, roc_auc_scorefrom sklearn.model_selection import (StratifiedKFold, cross_val_score, train_test_split)from sklearn.pipeline import Pipelinefrom sklearn.preprocessing import StandardScaler
out = Path("outputs")out.mkdir(exist_ok=True)
features, y = make_classification(n_samples=3000, n_features=20, n_informative=10, n_redundant=3, weights=[0.7, 0.3], flip_y=0.05, random_state=42)feature_names = [f"feature_{i}" for i in range(features.shape[1])]print(f"Samples: {features.shape[0]}, Features: {features.shape[1]}")print(f"Class distribution: {np.bincount(y)}")print(f"Class ratio: {np.bincount(y)[1] / len(y):.2%} positive")Samples: 3000, Features: 20Class distribution: [2081 919]Class ratio: 30.63% positive2. Split
Section titled “2. Split”x_train, x_test, y_train, y_test = train_test_split(features, y, test_size=0.2, random_state=42, stratify=y)Hold the test set out until the very end. All model selection happens on the training set with cross-validation.
3. Compare models with cross-validation
Section titled “3. Compare models with cross-validation”models = { "Logistic Regression": Pipeline([("scaler", StandardScaler()), ("clf", LogisticRegression(max_iter=1000, random_state=42))]), "Random Forest": RandomForestClassifier(n_estimators=200, max_depth=10, random_state=42, n_jobs=-1), "XGBoost": xgb.XGBClassifier(n_estimators=200, max_depth=5, learning_rate=0.1, random_state=42, eval_metric="logloss"), "LightGBM": lgb.LGBMClassifier(n_estimators=200, num_leaves=31, learning_rate=0.1, random_state=42, verbose=-1),}cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)cv_scores = {}for name, model in models.items(): s = cross_val_score(model, x_train, y_train, cv=cv, scoring="roc_auc") cv_scores[name] = s print(f"{name:20}: ROC-AUC = {s.mean():.4f} (+/- {s.std():.4f})")cv_means = {name: s.mean() for name, s in cv_scores.items()}Logistic Regression : ROC-AUC = 0.8893 (+/- 0.0171)Random Forest : ROC-AUC = 0.9444 (+/- 0.0114)XGBoost : ROC-AUC = 0.9466 (+/- 0.0121)LightGBM : ROC-AUC = 0.9488 (+/- 0.0117)All three tree models beat logistic regression. LightGBM edges out the others, but the three tree models are within a standard deviation of each other.
The comparison plots also use the training set only. cross_val_predict gives every
training row a prediction from the model that did not see it, with the same five folds,
so the ROC curves compare the four models without the test set. The second plot shows
the mean and standard deviation of the five fold scores printed above.
from sklearn.model_selection import cross_val_predict
fig, ax = plt.subplots(figsize=(6, 5))for name, model in models.items(): oof = cross_val_predict(model, x_train, y_train, cv=cv, method="predict_proba")[:, 1] RocCurveDisplay.from_predictions(y_train, oof, ax=ax, name=name)ax.plot([0, 1], [0, 1], "k--", alpha=0.3)ax.set_title("Out-of-fold ROC curves on the training set")fig.tight_layout()fig.savefig(out / "model-comparison-roc.png", dpi=150)plt.close(fig)
fig, ax = plt.subplots(figsize=(6, 4))ranked = sorted(cv_means, key=cv_means.get)ax.errorbar([cv_means[n] for n in ranked], ranked, xerr=[cv_scores[n].std() for n in ranked], fmt="o", color="#4c72b0", capsize=4)ax.set_xlabel("Cross-validated ROC-AUC (mean +/- SD over 5 folds)")ax.set_title("Model comparison on the training set")fig.tight_layout()fig.savefig(out / "model-comparison-cv.png", dpi=150)plt.close(fig)

The three tree models cluster together; logistic regression sits lower, unable to capture the nonlinear structure. The error bars of the three tree models overlap. The AUC in each ROC legend comes from all out-of-fold predictions pooled together, so it can differ slightly from the mean of the five fold scores.
4. Evaluate the chosen model on the test set
Section titled “4. Evaluate the chosen model on the test set”Cross-validation picks the model, and only that model meets the test set, once. Scoring all four on the test set and keeping the best would turn the test set into a selection tool, the leak the caution at the end of this page warns against.
best_name = max(cv_means, key=cv_means.get)best = models[best_name]best.fit(x_train, y_train)test_auc = roc_auc_score(y_test, best.predict_proba(x_test)[:, 1])print(f"Chosen by cross-validation: {best_name}")print(f"Test ROC-AUC: {test_auc:.4f}")Chosen by cross-validation: LightGBMTest ROC-AUC: 0.9341The test ROC-AUC, 0.9341, is the number to report for LightGBM. It sits below the cross-validated 0.9488. The fold scores already varied with a standard deviation of 0.0117, so a single split of 600 rows can land this far from the mean.
5. Feature importance from the chosen model
Section titled “5. Feature importance from the chosen model”# feature_importances_ exists on the three tree models, not on the# logistic regression pipeline.importance = pd.DataFrame({ "feature": feature_names, "importance": best.feature_importances_,}).sort_values("importance", ascending=False)print(importance.head(6).to_string(index=False))
top15 = importance.head(15)fig, ax = plt.subplots(figsize=(6, 5))ax.barh(top15["feature"][::-1], top15["importance"][::-1], color="#55a868")ax.set_xlabel("Importance")ax.set_title(f"{best_name} feature importance (top 15)")fig.tight_layout()fig.savefig(out / "best-model-importance.png", dpi=150)plt.close(fig) feature importance feature_1 473 feature_8 471 feature_0 458feature_17 414feature_18 413feature_10 399
The complete checklist
Section titled “The complete checklist”- Explore: shape, target balance, missing values, types.
- Split: stratified train/test; hold the test out.
- Preprocess: scale for linear models; tree models take raw features.
- Compare: cross-validate several models on the training set.
- Select: pick the best by cross-validated metric.
- Tune: optionally with
RandomizedSearchCV. - Evaluate: train on the full training set, score on the test set.
- Interpret: feature importance and SHAP.
When model differences are small
Section titled “When model differences are small”Here LightGBM, XGBoost, and Random Forest scored within half a percent in cross-validation. When models are this close, pick the one that is easiest to deploy, fastest to retrain, or most interpretable, or ensemble them. Do not over-optimize on the third decimal place.
Summary
Section titled “Summary”| Step | Tools |
|---|---|
| EDA | pandas, matplotlib |
| Preprocessing | StandardScaler, ColumnTransformer, Pipeline |
| Cross-validation | StratifiedKFold, cross_val_score, cross_val_predict |
| Tuning | RandomizedSearchCV, GridSearchCV |
| Evaluation | classification_report, roc_auc_score, RocCurveDisplay |
| Interpretation | feature_importances_, SHAP |
Scientific references
Section titled “Scientific references”Ke and colleagues, 2017 describe LightGBM, a fast implementation of gradient boosting decision trees.
Chen and Guestrin, 2016 describe XGBoost, a scalable system for gradient tree boosting.
Further reading
Section titled “Further reading”-
scikit-learn cross-validation guide
The guide explains model assessment and selection with separate evaluation data. It helps distinguish the mean fold score used to choose a model from the final test result.
-
The reference separates classification decisions, probability quality, and ranking metrics. Use those definitions when comparing ROC AUC with the other printed results.