Many mediocre models, one better model: under which conditions
An ensemble combines several models to obtain better predictions than each one. The intuition is that of the jury: ten people who err in different ways, put together, err less than each taken alone; but if they all err in the same way, the jury is useless. The two big families answer two different problems you have already met in the article on overfitting and underfitting. Bagging trains many complex models on different samples of the data and averages them: it reduces the variance. Boosting trains simple models one after the other, each on the errors of the previous ones: it mainly reduces the bias. Stacking finally lets another model decide how to weigh the predictions. The scikit-learn guide says the same thing in one line: bagging works best with strong and complex models, such as fully developed trees, boosting with weak models. The basics of trees are in article 3.
Six models compared on noisy data
The listing compares a single tree, bagging, random forest, AdaBoost, gradient boosting and its histogram variant on 1000 samples with 10% wrong labels, evaluated with a 5-fold cross-validation repeated three times (15 evaluations per model). The noise is deliberate: it is in difficult conditions that models set themselves apart. The random forest extends bagging with the random choice of variables at each split, which makes the trees less correlated with each other and therefore the average more effective. HistGradientBoostingClassifier is the scikit-learn implementation of boosting with trees, inspired by LightGBM according to the guide; it builds histograms of the variables and is therefore much faster on large datasets.
import numpy as np
from sklearn.datasets import make_classification
from sklearn.ensemble import (AdaBoostClassifier, BaggingClassifier, GradientBoostingClassifier,
HistGradientBoostingClassifier, RandomForestClassifier)
from sklearn.model_selection import RepeatedStratifiedKFold, cross_val_score
from sklearn.tree import DecisionTreeClassifier
# Noisy data: 10% of the labels are wrong, 6 variables out of 20 are informative
X, y = make_classification(n_samples=1000, n_features=20, n_informative=6, flip_y=0.10, random_state=0)
cv = RepeatedStratifiedKFold(n_splits=5, n_repeats=3, random_state=0)
modelli = {
"single tree": DecisionTreeClassifier(random_state=0),
"bagging (50 trees)": BaggingClassifier(estimator=DecisionTreeClassifier(), n_estimators=50, random_state=0),
"random forest (200)": RandomForestClassifier(n_estimators=200, random_state=0),
"AdaBoost (100 stumps)": AdaBoostClassifier(n_estimators=100, random_state=0),
"gradient boosting (100)": GradientBoostingClassifier(n_estimators=100, random_state=0),
"hist gradient boosting": HistGradientBoostingClassifier(random_state=0),
}
for nome, m in modelli.items():
s = cross_val_score(m, X, y, cv=cv)
print(f"{nome:24s} accuracy {s.mean():.3f} (standard deviation {s.std():.3f}, 15 evaluations)")
# Output:
# single tree accuracy 0.789 (standard deviation 0.026, 15 evaluations)
# bagging (50 trees) accuracy 0.855 (standard deviation 0.024, 15 evaluations)
# random forest (200) accuracy 0.862 (standard deviation 0.027, 15 evaluations)
# AdaBoost (100 stumps) accuracy 0.790 (standard deviation 0.027, 15 evaluations)
# gradient boosting (100) accuracy 0.851 (standard deviation 0.022, 15 evaluations)
# hist gradient boosting accuracy 0.863 (standard deviation 0.021, 15 evaluations)
The single tree obtains 0.789; bagging with 50 trees jumps to 0.855 and the random forest to 0.862: the average alone removed the variance. Gradient boosting reaches 0.851 and its histogram version 0.863, level with the forest. The standard deviations (0.021-0.027) are larger than the differences among forest, boosting and histogram boosting: they are three equivalent models on this data, and whoever declares a winner is reading noise. The surprising figure is AdaBoost, at 0.790: practically at the level of the single tree. AdaBoost increases the weight of the wrong samples at every round, and with 10% wrong labels it ends up concentrating precisely on those, chasing the noise; it is a known weakness of the algorithm, and here you see it in numbers. On clean data the comparison would be different, so always report under which conditions you measured.
What gradient boosting really does: building it by hand
Gradient boosting is less mysterious than it is made out to be. You start from a constant prediction, the mean. You compute the residuals, that is how much the prediction is off for each example, and train a small tree to predict those residuals. You add a fraction of that tree (the learning rate) to the prediction, recompute the residuals and repeat. For the squared error the residual coincides with the negative gradient of the cost function, hence the name: each tree is a gradient descent step in the space of functions, as in the article on regression it was in the space of weights. The listing builds it with 100 trees of depth 2 on a noisy sine curve, and compares it with GradientBoostingRegressor.
import numpy as np
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.tree import DecisionTreeRegressor
rng = np.random.default_rng(0)
X = rng.uniform(0, 6, (200, 1))
y = np.sin(X[:, 0]) + rng.normal(0, 0.2, 200)
LR, N = 0.1, 100
previsione = np.full_like(y, y.mean()) # first model: the mean
alberi = []
for i in range(N):
residuo = y - previsione # for the squared error the negative gradient is the residual
albero = DecisionTreeRegressor(max_depth=2, criterion="friedman_mse", random_state=0).fit(X, residuo)
alberi.append(albero)
previsione = previsione + LR * albero.predict(X)
if i + 1 in (1, 10, 50, 100):
print(f"after {i + 1:3d} trees: training MSE {np.mean((y - previsione) ** 2):.4f}")
sk = GradientBoostingRegressor(n_estimators=N, learning_rate=LR, max_depth=2, random_state=0).fit(X, y)
print("maximum difference with GradientBoostingRegressor:", float(np.abs(sk.predict(X) - previsione).max()))
# Output:
# after 1 trees: training MSE 0.4458
# after 10 trees: training MSE 0.1216
# after 50 trees: training MSE 0.0317
# after 100 trees: training MSE 0.0268
# maximum difference with GradientBoostingRegressor: 0.0
The training error falls from 0.4458 after one tree to 0.1216 after ten, 0.0317 after fifty and 0.0268 after a hundred: the first trees do the bulk of the work, the later ones refine. The last line is the proof: the maximum difference between my predictions and those of GradientBoostingRegressor is 0.0, so the hand-written loop and the library compute the same thing. This explains two pieces of advice you will hear repeated: the trees must be small (here depth 2), because each one must correct a little and not alone, and training is sequential, so it cannot be parallelized over trees as in bagging. It also explains why the training error keeps falling: boosting can overfit if you do not stop it.
Learning rate and number of trees must be chosen together
A small learning rate makes the model advance in cautious steps and requires more trees to reach the same point. The listing tries three values on data with 15% wrong labels; for each value it finds, on a validation set, the number of trees that gives the best accuracy (with staged_predict, which returns the predictions after each tree) and measures the test set once, at that point. The procedure is the early stopping described in the previous article.
import numpy as np
from sklearn.datasets import make_classification
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.model_selection import train_test_split
X, y = make_classification(n_samples=2000, n_features=20, n_informative=5, flip_y=0.15, random_state=1)
X_rest, X_test, y_rest, y_test = train_test_split(X, y, test_size=0.3, random_state=1)
X_train, X_val, y_train, y_val = train_test_split(X_rest, y_rest, test_size=0.25, random_state=1)
print("learning_rate best trees (validation) validation test")
for lr in (1.0, 0.1, 0.02):
m = GradientBoostingClassifier(n_estimators=400, learning_rate=lr, max_depth=3, random_state=0).fit(X_train, y_train)
va = np.array([np.mean(p == y_val) for p in m.staged_predict(X_val)])
k = int(np.argmax(va))
te = np.mean(list(m.staged_predict(X_test))[k] == y_test)
print(f"{lr:13} {k + 1:28d} {va[k]:11.3f} {te:.3f}")
# Output:
# learning_rate best trees (validation) validation test
# 1.0 128 0.777 0.750
# 0.1 24 0.794 0.770
# 0.02 133 0.783 0.768
With learning rate 1.0 the model takes enormous steps: the best number of trees is 128 but the test score stays at 0.750. With 0.1 validation is higher and it is enough to stop at 24 trees, with a test score of 0.770. With 0.02 you need 133 trees to reach 0.768. The advantage of a low learning rate, in this test, is small: 0.770 against 0.768 is one or two examples out of 600 test samples, therefore indistinguishable. What is clear is the poor choice of 1.0. The practical rule that follows is to set a moderate learning rate (0.05-0.1) and let early stopping establish how many trees are needed, instead of guessing the number.
Voting and stacking: combining different models
Voting combines models of different types. With hard voting each model votes for a class and the majority wins; with soft voting the probability is averaged, and whoever is confident counts more. Stacking adds a level: the predictions of the base models, obtained with an internal cross-validation so as not to use predictions made on the data the model was trained on, become the variables of a final model. For them to work, the models must err in different ways: a forest, a boosting, an SVM and a logistic regression are different families. The listing compares them on the breast cancer dataset.
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import GradientBoostingClassifier, RandomForestClassifier, StackingClassifier, VotingClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import RepeatedStratifiedKFold, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
X, y = load_breast_cancer(return_X_y=True)
rf = RandomForestClassifier(n_estimators=100, random_state=0)
gb = GradientBoostingClassifier(random_state=0)
svm = make_pipeline(StandardScaler(), SVC(probability=True, random_state=0))
lr = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
base = [("rf", rf), ("gb", gb), ("svm", svm), ("lr", lr)]
modelli = {
"random forest": rf, "gradient boosting": gb, "SVM": svm, "logistic regression": lr,
"voting hard": VotingClassifier(base, voting="hard"),
"voting soft": VotingClassifier(base, voting="soft"),
"stacking": StackingClassifier(base, final_estimator=LogisticRegression(max_iter=1000), cv=5),
}
cv = RepeatedStratifiedKFold(n_splits=5, n_repeats=2, random_state=0)
for nome, m in modelli.items():
s = cross_val_score(m, X, y, cv=cv)
print(f"{nome:22s} accuracy {s.mean():.3f} (standard deviation {s.std():.3f})")
# Output:
# random forest accuracy 0.962 (standard deviation 0.013)
# gradient boosting accuracy 0.963 (standard deviation 0.015)
# SVM accuracy 0.974 (standard deviation 0.013)
# logistic regression accuracy 0.975 (standard deviation 0.018)
# voting hard accuracy 0.974 (standard deviation 0.015)
# voting soft accuracy 0.975 (standard deviation 0.012)
# stacking accuracy 0.979 (standard deviation 0.011)
The single models range from 0.962 (forest) to 0.975 (logistic regression); soft voting obtains 0.975 and stacking 0.979. But the standard deviation is between 0.011 and 0.018, so stacking is not provably better than logistic regression alone: the difference is 0.004 with 10 evaluations. On this dataset, the simple models are already close to the maximum, and combining complicates without giving much. The most useful result is another: no ensemble got worse, and the gain from an ensemble is larger when the base models are different and none dominates. Before adopting stacking in production ask yourself whether the 0.4% is worth the cost of training, versioning and serving four models plus a meta-model.
XGBoost, LightGBM and CatBoost: what they add
They are specialized implementations of gradient boosting with trees, and they remain the usual choice for tabular data, but they are not part of scikit-learn. XGBoost (Chen and Guestrin, 2016) exposes L1 and L2 penalties on the weights (parameters alpha and lambda in the documentation) and proposes an algorithm aware of sparse data; LightGBM (Ke et al., 2017) speeds up training on large data with two techniques of sampling and bundling of variables; CatBoost (Prokhorenkova et al.) is designed for categorical variables. On this machine the three packages are not installed and I did not install them, so the block that follows is a schema to adapt, not executed: the parameters are those of the XGBoost documentation (I checked the names and meaning of subsample, colsample_bytree, reg_alpha and reg_lambda), but I have no figure to report. To test the same principle I used in the previous listings HistGradientBoostingClassifier, which is the closest to LightGBM inside scikit-learn.
from xgboost import XGBClassifier
from sklearn.model_selection import cross_val_score
xgb = XGBClassifier(
n_estimators=200,
learning_rate=0.05,
max_depth=5,
subsample=0.8, # fraction of rows per tree
colsample_bytree=0.8, # fraction of columns per tree
reg_alpha=0.1, # L1 penalty on the leaf weights
reg_lambda=1.0, # L2 penalty on the leaf weights
eval_metric="logloss",
random_state=0,
)
scores = cross_val_score(xgb, X, y, cv=5) # X, y: your matrix and your labels
The lines that matter are those that regulate capacity: subsample and colsample_bytree use only a part of the rows and columns per tree (like bagging, to reduce variance), reg_alpha and reg_lambda are the L1 and L2 penalties, max_depth keeps the trees small. If you remove the regularization and raise n_estimators without validation, you get the same overfitting you saw above. Adapt X and y to your data before running it.
Searching hyperparameters without fooling yourself
Ensembles have many hyperparameters and a full grid search costs too much: RandomizedSearchCV draws a fixed number of combinations from distributions (for example logarithmic ones for the learning rate). The constraint is the one already seen: the search sees only the training set, and the final score is measured on the test set. The listing searches among 15 combinations of HistGradientBoostingClassifier and compares with the default parameters.
from scipy.stats import loguniform
from sklearn.datasets import make_classification
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.model_selection import RandomizedSearchCV, train_test_split
X, y = make_classification(n_samples=2000, n_features=20, n_informative=5, flip_y=0.1, random_state=2)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=2)
spazio = {
"learning_rate": loguniform(0.01, 0.3),
"max_leaf_nodes": [4, 8, 16, 31],
"min_samples_leaf": [10, 20, 40],
"l2_regularization": loguniform(1e-3, 10),
}
ricerca = RandomizedSearchCV(HistGradientBoostingClassifier(max_iter=200, early_stopping=False, random_state=0), spazio,
n_iter=15, cv=5, random_state=0).fit(X_train, y_train)
base = HistGradientBoostingClassifier(max_iter=200, early_stopping=False, random_state=0).fit(X_train, y_train)
print("best parameters:", {k: (round(float(v), 3) if k in ('learning_rate', 'l2_regularization') else v) for k, v in ricerca.best_params_.items()})
print(f"cross-validation on the training set (optimistic): {ricerca.best_score_:.3f}")
print(f"test with searched parameters: {ricerca.score(X_test, y_test):.3f} test with default parameters: {base.score(X_test, y_test):.3f}")
# Output:
# best parameters: {'l2_regularization': 0.312, 'learning_rate': 0.037, 'max_leaf_nodes': 31, 'min_samples_leaf': 40}
# cross-validation on the training set (optimistic): 0.871
# test with searched parameters: 0.888 test with default parameters: 0.877
The search chooses a learning rate of about 0.037, trees of up to 31 leaves (the maximum of the space I gave it), a minimum of 40 examples per leaf and an L2 regularization of about 0.31. The cross-validation on the training set declares 0.871, which is optimistic because it is the maximum of 15 attempts; the test gives 0.888 with the searched parameters and 0.877 with the default ones. A gain of one point on 600 test examples (six or seven samples) is plausible but not proof: the search reduced the risk of overfitting more than it pushed performance. If your gain after tuning is of this size, the time is better spent improving the data, as in Feature Engineering.
What you can do now
You can tell bagging and boosting apart by the problem they solve, variance or bias, and you can build a gradient boosting by hand checking it against the library. You know that AdaBoost suffers from wrong labels, that learning rate and number of trees are chosen together with a validation set, and that voting and stacking pay off only with different models. You can search hyperparameters without contaminating the test set. The next article changes ground: recommendation systems.
To compare boosting with a margin model see Support Vector Machines; for the idea of starting from weights already learned, transfer learning; for the comparison in production, the end-to-end pipeline.
Frequently asked questions
What is the difference between bagging and boosting?
Bagging trains many complex models in parallel on random samples of the data and averages them, reducing variance; boosting trains simple models in sequence, each on the errors of the previous ones, mainly reducing bias.
Why does AdaBoost do badly with wrong labels?
Because it increases the weight of misclassified samples at every round, and wrong labels are always misclassified: the model ends up concentrating on them. In the example with 10% noise it gets 0.790, like a single tree.
Is stacking worth it compared with a single model?
Only if the base models are different and the difference exceeds the variability of the evaluation: in the example stacking gets 0.979 against 0.975 for logistic regression alone, with standard deviations of 0.011-0.018.
Sources
- scikit-learn User Guide: Ensembles - bagging, random forest, gradient boosting, HistGradientBoosting, voting and stacking, consulted on 2026-11-12
- Friedman, Greedy function approximation: a gradient boosting machine, Annals of Statistics 29 (2001) - the original reference of the method, cited by the scikit-learn guide (the page only exposes the bibliographic data), consulted on 2026-11-12
- Chen and Guestrin, XGBoost: A Scalable Tree Boosting System (2016) - the algorithm aware of sparse data, consulted on 2026-11-12
- XGBoost Parameters, official documentation - subsample, colsample_bytree, alpha and lambda, consulted on 2026-11-12
- Ke et al., LightGBM: A Highly Efficient Gradient Boosting Decision Tree, NeurIPS 2017 - GOSS and EFB, consulted on 2026-11-12
- Prokhorenkova et al., CatBoost: unbiased boosting with categorical features (2017) - the treatment of categorical variables, consulted on 2026-11-12
Commenti
Caricamento commenti...
Sign in to comment