Skip to content

GradientBoosting fails when using init estimator parameter. #12429

Closed

Description

@stoddardg

Description

Passing any estimator to the init parameter in GradientBoostingClassifier (or GradientBoostingRegressor) causes errors when fitting. I'm including one example below as a MWE but I've fiddled with this issue for a while and get a number of different errors even if I can get past one. My guess is that this part of the code (the init estimator part) hasn't been shown any love in quite a while (since I've found similar issues that date back to 2014: #2691). A more complete exploration can be found here: https://github.com/stoddardg/sklearn_bug_example/blob/master/Gradient%2BBoosting%2Binit%2BMWE.ipynb

Steps/Code to Reproduce

from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegressionCV
from sklearn.ensemble import GradientBoostingClassifier

X, y = make_classification(n_samples=1000, n_features=50, n_informative=10,random_state=0)
init_clf = LogisticRegressionCV()
clf = GradientBoostingClassifier(init=init_clf)
clf.fit(X, y)

Actual Results

IndexError                                Traceback (most recent call last)
<ipython-input-5-f94c05274ee0> in <module>()
      6 init_clf = LogisticRegressionCV()
      7 clf = GradientBoostingClassifier(init=init_clf)
----> 8 clf.fit(train_X, train_y)

~/anaconda3/envs/eis_env/lib/python3.7/site-packages/sklearn/ensemble/gradient_boosting.py in fit(self, X, y, sample_weight, monitor)
   1463         n_stages = self._fit_stages(X, y, y_pred, sample_weight, self._rng,
   1464                                     X_val, y_val, sample_weight_val,
-> 1465                                     begin_at_stage, monitor, X_idx_sorted)
   1466 
   1467         # change shape of arrays after fit (early-stopping or additional ests)

~/anaconda3/envs/eis_env/lib/python3.7/site-packages/sklearn/ensemble/gradient_boosting.py in _fit_stages(self, X, y, y_pred, sample_weight, random_state, X_val, y_val, sample_weight_val, begin_at_stage, monitor, X_idx_sorted)
   1527             y_pred = self._fit_stage(i, X, y, y_pred, sample_weight,
   1528                                      sample_mask, random_state, X_idx_sorted,
-> 1529                                      X_csc, X_csr)
   1530 
   1531             # track deviance (= loss)

~/anaconda3/envs/eis_env/lib/python3.7/site-packages/sklearn/ensemble/gradient_boosting.py in _fit_stage(self, i, X, y, y_pred, sample_weight, sample_mask, random_state, X_idx_sorted, X_csc, X_csr)
   1197             loss.update_terminal_regions(tree.tree_, X, y, residual, y_pred,
   1198                                          sample_weight, sample_mask,
-> 1199                                          self.learning_rate, k=k)
   1200 
   1201             # add tree to ensemble

~/anaconda3/envs/eis_env/lib/python3.7/site-packages/sklearn/ensemble/gradient_boosting.py in update_terminal_regions(self, tree, X, y, residual, y_pred, sample_weight, sample_mask, learning_rate, k)
    396             self._update_terminal_region(tree, masked_terminal_regions,
    397                                          leaf, X, y, residual,
--> 398                                          y_pred[:, k], sample_weight)
    399 
    400         # update predictions (both in-bag and out-of-bag)

IndexError: too many indices for array

Versions

System
------
    python: 3.7.0 (default, Jun 28 2018, 13:15:42)  [GCC 7.2.0]
executable: /home/gstoddard/anaconda3/envs/eis_env/bin/python
   machine: Linux-3.10.0-862.14.4.el7.x86_64-x86_64-with-redhat-7.5-Maipo

BLAS
----
    macros: SCIPY_MKL_H=None, HAVE_CBLAS=None
  lib_dirs: /home/gstoddard/anaconda3/envs/eis_env/lib
cblas_libs: mkl_rt, pthread

Python deps
-----------
       pip: 18.0
setuptools: 39.2.0
   sklearn: 0.20.0
     numpy: 1.15.0
     scipy: 1.1.0
    Cython: None
    pandas: 0.23.3

Activity

  1. amueller commented on Oct 22, 2018

    @amueller
    Member

    So is this not a duplicate of #2691? And yes, no-one has taken the time to fix that afaik. I don't think people thought it was an important use-case.

  2. jeremiedbb commented on Oct 22, 2018

    @jeremiedbb
    Member

    This issue was also reported here #10302.

    It seems that there are 2 issues. Both come from the line

    y_pred = self.init_.predict(X)
    • If the prediction on a single label, y_pred will have shape (n_samples,) and this causes a failure later. It should be reshaped.
    • Then, if y has an integer dtype, y_pred will also have one, and this also causes a failure later due to unsafe casting. It should be cast to float.

    a simple fix is to replace the line above by:

    y_pred = self.init_.predict(X).astype(np.float64, copy=False)
    if y_pred.shape == (X.shape[0],):
        y_pred = y_pred[:, np.newaxis]

    I'll make a PR

  3. jeremiedbb commented on Oct 22, 2018

    @jeremiedbb
    Member

    It seems to be a duplicate of #2691. The code snippet is almost the same (different init classifier but the issue is for all classifiers)

  4. jeremiedbb commented on Oct 22, 2018

    @jeremiedbb
    Member

    In the meanwhile, you can do:

    class init_clf:
        def __init__(self, estimator):
            self.estimator = estimator
        def predict(self, X):
            return self.estimator.predict_proba(X)[:, 1][:, numpy.newaxis]
        def fit(self, X, y):
            self.estimator.fit(X, y)

    as explained here https://stackoverflow.com/a/19679862, and use init_clf(LogisticRegressionCV()) for the init parameter.

  5. stoddardg commented on Oct 23, 2018

    @stoddardg
    Author

    Thanks all for the responses.

    Its not an exact duplicate of #2691 if only for the reason that there are more errors than just the too many indices for array error. For example, if I use the init_clf as defined in #12429 (comment), another issue is thrown

    TypeError                                 Traceback (most recent call last)
    <ipython-input-15-bf43bf1f4e0f> in <module>()
          1 init_clf = Init_Clf(LassoCV(cv=3))
          2 clf = GradientBoostingRegressor(init=init_clf)
    ----> 3 clf.fit(X, y)
    
    ~/anaconda3/envs/eis_env/lib/python3.7/site-packages/sklearn/ensemble/gradient_boosting.py in fit(self, X, y, sample_weight, monitor)
       1419 
       1420             # fit initial model - FIXME make sample_weight optional
    -> 1421             self.init_.fit(X, y, sample_weight)
       1422 
       1423             # init predictions
    
    TypeError: fit() takes 3 positional arguments but 4 were given
    

    If you want to get around both issues, you need something that will deal with thesample_weight argument, e.g.:

    class Working_Init_Clf:
        def __init__(self, estimator):
            self.estimator = estimator
        def predict(self, X):
            return self.estimator.predict_proba(X)[:, 1][:, np.newaxis]
        def fit(self, X, y,sample_weight=None, **fit_params):
            self.estimator.fit(X, y)

    As far as the use case goes, its hard to tell how useful it is. I was excited about it with the idea that I would use a linear function for init_estimator so that it could take care of the "linear parts of my problem" and then use GradientBoosting to refine the non-linear parts. The underlying theory is that trees need a lot of complexity to approximate functions (because you need a lot of step-wise pieces to approximate a line) that can easily be described with a simple linear function. So combining the two approaches, with init_clf, would give a better model.

  6. jeremiedbb commented on Oct 23, 2018

    @jeremiedbb
    Member

    Hum this is because the estimator you provided does not support sample weights. But one should be able to do that as long to as he does not try to fit the gradient boosting with sample weights. I'll fix that too in my PR.

    Have you encounter other kinds of bugs related to that ?

  7. stoddardg commented on Oct 30, 2018

    @stoddardg
    Author

    Sorry for the late reply but I haven't noticed any other bugs. The workaround we identified has been working for me and I'm excited to see the finished product.

    Also, I just wanted to say that I really appreciate the work that you (and other folks) have done on this. I've been keeping an eye on the PR and resulting discussion and its been educating/fun to watch. I'll try to pay it forward in the future by contributing myself (or at least encouraging my team to do so) but in the mean time, I donated a small amount. Thanks!

  8. thomasjpfan commented on Oct 27, 2019

    @thomasjpfan
    Member

    This may have been resolved in #12983 (in the code snippet in the original post now works without error on master).

    @stoddardg May you test this by installing the dev build?

  9. stoddardg commented on Nov 6, 2019

    @stoddardg
    Author

    @thomasjpfan Yes, I'll get to testing it this weekend.

  10. jeremiedbb commented on Mar 2, 2020

    @jeremiedbb
    Member

    Fixed by #12983. Closing

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions