Skip to content

AdaBoost's training error can increase with a larger number of trees #20443

Open

Description

@ogrisel

We encountered the following behavior of AdaBoost when working on the scikit-learn mooc. Here is a script that reproduces the problem:

We compute the validation curves for 3 models with different numbers of leaf nodes in the weak learners and each time study the impact of the number of trees on the train and validation errors.

from sklearn.ensemble import AdaBoostRegressor
from sklearn.tree import DecisionTreeRegressor
from sklearn.model_selection import validation_curve
from sklearn.datasets import fetch_california_housing
import matplotlib.pyplot as plt


data, target = fetch_california_housing(return_X_y=True)

for max_leaf_nodes in [50, 100, 500]:
    adaboost = AdaBoostRegressor(
        learning_rate=1.,
        base_estimator=DecisionTreeRegressor(max_leaf_nodes=max_leaf_nodes),
    )
    param_range = [1, 2, 5, 10, 20, 50, 100, 500]
    train_scores, test_scores = validation_curve(
        adaboost,
        data,
        target,
        param_name="n_estimators",
        param_range=param_range,
        scoring="neg_mean_absolute_error",
        n_jobs=4,
    )
    train_errors, test_errors = -train_scores, -test_scores
    plt.figure()
    plt.errorbar(param_range, train_errors.mean(axis=1),
                 yerr=train_errors.std(axis=1), label="Training score",
                 alpha=0.7)
    plt.errorbar(param_range, test_errors.mean(axis=1),
                 yerr=test_errors.std(axis=1), label="Cross-validation score",
                 alpha=0.7)
    plt.legend()
    plt.xscale("log")
    plt.xticks(param_range)
    plt.ylabel("Mean absolute error in k$\n(smaller is better)")
    plt.xlabel("# estimators")
    _ = plt.title(
        f"AdaBoost regressor with {max_leaf_nodes=}\n"
        f"best CV score: {test_errors.mean(axis=1).min():.4f}"
    )

Here are the results:

adaboost_50_leaves
adaboost_100_leaves
adaboost_500_leaves

For 500 leaves we get the expected behavior: both the training and validation errors decrease when increasing the number of trees. At some point we reach a plateau of diminishing returns (expected, at least for validation error).

However for lower number of leaves (e.g. the second plot with max_leaf_nodes=50), the training set is growing with more trees! This is really something that I would not have expected. I wonder if this is not revealing a bug in our implementation.

For reference, for lower values of max_leaf_nodes both the training and validation errors stay do not decrease (and even increase again) and they stay close to one another (severe under fitting) with large error bars.

Activity

  1. europeanplaice commented on Jul 3, 2021

    @europeanplaice
    Contributor

    My suggestion is that if the prediction score is not improved compared to the previous score, we should reset sample_weight.

    I'm not an expert but my understanding is as follows. Forgive me if I'm wrong.
    Sample weights are updated so that the weak learner study intensively the data the previous weak learner can't predict well.
    It means the weak learner is given challenging data more frequently than one step before.

    However, if the weak learner is too weak to restudy such data, prediction scores deteriorate because the percentage of the challenging data goes up.
    The weak learner can't get insights because the task is too difficult.

    Consequently, although we increase the number of trees, we can't get the expected result.

    My proposal
    From

    beta = estimator_error / (1.0 - estimator_error)
    # Boost weight using AdaBoost.R2 alg
    estimator_weight = self.learning_rate * np.log(1.0 / beta)
    if not iboost == self.n_estimators - 1:
    sample_weight[sample_mask] *= np.power(
    beta, (1.0 - masked_error_vector) * self.learning_rate
    )

    To like this

    beta = estimator_error / (1.0 - estimator_error)
    
    # Boost weight using AdaBoost.R2 alg
    estimator_weight = self.learning_rate * np.log(1.0 / beta)
    
    if not iboost == self.n_estimators - 1:
        if hasattr(self, "previous_beta"):
            if self.previous_beta > beta:
                # improved
                sample_weight[sample_mask] *= np.power(
                    beta, (1.0 - masked_error_vector) * self.learning_rate
                )
            else:
                # reset if not improved
                sample_weight[sample_mask] = 1 / len(sample_weight)
        else:
            sample_weight[sample_mask] *= np.power(
                beta, (1.0 - masked_error_vector) * self.learning_rate
            )       
    
    self.previous_beta = beta

    The results were
    50

    100

    500

    I'm not sure this problem is a bug and I wonder resetting sample_weight makes this something other than AdaBoost.

  2. ogrisel commented on Jul 4, 2021

    @ogrisel
    MemberAuthor

    Very interesting analysis and clever fix.

    I'm not sure this problem is a bug and I wonder resetting sample_weight makes this something other than AdaBoost.

    I agree. But maybe we could add a flag to enable or disable the trick you suggest. @europeanplaice do you know if any paper been published in the weight-based boosting literature to analyze this problem?

    For reference, I tried to run the experiment in the description replacing AdaBoost with gradient boosting and there is no problem: training error always trends towards zero with more trees, irrespective of the size of the trees.

  3. changed the title [-]AdaBoost can underfit more with larger number of trees[/-] [+]AdaBoost's training error can increase with a larger number of trees[/+] on Jul 4, 2021
  4. glemaitre commented on Jul 4, 2021

    @glemaitre
    Member

    I am not sure entirely but I kind of recall something similar with the classification problem while preparing the MOOC.
    Thought I might be wrong since this is quite a long time ago (but I kind of recall plotting a score and not an error and seeing a bell curve like).

  5. ogrisel commented on Jul 5, 2021

    @ogrisel
    MemberAuthor

    For information, I have tried:

    • to plot mean squared error instead of the mean absolute error;
    • clip the sample weights below 1e-12 or even 1e-7:

    Those changes did not impact the shape of the training error curve with max_leaf_nodes=50: each time, the training error starts to increase with n_estimator > 10.

  6. europeanplaice commented on Jul 5, 2021

    @europeanplaice
    Contributor

    @ogrisel @glemaitre
    Thank you for the additional information.
    I've found a paper that seems to be related to this issue.

    An Investigation into How ADABOOST Affects Classifier Diversity
    http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.22.9349&rep=rep1&type=pdf

    However, it was found out that the method might get to an inefficient stage where adding new classifiers will not improve the performance but on the contrary, deteriorate it. This is caused by sampling repetitively from similar distributions whose resultant training set poses the same difficulty to the chosen classifier model. Then the ensemble will be overpopulated with "semi-good" and almost identical experts, and the effect of some good quality members of the team will be diluted. Our study of diversity aims at showing a pattern of diversity during training of the ensemble to support this hypothesis.

    According to this paper, diversity plays an important role in performance.

    Also, here are the histograms of the shuffled indexes of train data in this example. I recorded them on tensorboard.
    A histogram of the shuffled indexes stacks at every iteration. A peak of a histogram shows that there exist some indexes frequently repeated.

    Below is the histogram of the first attempt that was underfitted (max_leaf_nodes=50).
    As you can see, there are a few peaks, and these peaks don't change as iterations proceed.
    It seems like AdaBoost got caught in local minima.

    However, introducing resetting sample_weight give diversity to some extent.

  7. ogrisel commented on Jul 5, 2021

    @ogrisel
    MemberAuthor

    Thanks for the reference. The paragraph you highlighted seems to accurately describe what we are experiencing. I don't understand the histograms though. Could you give more details on how they are constructed? In particular what is the x axis and what are the stacks?

  8. ogrisel commented on Jul 5, 2021

    @ogrisel
    MemberAuthor

    For reference I also tried to decrease the learning rate (and increase the maximum number of trees): the problem appears later (e.g. around n_estimator=100 for learning_rate=0.1 but it still there. So decreasing the learning rate might only be a way to hide this convergence problem.

  9. europeanplaice commented on Jul 5, 2021

    @europeanplaice
    Contributor

    Sorry for the lack of explanation.

    https://github.com/europeanplaice/scikit-learn/blob/adaboost_with_tensorboard/sklearn/ensemble/_weight_boosting.py

    This is the code that records histograms on tensorboard.
    x-axis is the index number and y-axis is the index of the weak estimators.
    z-axis (height of histograms ) is the count of the index that is repeatedly chosen.

    The histogram was recorded at this line.
    tf.summary.histogram("bootstrap_idx", bootstrap_idx, iboost)

  10. DAKSHA2001 commented on Aug 29, 2021

    @DAKSHA2001

    take

  11. ogrisel commented on Sep 7, 2021

    @ogrisel
    MemberAuthor

    Thinking again about this issue, I think we could implement the strategy suggested by @europeanplaice above (#20443 (comment)) but it should not be the default behavior of this estimator because it would not be the "real" Adaboost anymore.

    Maybe what we could do is:

    • add a new constructor parameter with default value no_improvement="warn" and monitor the value of beta: if it stop improving, raise a warning suggesting to warn the user that the training loss does not decrease when adding more base estimator and suggest to try with different hyper-parameters for the base estimators to allow for more diversity or to set no_improvement="reset_weights" or no_improvement="stop" explicitly.
    • no_improvement="reset_weights" would implement the strategy above,
    • no_improvement="stop" would just implement early stopping,
    • no_improvement="continue" would just silence the warning.

    Not sure the latter two options are that useful, but they are easy to implement and give full control to the user and make it possible to keep the behavior of scikit-learn 0.24.2 with the warning.

  12. europeanplaice commented on Sep 7, 2021

    @europeanplaice
    Contributor

    Thank you for leading the discussion and indicating the implementation guide. I'll try to implement it according to your remark.

  13. glemaitre commented on Jun 2, 2023

    @glemaitre
    Member

    Since I observed the same behaviour on AdaBoostClassifier. To get this behaviour, I had the combination of a low learning rate, with an expressive model. The train and test errors of AdaBoost are the following using both algorithms:

    image

    One thing that I noticed is the error of the weak learner at each stage:

    image

    Somehow, one would expect the values as seen in "SAMME". It is counterintuitive to have a lower error for the latest weak learner.

    Code to reproduce the issue:

    Details
    # %%
    from sklearn.datasets import make_gaussian_quantiles
    
    X, y = make_gaussian_quantiles(
        n_samples=13000, n_features=10, n_classes=3, random_state=0
    )
    
    # %%
    from sklearn.model_selection import train_test_split
    
    X_train, X_test, y_train, y_test = train_test_split(
        X, y, test_size=10_000, random_state=0
    )
    
    # %%
    from sklearn.tree import DecisionTreeClassifier
    
    max_leaf_nodes = 30
    weak_learner = DecisionTreeClassifier(max_leaf_nodes=max_leaf_nodes)
    
    # %%
    from sklearn.ensemble import AdaBoostClassifier
    
    n_estimators = 600
    learning_rate = 0.1
    adaboost_samme_r = AdaBoostClassifier(
        estimator=weak_learner,
        n_estimators=n_estimators,
        learning_rate=learning_rate,
        algorithm="SAMME.R",
        random_state=0,
    )
    adaboost_samme = AdaBoostClassifier(
        estimator=weak_learner,
        n_estimators=n_estimators,
        learning_rate=learning_rate,
        algorithm="SAMME",
        random_state=0,
    )
    
    # %%
    from sklearn.metrics import accuracy_score
    
    
    def misclassification_error(estimator, X, y):
        return 1 - accuracy_score(y, estimator.predict(X))
    
    
    def misclassification_error_from_prediction(y_true, y_pred):
        return 1 - accuracy_score(y_true, y_pred)
    
    
    # %%
    from sklearn.model_selection import cross_validate
    
    cv = 10
    cv_results = {}
    for adaboost in [adaboost_samme_r, adaboost_samme]:
        cv_results[adaboost.algorithm] = cross_validate(
            adaboost,
            X,
            y,
            cv=cv,
            n_jobs=-1,
            scoring=misclassification_error,
            return_train_score=True,
            return_estimator=True,
            return_indices=True,
        )
    
    
    
    # %%
    import pandas as pd
    import numpy as np
    
    adaboost_error = {}
    for algorithm, result in cv_results.items():
        train_errors = []
        test_errors = []
        for fold_idx in range(cv):
            estimator = result["estimator"][fold_idx]
            train_idx = result["indices"]["train"][fold_idx]
            test_idx = result["indices"]["test"][fold_idx]
    
            train_errors.append([
                misclassification_error_from_prediction(y[train_idx], y_pred)
                for y_pred in estimator.staged_predict(X[train_idx])
            ])
            test_errors.append([
                misclassification_error_from_prediction(y[test_idx], y_pred)
                for y_pred in estimator.staged_predict(X[test_idx])
            ])
        adaboost_error[algorithm] = {
            "Train error": np.mean(train_errors, axis=0),
            "Test error": np.mean(test_errors, axis=0),
        }
    
    
    # %%
    index = pd.MultiIndex.from_product([
        list(adaboost_error.keys()), list(adaboost_error["SAMME"].keys())
    ])
    results = [
        adaboost_error[algorithm][error_type]
        for algorithm, error_type in index
    ]
    results = pd.DataFrame(results, index=index).T
    results.index.rename("Number of trees", inplace=True)
    
    # %%
    import matplotlib.pyplot as plt
    
    _, ax = plt.subplots(figsize=(8, 6))
    ax = results.plot(ax=ax)
    ax.set_ylabel("Misclassification error")
    _ = ax.set_title("AdaBoost SAMME vs SAMME.R")
    
    # %%
    from collections import defaultdict
    
    weak_learner_error = defaultdict(list)
    for algorithm, result in cv_results.items():
        for fold_idx in range(cv):
            estimator = result["estimator"][fold_idx]
            weak_learner_error[algorithm].append(estimator.estimator_errors_)
    
    # %%
    weak_learner_error = {key: np.mean(value, axis=0) for key, value in weak_learner_error.items()}
    weak_learner_error = pd.DataFrame(weak_learner_error)
    weak_learner_error.index.rename("Position of weak learner", inplace=True)
    weak_learner_error
    
    # %%
    ax = weak_learner_error.plot()
    ax.set_ylabel("Misclassification error")
    _ = ax.set_title("Misclassification error of each weak learner on the training set")
    
    # %%
  14. glemaitre commented on Jun 3, 2023

    @glemaitre
    Member

    Actually, AdaBoost is minimizing the exponential loss which is not necessarily minimizing the misclassification error. It might be one of the issue that observe. Also the papers are not written with a learning rate and I am not sure that we are placing it at the right location.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions