4. Ensemble Methods & Boosting
Bagging and Random Forests: Decorrelating Decision Trees
Bagging, or Bootstrap Aggregating, is an ensemble meta-algorithm designed to improve the stability and accuracy of machine learning algorithms. It works by generating multiple bootstrap samples from the training dataset (sampling with replacement) and training an independent base estimator on each sample. For classification, the final prediction is determined by a majority vote; for regression, it is the average of all individual predictions.
The Random Forest algorithm builds directly on bagging by introducing feature subspace sampling. While standard bagging evaluates every available feature when looking for the best split point, Random Forest considers only a random subset of features at each node split. This further decorrelates the trees, making the overall average highly robust against noise and overfitting.
Key hyperparameters dictate how a Random Forest is trained in scikit-learn. These parameters can be customized based on requirements to trade off compute time against predictive variance reduction:
| Hyperparameter | Description |
|---|---|
| n_estimators | The total number of decision trees in the forest. More trees generally improve stability but increase computation. |
| max_features | The size of the random subset of features to consider at each node split (e.g., sqrt or log2). |
| bootstrap | Boolean indicating whether bootstrap samples are used when building trees. If False, the whole dataset is used. |
| oob_score | Whether to use out-of-bag samples to estimate the generalization score, serving as a built-in validation. |
import numpy as np from sklearn.datasets import make_classification, make_regression from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor # Generate simulated classification data X_c, y_c = make_classification(n_samples=200, n_features=10, random_state=42) # Fit a Random Forest Classifier with OOB validation rf_clf = RandomForestClassifier(n_estimators=100, max_features='sqrt', bootstrap=True, oob_score=True, random_state=42) rf_clf.fit(X_c, y_c) print(f"Classifier OOB Score: {rf_clf.oob_score_:.4f}") # Generate simulated regression data X_r, y_r = make_regression(n_samples=200, n_features=10, random_state=42) # Fit a Random Forest Regressor rf_reg = RandomForestRegressor(n_estimators=50, max_depth=5, bootstrap=True, oob_score=True, random_state=42) rf_reg.fit(X_r, y_r) print(f"Regressor OOB Score: {rf_reg.oob_score_:.4f}")
Sequential Boosting Frameworks: AdaBoost, Gradient Boosting, and HistGradientBoosting
Boosting is a sequential ensemble strategy where base learners are trained consecutively rather than in parallel. Each subsequent model attempts to correct the errors made by its predecessor. AdaBoost (Adaptive Boosting) achieves this by adjusting sample weights: samples that were incorrectly classified by the previous tree are assigned higher weights, forcing the next tree to focus on difficult instances.
Gradient Boosting generalizes boosting to arbitrary loss functions by fitting new trees directly to the pseudo-residuals (gradients of the loss function) of the current ensemble's predictions. Instead of adjusting sample weights, it trains a new regression tree to predict the gradient direction of the loss, updating the cumulative ensemble predictions sequentially.
Histogram-based Gradient Boosting (HistGradientBoostingClassifier/Regressor in scikit-learn) is a modern, highly optimized implementation inspired by LightGBM. It discretizes continuous numerical features into integer-valued bins (typically up to 256 bins). This reduces the complexity of finding splits from O(N log N) to O(N), speeding up training by orders of magnitude and natively supporting missing value imputation without preprocessing.
import numpy as np from sklearn.datasets import make_classification from sklearn.ensemble import AdaBoostClassifier, GradientBoostingClassifier, HistGradientBoostingClassifier from sklearn.model_selection import train_test_split # Prepare data X, y = make_classification(n_samples=500, n_features=15, random_state=42) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) # Instantiate boosting estimators ada = AdaBoostClassifier(n_estimators=50, random_state=42) gb = GradientBoostingClassifier(n_estimators=50, random_state=42) hgb = HistGradientBoostingClassifier(max_iter=50, random_state=42) # Train and print test accuracies for name, clf in [('AdaBoost', ada), ('Gradient Boosting', gb), ('Hist Gradient Boosting', hgb)]: clf.fit(X_train, y_train) acc = clf.score(X_test, y_test) print(f"{name} Test Accuracy: {acc:.4f}")
Hyperparameter Interplay and Optimization Strategies
Tuning hyperparameters in ensemble models requires understanding the core mathematical dynamics of bagging versus boosting. In bagging models like Random Forest, increasing n_estimators does not cause overfitting; it simply asymptotically reduces variance. Thus, you should set n_estimators as high as your computing budget permits.
In contrast, boosting is susceptible to overfitting if n_estimators is too large because the model continues to fit complex training noise. To prevent this, boosting models rely on learning_rate (or shrinkage), which scales down the step size of each new tree. The relationship is reciprocal: a lower learning rate requires a larger number of estimators to reach optimal performance, but often results in better generalization.
The depth of individual trees (max_depth) also differs dramatically. Random Forests typically use fully grown, deep decision trees ('max_depth=None') to minimize bias in each estimator, leaving the averaging process to reduce variance. Boosting models use shallow decision trees ('max_depth=3' to 'max_depth=5'), also called weak learners, to systematically control individual estimator variance while relying on the additive boosting sequence to reduce bias.
import numpy as np from sklearn.datasets import make_classification from sklearn.ensemble import GradientBoostingClassifier from sklearn.model_selection import validation_curve X, y = make_classification(n_samples=300, n_features=10, random_state=42) # Evaluate the effect of n_estimators at two different learning rates for lr in [0.01, 0.1]: gb = GradientBoostingClassifier(learning_rate=lr, random_state=42) train_scores, test_scores = validation_curve( gb, X, y, param_name="n_estimators", param_range=[10, 50, 100], cv=3, scoring="accuracy" ) print(f"Learning Rate: {lr}") print(f" Mean Train Accuracies: {np.mean(train_scores, axis=1).round(3)}") print(f" Mean Test Accuracies: {np.mean(test_scores, axis=1).round(3)}")
Model Interpretability: Feature Importances and Tree Inspections
Once an ensemble model is trained, it is essential to understand what features are driving its decisions. Tree-based ensembles expose a .feature_importances_ attribute, representing the Mean Decrease in Impurity (MDI). MDI measures the sum of all split criterion improvements across all nodes and all trees, weighted by the fraction of samples reaching those nodes.
However, MDI importances can be heavily biased towards continuous features or categorical features with high cardinality, as these features provide more split opportunities. To balance this bias, or to inspect the internal architecture of your models, you can programmatically access the constituent trees using the .estimators_ attribute in Random Forests and traditional Gradient Boosting models.
By traversing .estimators_, you can check diagnostic statistics of individual trees, such as their tree depths or number of leaves. This helps identify whether individual estimators are hitting the maximum depth boundary or if they are remaining under-grown due to sample size constraints.
max_depth limit, consider slightly expanding the depth or tuning min_samples_leaf to allow more flexible boundaries without overfitting.
import numpy as np from sklearn.datasets import make_classification from sklearn.ensemble import RandomForestClassifier X, y = make_classification(n_samples=400, n_features=8, random_state=42) rf = RandomForestClassifier(n_estimators=10, max_depth=6, random_state=42) rf.fit(X, y) # 1. Extract and display feature importances for idx, importance in enumerate(rf.feature_importances_): print(f"Feature {idx}: Importance = {importance:.4f}") # 2. Inspect the depth of each individual estimator tree depths = [estimator.get_depth() for estimator in rf.estimators_] print(f"Individual Tree Depths: {depths}") print(f"Average Depth: {np.mean(depths):.1f}")
Knowledge Check
Ready to test your understanding of 4. Ensemble Methods & Boosting?