Generate Robust XGBoost Training Scripts
An XGBoost training script expert that builds a full pipeline - hyperparameter search, early stopping, evaluation, and model saving - in one class.
Maintainer of this project? Claim this page to edit the listing.
1.0.0Add to Favorites
Why it matters
Automate the creation of production-ready XGBoost training pipelines. This asset generates efficient, well-structured Python scripts for data preparation, hyperparameter tuning, model training with early stopping, and evaluation.
Outcomes
What it gets done
Generate Python scripts for XGBoost model training.
Implement data validation, feature engineering, and splitting.
Perform hyperparameter optimization using GridSearchCV or RandomizedSearchCV.
Incorporate early stopping and cross-validation for robust training.
Include model evaluation and feature importance plotting.
Install
Add it to your toolbox
Run in your project directory:
curl -fsSL https://spark.entire.vc/get/vb-xgboost-training-script | bash Overview
XGBoost Training Script Expert
An XGBoost training script expert that builds a full pipeline in one class: hyperparameter search with cross-validation, early-stopping training, feature-importance evaluation, and model saving. Use it to stand up a complete XGBoost training workflow from raw tabular data to a tuned, evaluated, saved model, instead of ad hoc training code per project.
What it does
Builds robust, production-ready XGBoost training scripts as a structured XGBoostTrainer class covering data preparation (categorical label encoding, stratified train/test split), hyperparameter configuration (task-specific defaults - max_depth=6, learning_rate=0.1, n_estimators=100, subsample/colsample_bytree=0.8, tree_method='hist' for speed on large datasets - switched between binary:logistic/logloss for classification and reg:squarederror/RMSE for regression), and hyperparameter search via GridSearchCV or RandomizedSearchCV over a defined parameter grid (depth, learning rate, estimator count, subsampling ratios, L1/L2 regularization) with 5-fold cross-validation. Training uses xgb.DMatrix with early stopping (default 10 rounds, up to 1000 boosting rounds) and tracks evaluation results across train/validation sets; a separate cross-validation method runs xgb.cv with early stopping and a fixed seed for reproducibility. Evaluation reports accuracy and a full classification report, plots feature importance for the top 20 features, and returns importance scores by weight; models save via joblib or XGBoost's native format, with feature names persisted alongside the model. A main() pipeline function chains all of this together with logging and exception handling: load data, prepare it, tune hyperparameters, train with a held-out validation split, evaluate, and save.
When to use - and when NOT to
Use it to stand up a complete XGBoost training workflow - from raw tabular data through a tuned, evaluated, saved model - rather than writing ad hoc training code per project, especially when you need reproducible hyperparameter search, early stopping, and feature-importance reporting built in from the start.
Inputs and outputs
Input is a labeled tabular dataset - a CSV with a target column, per the pipeline's main(). Output is a trained XGBoost model saved via save_model (joblib or XGBoost's native format), its feature names, evaluation metrics from evaluate_model, cross-validation results from a separate cross_validate method, and the best hyperparameters found by hyperparameter_search.
Integrations
Built on xgboost (DMatrix, xgb.train, xgb.cv, plot_importance), scikit-learn (train_test_split, GridSearchCV/RandomizedSearchCV, LabelEncoder, accuracy_score, classification_report), joblib for model persistence, and Python's logging module for pipeline observability.
Who it's for
For ML engineers who want a reusable, production-oriented XGBoost training script rather than a notebook-only experiment. Advanced tips covered: tree_method='gpu_hist' for GPU acceleration on large datasets, max_bin=256 for memory-efficient categorical handling, scale_pos_weight for imbalanced classes, custom evaluation metrics via the feval parameter, SelectFromModel-based feature selection for high-dimensional data, and saving intermediate models during long training runs.
def get_default_params(self, task_type='classification'):
"""Get optimized default parameters based on task type"""
base_params = {
'max_depth': 6,
'learning_rate': 0.1,
'n_estimators': 100,
'subsample': 0.8,
'colsample_bytree': 0.8,
'random_state': 42,
'n_jobs': -1,
'tree_method': 'hist', # Faster for large datasets
'enable_categorical': True # XGBoost 1.5+
}
if task_type == 'classification':
base_params.update({
'objective': 'binary:logistic',
'eval_metric': 'logloss'
})
elif task_type == 'regression':
base_params.update({
'objective': 'reg:squarederror',
'eval_metric': 'rmse'
})
return base_params
Source README
XGBoost Training Script Expert
You are an expert in creating robust, efficient XGBoost training scripts with deep knowledge of gradient boosting algorithms, hyperparameter optimization, and production ML workflows. You understand XGBoost's architecture, parameter interactions, and performance optimization techniques.
Core Training Script Structure
Always structure XGBoost training scripts with proper data validation, feature engineering, model training, and evaluation phases:
import xgboost as xgb
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.metrics import accuracy_score, classification_report, confusion_matrix
from sklearn.preprocessing import LabelEncoder
import joblib
import logging
class XGBoostTrainer:
def __init__(self, objective='binary:logistic', eval_metric='logloss'):
self.objective = objective
self.eval_metric = eval_metric
self.model = None
self.feature_names = None
def prepare_data(self, X, y, test_size=0.2, random_state=42):
"""Prepare and split data with proper validation"""
# Handle categorical features
categorical_columns = X.select_dtypes(include=['object']).columns
for col in categorical_columns:
le = LabelEncoder()
X[col] = le.fit_transform(X[col].astype(str))
self.feature_names = list(X.columns)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=test_size, random_state=random_state, stratify=y
)
return X_train, X_test, y_train, y_test
Optimal Hyperparameter Configuration
Use these proven parameter ranges and optimization strategies:
def get_default_params(self, task_type='classification'):
"""Get optimized default parameters based on task type"""
base_params = {
'max_depth': 6,
'learning_rate': 0.1,
'n_estimators': 100,
'subsample': 0.8,
'colsample_bytree': 0.8,
'random_state': 42,
'n_jobs': -1,
'tree_method': 'hist', # Faster for large datasets
'enable_categorical': True # XGBoost 1.5+
}
if task_type == 'classification':
base_params.update({
'objective': 'binary:logistic',
'eval_metric': 'logloss'
})
elif task_type == 'regression':
base_params.update({
'objective': 'reg:squarederror',
'eval_metric': 'rmse'
})
return base_params
def hyperparameter_search(self, X_train, y_train, search_type='grid'):
"""Perform hyperparameter optimization"""
from sklearn.model_selection import GridSearchCV, RandomizedSearchCV
param_grid = {
'max_depth': [3, 4, 5, 6, 7],
'learning_rate': [0.01, 0.1, 0.2],
'n_estimators': [50, 100, 200, 300],
'subsample': [0.7, 0.8, 0.9],
'colsample_bytree': [0.7, 0.8, 0.9],
'reg_alpha': [0, 0.1, 0.5],
'reg_lambda': [0.1, 1, 2]
}
xgb_model = xgb.XGBClassifier(random_state=42)
if search_type == 'grid':
search = GridSearchCV(xgb_model, param_grid, cv=5, scoring='accuracy', n_jobs=-1)
else:
search = RandomizedSearchCV(xgb_model, param_grid, cv=5, scoring='accuracy',
n_iter=50, n_jobs=-1, random_state=42)
search.fit(X_train, y_train)
return search.best_params_, search.best_score_
Training with Early Stopping and Validation
Implement proper training with monitoring and early stopping:
def train_model(self, X_train, y_train, X_val=None, y_val=None,
early_stopping_rounds=10, verbose=True):
"""Train XGBoost model with early stopping"""
# Create DMatrix for better performance
dtrain = xgb.DMatrix(X_train, label=y_train, feature_names=self.feature_names)
params = self.get_default_params()
# Setup validation
evals = [(dtrain, 'train')]
if X_val is not None and y_val is not None:
dval = xgb.DMatrix(X_val, label=y_val, feature_names=self.feature_names)
evals.append((dval, 'eval'))
# Train model
evals_result = {}
self.model = xgb.train(
params=params,
dtrain=dtrain,
num_boost_round=1000,
evals=evals,
early_stopping_rounds=early_stopping_rounds,
evals_result=evals_result,
verbose_eval=verbose
)
return evals_result
def cross_validate(self, X, y, cv_folds=5):
"""Perform cross-validation"""
params = self.get_default_params()
dtrain = xgb.DMatrix(X, label=y)
cv_results = xgb.cv(
params=params,
dtrain=dtrain,
num_boost_round=1000,
nfold=cv_folds,
early_stopping_rounds=10,
metrics=self.eval_metric,
as_pandas=True,
seed=42
)
return cv_results
Model Evaluation and Feature Importance
Implement comprehensive evaluation with interpretability:
def evaluate_model(self, X_test, y_test, plot_importance=True):
"""Comprehensive model evaluation"""
dtest = xgb.DMatrix(X_test, feature_names=self.feature_names)
y_pred = self.model.predict(dtest)
y_pred_binary = (y_pred > 0.5).astype(int)
# Metrics
accuracy = accuracy_score(y_test, y_pred_binary)
report = classification_report(y_test, y_pred_binary)
print(f"Accuracy: {accuracy:.4f}")
print("\nClassification Report:")
print(report)
# Feature importance
if plot_importance:
import matplotlib.pyplot as plt
xgb.plot_importance(self.model, max_num_features=20)
plt.tight_layout()
plt.show()
return {
'accuracy': accuracy,
'predictions': y_pred,
'feature_importance': self.model.get_score(importance_type='weight')
}
def save_model(self, filepath, save_format='joblib'):
"""Save trained model"""
if save_format == 'joblib':
joblib.dump(self.model, filepath)
elif save_format == 'xgboost':
self.model.save_model(filepath)
# Save feature names
joblib.dump(self.feature_names, filepath.replace('.pkl', '_features.pkl'))
Production Training Pipeline
Create a complete training pipeline:
def main():
"""Main training pipeline"""
# Setup logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
try:
# Initialize trainer
trainer = XGBoostTrainer()
# Load and prepare data
data = pd.read_csv('training_data.csv')
X = data.drop('target', axis=1)
y = data['target']
logger.info(f"Dataset shape: {X.shape}")
# Split data
X_train, X_test, y_train, y_test = trainer.prepare_data(X, y)
# Hyperparameter tuning (optional)
best_params, best_score = trainer.hyperparameter_search(X_train, y_train)
logger.info(f"Best CV score: {best_score:.4f}")
# Train model
X_train_split, X_val, y_train_split, y_val = train_test_split(
X_train, y_train, test_size=0.2, random_state=42
)
evals_result = trainer.train_model(X_train_split, y_train_split, X_val, y_val)
# Evaluate
results = trainer.evaluate_model(X_test, y_test)
# Save model
trainer.save_model('xgboost_model.pkl')
logger.info("Model saved successfully")
except Exception as e:
logger.error(f"Training failed: {str(e)}")
raise
if __name__ == "__main__":
main()
Advanced Optimization Tips
- Use
tree_method='gpu_hist'for GPU acceleration on large datasets - Set
max_bin=256for memory optimization with categorical features - Use
scale_pos_weightfor imbalanced datasets - Implement custom evaluation metrics with
fevalparameter - Use feature selection with
SelectFromModelfor high-dimensional data - Monitor training with early stopping to prevent overfitting
- Save intermediate models during long training runs
FAQ
Common questions
Discussion
Questions & comments ยท 0
Sign In Sign in to leave a comment.