Lesson 5 of 9
Hyperparameter Tuning for Tree Ensembles: Learning Rate, Tree Depth & Subsample
Tuning tree ensembles involves navigating a multi-dimensional hyperparameter landscape: Learning Rate (`learning_rate`), Tree Complexity (`max_depth`, `num_leaves`), Regularization (`reg_alpha` L1, `reg_lambda` L2), and Stochastic Sampling (`subsample`, `colsample_bytree`). Tuning these hyperparameters in the proper sequential hierarchy saves days of wasted compute time.
Systematic Hyperparameter Search Strategy
import numpy as np
import pandas as pd
from sklearn.model_selection import RandomizedSearchCV, StratifiedKFold
from sklearn.ensemble import HistGradientBoostingClassifier
from scipy.stats import uniform, randint
# Synthetic tabular classification dataset
np.random.seed(42)
X = np.random.randn(2000, 15)
y = (X[:, 0] * 2.0 - X[:, 1] * 1.5 + np.random.randn(2000) > 0).astype(int)
# Strategic search space based on production empirical best practices
param_distributions = {
'learning_rate': uniform(0.01, 0.19), # 0.01 to 0.20
'max_leaf_nodes': randint(15, 63), # 15 to 63 leaves
'min_samples_leaf': randint(10, 50), # Prevents leaf memorization
'l2_regularization': uniform(0.0, 5.0) # L2 leaf penalty
}
hgb = HistGradientBoostingClassifier(max_iter=100, random_state=42)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
search = RandomizedSearchCV(
estimator=hgb,
param_distributions=param_distributions,
n_iter=20, # 20 strategic random samples
scoring='roc_auc',
cv=cv,
random_state=42,
n_jobs=-1
)
search.fit(X, y)
print("=== OPTIMAL TREE ENSEMBLE HYPERPARAMETERS ===")
print(f"Best 5-Fold CV ROC-AUC: {search.best_score_:.4f}")
print("Optimal Configuration:")
for param, val in search.best_params_.items():
print(f" {param:20s}: {val:.4f}" if isinstance(val, float) else f" {param:20s}: {val}")Pro Tip: The Golden Sequence for Tuning GBDTs
Never grid search all hyperparameters at once. Follow this golden sequence: (1) Fix `learning_rate=0.1` and find the optimal number of trees using Early Stopping; (2) Tune tree architecture (`max_depth`, `num_leaves`, `min_samples_leaf`); (3) Tune stochastic sampling (`subsample`, `colsample_bytree`); (4) Tune regularization (`alpha`, `lambda`); (5) Cut `learning_rate` in half (e.g. 0.05) and double `n_estimators` for a final 1-2% accuracy boost.
MlHyperparameterTuning Visual Representation
Hands-On Challenge: Build an Optuna Tuning Loop
Write a Bayesian optimization script with `optuna` that tunes `n_estimators`, `learning_rate`, and `max_depth` on a validation fold, plotting the hyperparameter importance diagram.
Quick Quiz & Key Concept Checks
Common Pitfall: Tuning on the Final Test Dataset
Evaluating hyperparameter combinations against the test set causes hyperparameter overfitting: the chosen parameters are optimized to fit the test set's random idiosyncrasies. Use Nested Cross-Validation or a dedicated validation split.