3. Hyperparameter Optimization
Duration2h30 AI Banned
Introduction
This practical session extends your structured ML pipeline by introducing advanced algorithms and systematic hyperparameter optimization. You’ll transform your linear regression baseline into a comprehensive comparison framework supporting gradient boosting models with automated parameter tuning.
Through this hands-on workshop, you will master advanced machine learning engineering skills:
- Advanced Algorithms: Implement XGBoost and LightGBM for improved predictive performance
- Hyperparameter Optimization: Apply GridSearchCV with geographic cross-validation to prevent data leakage
- Model Comparison: Systematically evaluate multiple algorithms with statistical rigor
- Production Optimization: Learn when and how to apply optimization in real-world scenarios
- Performance Analysis: Understand the trade-offs between model complexity, training time, and predictive accuracy
The challenge is to extend your existing pipeline architecture while maintaining geographic cross-validation integrity and implementing robust optimization strategies. This represents the natural evolution from proof-of-concept to production-ready ML systems.
Prerequisites
Before starting this activity, ensure you have completed:
- Environment Setup - Python environment with required packages installed
- Structured ML Pipeline Development - Previous workshop with complete pipeline implementation
This activity assumes you have a working structured pipeline with DataProcessor, FeatureEngineer, ModelTrainer, and Evaluator components fully implemented.
Understanding Advanced Model Integration
The advanced pipeline extends your existing architecture while preserving the modular design principles:
src/
├── pipeline/
│ ├── data_processor.py # ✅ Already implemented
│ ├── feature_engineer.py # ✅ Already implemented
│ ├── model_trainer.py # 🔧 Extend with XGBoost/LightGBM
│ └── evaluator.py # 🔧 Add hyperparameter optimization
└── utils/
└── config.py # 🔧 Add model configurationsNew Components
- XGBoost Integration: Gradient boosting framework optimized for speed and performance
- LightGBM Integration: Microsoft’s efficient gradient boosting framework
- GridSearchCV with Geographic Folds: Systematic hyperparameter search that respects city boundaries
- Performance Comparison: Automated evaluation across multiple algorithms and configurations
Architecture Benefits
- Backward Compatibility: Existing linear models continue to work unchanged
- Extensible Design: Easy addition of new algorithms without breaking existing code
- Geographic Integrity: Hyperparameter optimization respects data leakage constraints
- Production Ready: Configurable optimization suitable for deployment scenarios
Getting Started
Environment Update
First, ensure you have the required advanced ML libraries xgboost 3.0.2 and lightgbm 3.3.0. Add them to a ml group with uv.
|
|
Baseline Performance Assessment
Before implementing advanced models, establish your current baseline:
|
|
Implementation Guide
You will extend your existing pipeline by implementing support for advanced algorithms and optimization. Complete the following components in order:
Phase 1: Model Configuration Extension
First, update the configuration to support new model types and optimization parameters.
Configuration Updates
Update src/utils/config.py to include new model types and hyperparameter grids.
Reference Documentation: Scikit-learn Model Selection
Sections to Complete:
- Extend
MODEL_TYPESlist to include'xgboost'and'lightgbm' - Add
DEFAULT_PARAM_GRIDSdictionary with optimization parameters
|
|
Info
Hyperparameter Reference:
- n_estimators: Number of boosting stages (XGBoost docs)
- max_depth: Maximum tree depth (LightGBM docs)
- learning_rate: Step size shrinkage (Gradient Boosting explanation)
- subsample: Fraction of samples for tree building
- colsample_bytree: Fraction of features for tree building
Phase 2: ModelTrainer Extension
Extend the ModelTrainer class to support advanced algorithms while maintaining the existing interface.
Method Extension: create_model()
Purpose: Extend model factory to support XGBoost and LightGBM instances.
Reference Documentation:
|
|
Sections to Complete:
- Add import statements for XGBoost and LightGBM
- Extend the model creation logic with new cases for
'xgboost'and'lightgbm' - Configure appropriate default parameters (objective, random_state, etc.)
Details
Action Required: Implement the extended create_model() method in src/pipeline/model_trainer.py. Test your implementation with uv run python scripts/run_pipeline.py --model xgboost after completion.
Tip
XGBoost Configuration: Use objective='reg:squarederror' for regression tasks and set random_state=RANDOM_STATE for reproducibility. LightGBM should use objective='regression' and verbose=-1 to suppress training output.
Phase 3: Hyperparameter Optimization
Implement systematic hyperparameter optimization that respects geographic cross-validation constraints.
Method: hyperparameter_optimization_cv()
Purpose: Perform GridSearchCV with geographic cross-validation to find optimal hyperparameters while preventing data leakage.
Reference Documentation:
|
|
Key Implementation Details:
- Geographic Cross-Validation Setup: Use GroupKFold when groups are provided to respect city boundaries
- Scoring Configuration: Use
'neg_root_mean_squared_error'for consistent RMSE optimization - Parallel Processing: Set
n_jobs=-1for faster optimization - Verbose Output: Control verbosity based on logging level
Details
Action Required: Implement the hyperparameter optimization method in src/pipeline/evaluator.py. The method should configure GridSearchCV with GroupKFold strategy and return the best model with its parameters and score.
Warning
Important: GridSearchCV returns negative RMSE scores (because it maximizes scores). Remember to convert best_score = -grid_search.best_score_ to get positive RMSE values.
Phase 4: Pipeline Integration
Integrate optimization functionality into the main pipeline execution with user-controllable options.
Script Extension: run_pipeline.py
Purpose: Integrate hyperparameter optimization into the main pipeline execution using the existing TODO structure.
Sections to Complete:
The run_pipeline.py script already contains properly placed TODO sections for Workshop 3. You need to complete the existing TODO blocks that handle:
- Import Parameter Grids: Complete the existing import TODO for
DEFAULT_PARAM_GRIDS - Pipeline Logic: Implement the conditional optimization logic in Step 4’s existing TODO blocks
Pipeline Logic Implementation:
The optimization logic should follow this pattern in the existing TODO structure:
- No Optimization: Use standard cross-validation with default parameters
- Optimization Requested: Apply GridSearchCV with geographic folds, then evaluate optimized model
- No Parameter Grid: Fall back to standard cross-validation with warning message
Info
Important: The --optimize argument and logging enhancements are already implemented in the provided run_pipeline.py. Focus on completing the TODO sections for parameter grid imports and the optimization logic in Step 4.
Key Implementation Points:
- Use
DEFAULT_PARAM_GRIDS.get(args.model, {})to retrieve parameter grids - Check if parameter grid is empty and handle gracefully
- Apply the
hyperparameter_optimization_cv()method you implemented in the Evaluator - Ensure fallback to standard cross-validation when optimization fails
Details
Action Required: Complete the TODO sections in scripts/run_pipeline.py to integrate optimization functionality. Test with uv run python scripts/run_pipeline.py --model xgboost --optimize after completion.
Testing and Validation
Progressive Testing Strategy
Test each implementation phase incrementally to ensure stability:
|
|
Advanced Topics
Understanding Hyperparameter Grids
The default parameter grids are designed to balance exploration with computational efficiency:
Coarse-to-Fine Strategy:
- Initial Grid: Covers wide parameter ranges with few values
- Refined Grid: Can be narrowed based on initial results for production use
Key Parameters Explained:
- n_estimators: More trees generally improve performance but increase training time
- max_depth: Controls overfitting; deeper trees capture more complex patterns
- learning_rate: Lower values require more estimators but often achieve better performance
- subsample/colsample_bytree: Regularization parameters that prevent overfitting
Geographic Cross-Validation Benefits
Your implementation maintains geographic integrity during optimization:
|
|
Why This Matters:
- Data Leakage Prevention: Ensures model cannot memorize city-specific patterns
- Realistic Performance: Evaluates generalization to completely new locations
- Deployment Validity: Mirrors real-world scenario of predicting for new cities
Optimization Trade-offs
Understanding when to use optimization in production:
When to Optimize:
- Initial model development and research phases
- Periodic retraining with new data
- Model performance is critical for business outcomes
When to Skip Optimization:
- Real-time prediction requirements
- Computational resources are limited
- Model performance is already satisfactory
Slow Optimization Performance
To speed up hyperparameter search:
|
|
Conclusion
This workshop has extended your ML pipeline with advanced algorithms and systematic optimization capabilities. By completing this implementation, you have gained practical experience with:
- Advanced Algorithms: Integrating gradient boosting models (XGBoost, LightGBM) into existing pipelines
- Hyperparameter Optimization: Implementing GridSearchCV with geographic cross-validation constraints
- Production Considerations: Balancing model performance improvements with computational costs
- Architecture Extension: Maintaining backward compatibility while adding new functionality
The optimization techniques you’ve learned represent industry best practices for systematic model improvement. This approach ensures that performance gains are statistically valid and will generalize to new data.