• Ensemble Learning: Bagging, Boosting and Stacking Explained With Python

    Ensemble Learning Bagging, Boosting and Stacking Explained With Python

    Ensemble learning combines many models into one that predicts better than any of its members. A single decision tree is easy to build and easy to fool; three hundred trees trained in the right way win most competitions on tabular data. The three classic ways to build an ensemble are bagging, boosting and stacking, and they work for different reasons.

    This guide explains how each method works, what bias and variance have to do with it, how random forest, AdaBoost, gradient boosting, XGBoost, LightGBM and CatBoost fit in, and when to use which. We also compared ten models on 48,842 people from the US census with scikit-learn, from a single tree to stacking, and measured how much each ensemble adds.

    Key takeaways

    • Ensemble learning trains several models, called base or weak learners, and combines their predictions by voting, averaging or a second model.
    • Bagging reduces variance. It trains strong, unstable models such as deep trees in parallel on random bootstrap samples and averages them. Random forest is bagging plus random feature selection.
    • Boosting reduces bias. It trains weak models such as shallow trees one after another, each focusing on the errors of the previous ones. AdaBoost, gradient boosting, XGBoost, LightGBM and CatBoost are boosting methods.
    • Stacking trains different kinds of models and a meta-model that learns how to combine them.
    • In our test, one decision tree reached 82.7% accuracy, bagging 85.3%, random forest 86.6% and gradient boosting 87.5%. Stacking three strong models gave 87.4%, no better than gradient boosting alone.

    What is ensemble learning?

    Ensemble learning is a machine learning technique that trains several models for the same task and combines their outputs into a single prediction. For classification the models vote or average their probabilities; for regression their numbers are averaged. The models inside an ensemble are called base learners, and when each of them is only slightly better than guessing, weak learners.

    The idea is the same as asking several experts instead of one. Each expert makes mistakes, but if the mistakes are different, they partly cancel out. Two conditions matter: each member must be better than chance, and members must make different errors. A hundred copies of the same model are no better than one.

    Ensembles are not a niche trick. Random forests and gradient-boosted trees are the default models for tabular data in industry: credit scoring, fraud detection, demand forecasting, ranking search results and ads. Gradient boosting libraries such as XGBoost, LightGBM and CatBoost appear in most winning solutions of tabular competitions on Kaggle, and many winners average or stack several such models at the end. For a gentle start, our Kaggle Titanic tutorial compares a single tree, a random forest and gradient boosting on 891 passengers.

    There are three main families, and they differ in how the members are trained and combined:

    • Bagging trains the same kind of model many times in parallel on random samples of the data and averages the results.
    • Boosting trains models one after another, each one correcting the mistakes of the ensemble so far.
    • Stacking trains different kinds of models and then a meta-model that learns how much to trust each of them.

    Why ensembles work: bias and variance

    The error of a model on new data has three parts: bias, variance and irreducible noise. Bias is the error that comes from wrong assumptions: a model that is too simple, such as a straight line through curved data, misses the pattern however much data it sees. This is underfitting. Variance is the error that comes from sensitivity to the particular training set: a model that is too flexible, such as a deep decision tree, learns the noise, and a slightly different sample gives a very different model. This is overfitting.

    Bias-variance tradeoff: bias falls and variance rises with model complexity, test error is lowest at the optimal balance between underfitting and overfitting
    The bias-variance tradeoff: simple models underfit, complex models overfit

    Making a single model more complex lowers bias but raises variance, which is the bias-variance tradeoff. Ensembles escape part of this tradeoff, in two different directions:

    • Averaging reduces variance. If you average N models, each with variance σ², and their errors are independent, the variance of the average is σ²/N. Real models trained on the same data are correlated; with correlation ρ the variance is ρσ² + (1 − ρ)σ²/N. Adding models drives the second term towards zero, and the first term explains why bagging tries to make its members as different as possible.
    • Sequential correction reduces bias. A model that is too simple to fit the data on its own, such as a tree with one split, can become very flexible when hundreds of such models are added up, each one fitted to what the previous ones got wrong.

    This explains the choice of base learners. Bagging uses models with low bias and high variance, typically deep trees, and averages away the variance. Boosting uses models with high bias and low variance, typically shallow trees, and adds them up to remove the bias.

    Combining weak learners: averaging low-bias high-variance models reduces variance, composing high-bias low-variance models reduces bias
    Averaging low-bias models reduces variance (bagging); composing high-bias models reduces bias (boosting)

    Bagging and random forest

    Bagging, short for bootstrap aggregating, was proposed by Leo Breiman in 1996. It is built on the bootstrap, a statistical technique for creating many data sets from one: draw rows at random with replacement until the new sample is as large as the original. Some rows appear twice or more, others not at all; on average a bootstrap sample contains about 63.2% of the distinct rows, and the remaining 36.8% are left out.

    Bootstrap: bootstrap samples drawn from the initial dataset by sampling with replacement
    Bootstrap samples are drawn from the data with replacement, so some rows repeat and others are left out

    The bagging algorithm is short:

    1. Draw B bootstrap samples from the training data, for example B = 300.
    2. Train one model on each sample, independently and in parallel.
    3. To predict, let the models vote (classification) or average their outputs (regression). In practice, averaging predicted probabilities usually works slightly better than counting votes.
    Bagging: weak learners are fitted on L bootstrap samples of the initial dataset and their predictions are aggregated
    Bagging: one model per bootstrap sample, predictions averaged

    Because every model sees a different sample, the models are different, and averaging cancels much of their variance. Bagging works best with unstable models whose predictions change a lot when the data changes: fully grown decision trees are the standard choice. With stable models such as linear regression or k-nearest neighbours it barely helps.

    The rows that a model did not see are a free validation set. The out-of-bag (OOB) score predicts each training row using only the models that left it out, which gives an estimate of test accuracy without a separate hold-out set. In scikit-learn, pass oob_score=True to BaggingClassifier or RandomForestClassifier.

    Random forest

    Trees trained on bootstrap samples of the same data are still quite similar: if one feature is very strong, nearly every tree splits on it first. Random forest, introduced by Breiman in 2001, adds a second source of randomness: at every split, a tree may choose only among a random subset of the features, by default the square root of their number for classification. This lowers the correlation ρ between trees, so averaging removes more variance.

    Random forest: each tree is trained on a bootstrap sample and a random subset of features, and the trees are averaged
    Random forest samples both rows and features, which makes the trees more different

    Random forests are popular because they need almost no tuning: the default settings usually work well, the trees can be trained in parallel, adding more trees never makes the model overfit (it only stops helping), and the forest reports feature importance. Their weaknesses are size and speed at prediction time, and a ceiling on accuracy that gradient boosting usually beats on large tabular data sets. A related method, Extra Trees (extremely randomized trees), also picks split thresholds at random, which makes it even faster and the trees even more different.

    Boosting: AdaBoost, gradient boosting, XGBoost

    Boosting builds the ensemble step by step. Each new model is trained to fix what the current ensemble gets wrong, and the final prediction is a weighted sum of all models. Because each step depends on the previous one, boosting cannot be parallelised across models the way bagging can, although modern libraries parallelise the work inside each tree.

    Boosting: weak learners are trained sequentially, each one on a dataset updated to focus on the errors of the previous ones
    Boosting trains models one after another, each one focusing on what the ensemble still gets wrong

    AdaBoost

    AdaBoost (adaptive boosting), published by Yoav Freund and Robert Schapire in 1995, was the first practical boosting algorithm. It keeps a weight for every training example:

    1. Start with equal weights and train a weak learner, typically a decision stump, a tree with a single split.
    2. Compute its weighted error and give the learner a say in the final vote: the lower the error, the larger its weight.
    3. Increase the weights of the examples it misclassified and decrease the others, so the next learner concentrates on the hard cases.
    4. Repeat for a fixed number of rounds; predict with the weighted vote of all learners.
    AdaBoost: misclassified observations get higher weights before the next weak learner is trained, and learners are combined with weights
    AdaBoost reweights the training examples after each round

    AdaBoost is simple and often surprisingly accurate, but because it pushes ever more weight onto misclassified examples, it is sensitive to noisy labels and outliers.

    Gradient boosting

    Gradient boosting, formulated by Jerome Friedman in 1999 to 2001, generalises the idea to any differentiable loss function. Instead of reweighting examples, each new tree is fitted to the negative gradient of the loss with respect to the current predictions; for squared error, that is simply the residuals, the differences between targets and predictions. The tree’s output is multiplied by a small learning rate, such as 0.1, and added to the model. A low learning rate with many trees usually generalises better than a high rate with few. Our gradient boosting guide walks through the algorithm step by step with code.

    Three libraries turned gradient boosting into the standard tool for tabular data:

    • XGBoost (2014) added regularisation of the trees, second-order gradients, efficient handling of missing values and fast parallel training. It made gradient boosting the default winning method on Kaggle in the mid-2010s.
    • LightGBM (Microsoft, 2017) bins feature values into histograms and grows trees leaf by leaf, which makes it much faster on large data sets.
    • CatBoost (Yandex, 2017) handles categorical features natively and uses ordered boosting to reduce overfitting; it often works well with default settings.

    scikit-learn has its own fast implementation, HistGradientBoostingClassifier, which is inspired by LightGBM and is usually a better choice than the older GradientBoostingClassifier for anything beyond small data sets.

    Gradient boosting: each new weak learner is fitted to the pseudo-residuals of the current ensemble and added with a small step
    Gradient boosting fits each new model to the remaining errors (pseudo-residuals) of the ensemble

    Bagging vs boosting

    Bagging and boosting are both ways to combine many models of the same type, usually decision trees, but they attack different parts of the error and behave differently in practice:

    Bagging Boosting
    Main goal Reduce variance Reduce bias (and variance)
    Training Parallel, models are independent Sequential, each model depends on the previous ones
    Data for each model Random bootstrap sample All data, with weights or residuals that change each round
    Typical base learner Deep, fully grown trees Shallow trees or stumps
    Combination Equal vote or plain average Weighted sum
    More models Never hurts, accuracy plateaus Can overfit; use a learning rate and early stopping
    Noisy labels Robust More sensitive, especially AdaBoost
    Tuning Little needed Learning rate, number and depth of trees matter
    Examples Bagged trees, random forest, Extra Trees AdaBoost, gradient boosting, XGBoost, LightGBM, CatBoost

    A simple rule: if a single model overfits, bagging helps; if it underfits, boosting helps. On most tabular problems a well-tuned gradient boosting model is a little more accurate than a random forest, while the forest is easier to get right on the first try.

    Stacking and voting

    Bagging and boosting usually combine models of one kind. Stacking, or stacked generalisation, introduced by David Wolpert in 1992, combines models of different kinds, for example a random forest, a gradient boosting model and a logistic regression, and trains a meta-model to combine their predictions.

    Stacking: several different base models are trained on the data and a meta-model learns to combine their predictions
    Stacking: a meta-model learns how to combine the predictions of different base models

    The meta-model must not learn from predictions that the base models made on their own training data, because those are too optimistic. Stacking therefore uses cross-validation: the training set is split into k folds, each base model is trained on k − 1 folds and predicts the remaining one, and these out-of-fold predictions become the training features of the meta-model. Then the base models are retrained on all the data. In scikit-learn, StackingClassifier and StackingRegressor do this automatically. A simple meta-model, such as logistic or linear regression, is usually best. Stacking can have several levels, but each level adds training time and risk of overfitting for smaller gains.

    Voting is the simplest way to combine different models: no meta-model, just a majority vote (hard voting) or the average of predicted probabilities (soft voting). It is fast and hard to overfit, and it works well when the models are about equally good. Blending is a cheaper variant of stacking that trains the meta-model on a single hold-out set instead of cross-validated predictions.

    Combining models helps most when they are accurate and make different errors. If one model is clearly better than the rest and the others are similar to it, stacking adds little, as our experiment shows.

    Ensemble methods in Python: an experiment

    To see what each method adds, we compared single models with bagging, random forest, AdaBoost, gradient boosting, voting and stacking on the UCI Adult data set: 48,842 records from the 1994 US census, with 12 columns such as age, education, occupation, hours worked per week and capital gains. The task is to predict whether a person earns more than $50,000 a year, which is true for 23.9% of them. We trained on 75% of the data and measured accuracy and ROC AUC (how well the model ranks people by probability) on the remaining 12,211 records.

    The code needs pandas, NumPy and scikit-learn (we used scikit-learn 1.9). Download the Adult data set from the UCI Machine Learning Repository. It comes as two files, adult.data and adult.test; join them into one CSV without a header, data/adult.csv, with all 48,842 rows, after removing the first line of adult.test, the spaces after commas and the trailing dot in its labels. Missing values, marked with “?”, become a separate category. The script runs in about three minutes on a two-core machine.

    import time
    
    import numpy as np
    import pandas as pd
    from sklearn.compose import make_column_transformer
    from sklearn.ensemble import (AdaBoostClassifier, BaggingClassifier, GradientBoostingClassifier,
                                  HistGradientBoostingClassifier, RandomForestClassifier, StackingClassifier,
                                  VotingClassifier)
    from sklearn.linear_model import LogisticRegression
    from sklearn.metrics import accuracy_score, roc_auc_score
    from sklearn.model_selection import train_test_split
    from sklearn.preprocessing import OneHotEncoder, StandardScaler
    from sklearn.tree import DecisionTreeClassifier
    
    # 1. Data: UCI Adult (US census, 1994). Task: does a person earn more than $50,000 a year?
    cols = ["age", "workclass", "fnlwgt", "education", "education_num", "marital_status", "occupation",
            "relationship", "race", "sex", "capital_gain", "capital_loss", "hours_per_week", "country", "income"]
    df = pd.read_csv("data/adult.csv", names=cols, na_values="?").drop(columns=["fnlwgt", "education"])
    y = (df.pop("income") == ">50K").astype(int)
    categorical = df.select_dtypes(exclude="number").columns.tolist()
    numeric = df.select_dtypes("number").columns.tolist()
    print(f"{len(df):,} people, {y.mean():.1%} earn more than $50K, {len(categorical)} categorical and {len(numeric)} numeric columns")
    
    prep = make_column_transformer((OneHotEncoder(handle_unknown="ignore", sparse_output=False), categorical),
                                   (StandardScaler(), numeric))
    X = prep.fit_transform(df)                       # learns only category lists and column means, never the target
    X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.25, stratify=y, random_state=0)
    
    # 2. One model vs ensembles of many
    tree = lambda depth=None: DecisionTreeClassifier(max_depth=depth, random_state=0)
    models = {
        "Logistic regression": LogisticRegression(max_iter=2000),
        "Decision stump (depth 1)": tree(1),
        "Decision tree (no depth limit)": tree(),
        "Bagging (300 deep trees)": BaggingClassifier(tree(), n_estimators=300, n_jobs=-1, random_state=0),
        "Random forest (300 trees)": RandomForestClassifier(300, min_samples_leaf=2, n_jobs=-1, random_state=0),
        "AdaBoost (300 stumps)": AdaBoostClassifier(tree(1), n_estimators=300, random_state=0),
        "Gradient boosting (300 trees)": GradientBoostingClassifier(n_estimators=300, max_depth=3, random_state=0),
        "HistGradientBoosting": HistGradientBoostingClassifier(max_iter=300, learning_rate=0.1, random_state=0),
    }
    base = [("rf", models["Random forest (300 trees)"]), ("hgb", models["HistGradientBoosting"]),
            ("lr", models["Logistic regression"])]
    models["Soft voting (forest + boosting + logistic)"] = VotingClassifier(base, voting="soft")
    models["Stacking (forest + boosting + logistic)"] = StackingClassifier(
        base, final_estimator=LogisticRegression(), cv=5)
    
    for name, model in models.items():
        start = time.time()
        model.fit(X_tr, y_tr)
        proba = model.predict_proba(X_te)[:, 1]
        print(f"{name:42s} accuracy {accuracy_score(y_te, proba > 0.5):.3f}  ROC AUC {roc_auc_score(y_te, proba):.3f}"
              f"  {time.time() - start:5.1f} s")
    
    # 3. How accuracy grows with the number of models in the ensemble
    steps = [1, 5, 10, 25, 50, 100, 200, 300]
    def staged(model):                               # boosting: predictions after each added tree
        preds = list(model.staged_predict(X_te))
        return [accuracy_score(y_te, preds[n - 1]) for n in steps]
    def averaged(model):                             # bagging and forests: average the first n trees
        votes = np.cumsum([est.predict_proba(X_te)[:, 1] for est in model.estimators_], axis=0)
        return [accuracy_score(y_te, votes[n - 1] / n > 0.5) for n in steps]
    curves = {"Bagging": averaged(models["Bagging (300 deep trees)"]),
              "Random forest": averaged(models["Random forest (300 trees)"]),
              "AdaBoost": staged(models["AdaBoost (300 stumps)"]),
              "Gradient boosting": staged(models["Gradient boosting (300 trees)"])}
    print("models in ensemble:  " + "  ".join(f"{n:>5d}" for n in steps))
    for name, accs in curves.items():
        print(f"{name:18s}   " + "  ".join(f"{a:.3f}" for a in accs))
    48,842 people, 23.9% earn more than $50K, 7 categorical and 5 numeric columns
    Logistic regression                        accuracy 0.854  ROC AUC 0.908    0.7 s
    Decision stump (depth 1)                   accuracy 0.761  ROC AUC 0.764    0.1 s
    Decision tree (no depth limit)             accuracy 0.827  ROC AUC 0.782    0.3 s
    Bagging (300 deep trees)                   accuracy 0.853  ROC AUC 0.899   40.7 s
    Random forest (300 trees)                  accuracy 0.866  ROC AUC 0.920    5.5 s
    AdaBoost (300 stumps)                      accuracy 0.857  ROC AUC 0.913   18.5 s
    Gradient boosting (300 trees)              accuracy 0.875  ROC AUC 0.928   34.5 s
    HistGradientBoosting                       accuracy 0.875  ROC AUC 0.930    1.8 s
    Soft voting (forest + boosting + logistic) accuracy 0.873  ROC AUC 0.924    7.3 s
    Stacking (forest + boosting + logistic)    accuracy 0.874  ROC AUC 0.929   40.4 s
    models in ensemble:      1      5     10     25     50    100    200    300
    Bagging              0.820  0.842  0.846  0.849  0.852  0.851  0.852  0.853
    Random forest        0.833  0.860  0.863  0.866  0.866  0.865  0.866  0.866
    AdaBoost             0.761  0.836  0.840  0.847  0.852  0.856  0.857  0.857
    Gradient boosting    0.761  0.805  0.847  0.855  0.863  0.868  0.874  0.875
    Test accuracy on UCI Adult: decision tree 82.7%, bagging 85.3%, random forest 86.6%, AdaBoost 85.7%, gradient boosting 87.5%, voting 87.3%, stacking 87.4%, and accuracy versus number of models
    One tree: 82.7%. Random forest: 86.6%. Gradient boosting: 87.5%. Combining strong models added nothing on this data

    What the numbers show:

    • One deep tree overfits, many deep trees do not. A single unlimited tree reached 82.7% accuracy and a poor ROC AUC of 0.782, below plain logistic regression (85.4%). Averaging 300 such trees on bootstrap samples lifted accuracy to 85.3% and ROC AUC to 0.899: this is bagging removing variance.
    • Random feature selection helps bagging. The random forest, which also samples features at every split, reached 86.6% and 0.920, and trained about seven times faster than plain bagging because each split looks at fewer features.
    • Boosting turns a useless model into a strong one. A single stump split people into married and not married, but both groups still had more people earning $50K or less, so it predicted that for everyone: 76.1%, the share of the majority class. AdaBoost with 300 stumps reached 85.7%: this is boosting removing bias.
    • Gradient boosting was the most accurate single method at 87.5% and ROC AUC 0.928 to 0.930. scikit-learn’s histogram-based version gave the same accuracy in under 2 seconds instead of 35.
    • Combining strong models added nothing here. Soft voting reached 87.3% (ROC AUC 0.924) and stacking 87.4%, while costing the training time of all three models. Gradient boosting already captured almost everything the forest and the logistic regression knew.
    • Bagging plateaus, boosting keeps learning. Bagging and random forest got nearly all their gain from the first 25 to 50 trees. AdaBoost and gradient boosting were still improving at 300 trees; with more trees or a tuned learning rate they would need early stopping to avoid overfitting.

    Timings are from a two-core cloud machine and will differ on yours, but the ranking of the methods is typical for tabular data of this size.

    Which ensemble method to choose

    • Start with gradient boosting for tabular data: scikit-learn’s HistGradientBoostingClassifier, LightGBM, XGBoost or CatBoost. Use early stopping on a validation set and tune the learning rate, number of trees and tree depth. CatBoost is a good choice when there are many categorical columns.
    • Use a random forest when you want a strong result with almost no tuning, a built-in validation estimate from out-of-bag predictions, or a robust model for noisy labels.
    • Use bagging with base models other than trees when one model is accurate but unstable; for trees, a random forest is almost always better than plain bagging.
    • Use voting or stacking at the end, when you already have several good and different models, for example a boosting model, a neural network and a linear model. The gains are usually small, tenths of a percent, which matters in competitions more than in production.
    • Do not ensemble by default in production. Every extra model costs memory, latency and maintenance. Check on a validation set that the gain is worth it, and always compare against a simple baseline such as logistic regression.

    Ensembles are mainly a tool for supervised learning, but the same idea appears elsewhere: deep learning practitioners average the predictions of several networks trained from different random starting points, and techniques such as dropout can be seen as training an implicit ensemble of many smaller networks.

    FAQ

    What is the difference between bagging and boosting?

    Bagging trains models independently on random bootstrap samples of the data and averages them, which reduces variance; it suits deep trees that overfit. Boosting trains models one after another, each focusing on the errors of the previous ones, and adds them up with weights, which reduces bias; it suits shallow trees that underfit. Bagging runs in parallel and rarely overfits; boosting is sequential, usually more accurate and needs more tuning.

    Is random forest bagging or boosting?

    Random forest is a bagging method. Each tree is trained independently on a bootstrap sample, and the forest averages their predictions. Its addition is random feature selection at every split, which makes the trees less similar and the average more accurate.

    Is XGBoost bagging or boosting?

    XGBoost is a gradient boosting library: trees are added one at a time, each fitted to the gradients of the loss of the current model. It borrows one idea from bagging, optional random sampling of rows and columns for each tree (the subsample and colsample_bytree parameters), which reduces overfitting. LightGBM and CatBoost are also boosting libraries.

    What is stacking in machine learning?

    Stacking is an ensemble method that combines different types of models with a meta-model. The base models are trained with cross-validation, their out-of-fold predictions become the inputs of the meta-model, often a logistic or linear regression, and the meta-model learns how much to trust each base model.

    Are ensemble methods better than deep learning?

    For tabular data with up to millions of rows, tree ensembles such as gradient boosting and random forest are usually as accurate as neural networks or better, and much faster to train and tune. For images, audio and text, deep neural networks are far ahead. Foundation models for tables, such as TabPFN, have recently become competitive on small tabular data sets, but gradient boosting remains the standard baseline.

    When does an ensemble not help?

    When the members make the same mistakes, for example several similar models trained on the same features, or when one model is much better than the others. Ensembles also cannot fix missing information: if the features do not contain the answer, no combination of models will find it.


    bnr2mob
    Subscribe
    Notify of
    guest

    0 Comments
    Oldest
    Newest Most Voted