Skip to content

ValueError: Buffer dtype mismatch, expected 'double' but got 'float' when calling fit on GradientBoostingRegressor with init = Ridge #10302

Closed

Description

@chorus12

Description

ValueError: Buffer dtype mismatch, expected 'double' but got 'float' when calling fit on GradientBoostingRegressor with init = Ridge

Steps/Code to Reproduce

from sklearn.ensemble import GradientBoostingRegressor
from sklearn.linear_model import Ridge

base_model_params = {'alpha' : 0.01, 
                     'fit_intercept' :True, 
                     'normalize' : True, 
                     'copy_X' : True, 
                     'max_iter' : None, 
                     'tol' : 0.01, 
                     'solver' : 'sag'}

base_model = Ridge(**base_model_params)

gb_params = {'loss' : 'huber',
            'criterion' : 'friedman_mse',
            'learning_rate' : 0.05,
            'max_depth' : 5,
            'max_features' : 'sqrt',
            'n_estimators' : 100,
            'init' : base_model
            }
model = GradientBoostingRegressor(**gb_params)
model.fit(X,Y)

Expected Results

The model fits

Actual Results

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<timed exec> in <module>()

~/anaconda/envs/python3/lib/python3.6/site-packages/sklearn/ensemble/gradient_boosting.py in fit(self, X, y, sample_weight, monitor)
    996 
    997             # fit initial model - FIXME make sample_weight optional
--> 998             self.init_.fit(X, y, sample_weight)
    999 
   1000             # init predictions

~/anaconda/envs/python3/lib/python3.6/site-packages/sklearn/linear_model/ridge.py in fit(self, X, y, sample_weight)
    663         self : returns an instance of self.
    664         """
--> 665         return super(Ridge, self).fit(X, y, sample_weight=sample_weight)
    666 
    667 

~/anaconda/envs/python3/lib/python3.6/site-packages/sklearn/linear_model/ridge.py in fit(self, X, y, sample_weight)
    504                 max_iter=self.max_iter, tol=self.tol, solver=self.solver,
    505                 random_state=self.random_state, return_n_iter=True,
--> 506                 return_intercept=False)
    507             self._set_intercept(X_offset, y_offset, X_scale)
    508 

~/anaconda/envs/python3/lib/python3.6/site-packages/sklearn/linear_model/ridge.py in ridge_regression(X, y, alpha, sample_weight, solver, max_iter, tol, verbose, random_state, return_n_iter, return_intercept)
    425                 max_iter, tol, verbose, random_state, False, max_squared_sum,
    426                 init,
--> 427                 is_saga=solver == 'saga')
    428             if return_intercept:
    429                 coef[i] = coef_[:-1]

~/anaconda/envs/python3/lib/python3.6/site-packages/sklearn/linear_model/sag.py in sag_solver(X, y, sample_weight, loss, alpha, beta, max_iter, tol, verbose, random_state, check_input, max_squared_sum, warm_start_mem, is_saga)
    295         num_seen_init = 0
    296 
--> 297     dataset, intercept_decay = make_dataset(X, y, sample_weight, random_state)
    298 
    299     if max_squared_sum is None:

~/anaconda/envs/python3/lib/python3.6/site-packages/sklearn/linear_model/base.py in make_dataset(X, y, sample_weight, random_state)
     62         intercept_decay = SPARSE_INTERCEPT_DECAY
     63     else:
---> 64         dataset = ArrayDataset(X, y, sample_weight, seed=seed)
     65         intercept_decay = 1.0
     66 

sklearn/utils/seq_dataset.pyx in sklearn.utils.seq_dataset.ArrayDataset.__cinit__()

ValueError: Buffer dtype mismatch, expected 'double' but got 'float'

Versions

Darwin-15.0.0-x86_64-i386-64bit
Python 3.6.2 |Continuum Analytics, Inc.| (default, Jul 20 2017, 13:14:59)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)]
NumPy 1.12.1
SciPy 0.19.1
Scikit-Learn 0.19.0

Activity

  1. jnothman commented on Dec 13, 2017

    @jnothman
    Member

    You should be using scikit-learn 0.19.1. You also should provide some X and y (fine if they're generated) for which this occurs. What type and what dtype, at least, is your data?

  2. chorus12 commented on Dec 13, 2017

    @chorus12
    Author

    Hi. Will provide the data in a shortwhile but as for now dtype is float.

  3. jnothman commented on Dec 13, 2017

    @jnothman
    Member
  4. chorus12 commented on Dec 13, 2017

    @chorus12
    Author

    float64
    XY.zip

    import pickle
    with open('X.pkl','br') as file:
    X = pickle.load(file)
    with open('Y.pkl','br') as file:
    Y = pickle.load(file)

  5. lesteve commented on Dec 13, 2017

    @lesteve
    Member

    I can reproduce here is a stand-alone snippet:

    import numpy as np
    
    from sklearn.ensemble import GradientBoostingRegressor
    from sklearn.linear_model import Ridge
    
    rng = np.random.RandomState(42)
    X = rng.randn(200, 10)
    y = rng.randn(200)
    
    base_model_params = {'alpha' : 0.01, 
                         'fit_intercept' :True, 
                         'normalize' : True, 
                         'copy_X' : True, 
                         'max_iter' : None, 
                         'tol' : 0.01, 
                         'solver' : 'sag'}
    
    base_model = Ridge(**base_model_params)
    
    gb_params = {'loss' : 'huber',
                'criterion' : 'friedman_mse',
                'learning_rate' : 0.05,
                'max_depth' : 5,
                'max_features' : 'sqrt',
                'n_estimators' : 100,
                'init' : base_model,
                }
    model = GradientBoostingRegressor(**gb_params)
    model.fit(X, y)

    The problem is that sample_weights is float32. The float32 sample_weights comes from GradientBoosting.fit:

    sample_weight = np.ones(n_samples, dtype=np.float32)

    Note that I could not get the snippet to run even passing float64 weights into model.fit. Maybe there is a deeper problem here. Here is the stack-trace with model.fit(X, y, sample_weight=np.ones(200, dtype='float64')):

    Details
    ---------------------------------------------------------------------------
    IndexError                                Traceback (most recent call last)
    <ipython-input-58-f2841f9901eb> in <module>()
         27             }
         28 model = GradientBoostingRegressor(**gb_params)
    ---> 29 model.fit(X, y, sample_weight=np.ones(200))
         30 
    
    /home/local/lesteve/dev/scikit-learn/sklearn/ensemble/gradient_boosting.py in fit(self, X, y, sample_weight, monitor)
       1065         n_stages = self._fit_stages(X, y, y_pred, sample_weight, self._rng,
       1066                                     X_val, y_val, sample_weight_val,
    -> 1067                                     begin_at_stage, monitor, X_idx_sorted)
       1068 
       1069         # change shape of arrays after fit (early-stopping or additional ests)
    
    /home/local/lesteve/dev/scikit-learn/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)
       1129             y_pred = self._fit_stage(i, X, y, y_pred, sample_weight,
       1130                                      sample_mask, random_state, X_idx_sorted,
    -> 1131                                      X_csc, X_csr)
       1132 
       1133             # track deviance (= loss)
    
    /home/local/lesteve/dev/scikit-learn/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)
        801                 loss.update_terminal_regions(tree.tree_, X, y, residual, y_pred,
        802                                              sample_weight, sample_mask,
    --> 803                                              self.learning_rate, k=k)
        804 
        805             # add tree to ensemble
    
    /home/local/lesteve/dev/scikit-learn/sklearn/ensemble/gradient_boosting.py in update_terminal_regions(self, tree, X, y, residual, y_pred, sample_weight, sample_mask, learning_rate, k)
        248             self._update_terminal_region(tree, masked_terminal_regions,
        249                                          leaf, X, y, residual,
    --> 250                                          y_pred[:, k], sample_weight)
        251 
        252         # update predictions (both in-bag and out-of-bag)
    
    IndexError: too many indices for array
    
  6. glemaitre commented on Dec 13, 2017

    @glemaitre
    Member

    y_pred[:, k] is the issue since y_pred is of shape (n,) and k is the index of the estimator being updated. I'll check a bit more later on.

    Edit:
    What I mean is that y_pred is 1D and indexed as a 2D array.

  7. glemaitre commented on Dec 13, 2017

    @glemaitre
    Member

    Actually y_pred is expected to be 2 d while predict from ridge is 1 d

  8. 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