简体   繁体   中英

sklearn check_estimator error for a custom estimator WLS from statsmodels

I created sklearn custom estimator (statsmodels.regression.linear_model.WLS with Lasso) to use cross validation. check_estimator() reports error, yet I can't anything wrong, and it seems to run.

class SMWrapper(BaseEstimator, RegressorMixin):
    def __init__(self, alpha=0, lasso=True):
        self.alpha = alpha
        self.lasso = lasso
    def fit(self, X, y):
        # unpack weight from X
        self.model_ = WLS(y, X[:,:-1], weights=X[:,-1])
        if self.lasso:
            L1_wt = 1
        else:
            L1_wt = 0
        self.results_ = self.model_.fit_regularized(alpha=self.alpha, L1_wt=L1_wt, method='sqrt_lasso')
        return self
    def predict(self, X):
        return self.results_.predict(X[:,:-1])

    # yy shape is (nb_obs), xx shape is (nb_xvar, nb_obs), weight shape is (nb_obs)
    # pack weight as one more xvar, so that train/validation split will be done properly on weight.
    lenx = len(xx)
    xxx = np.full((yy.shape[0], lenx+1), 0.0)
    for i in range(lenx):
        xxx[:,i] = xx[i]
    xxx[:,lenx] = weight
    lassoReg = SMWrapper(lasso=lasso)
    param_grid = {'alpha': alpha}
    grid_search = GridSearchCV(lassoReg, param_grid, cv=10, scoring='neg_mean_squared_error',return_train_score=True)
    grid_search.fit(xxx, yy)

I do:

from sklearn.utils.estimator_checks import check_estimator
check_estimator(SMWrapper())

It gives error:

---------------------------------------------------------------------------
NotImplementedError                       Traceback (most recent call last)
<ipython-input-518-6da3cc5b584c> in <module>()
----> 1 check_estimator(SMWrapper())

/nfs/geardata/anaconda2/lib/python2.7/site-packages/sklearn/utils/estimator_checks.pyc in check_estimator(Estimator)
    302     for check in _yield_all_checks(name, estimator):
    303         try:
--> 304             check(name, estimator)
    305         except SkipTest as exception:
    306             # the only SkipTest thrown currently results from not

/nfs/geardata/anaconda2/lib/python2.7/site-packages/sklearn/utils/testing.pyc in wrapper(*args, **kwargs)
    346             with warnings.catch_warnings():
    347                 warnings.simplefilter("ignore", self.category)
--> 348                 return fn(*args, **kwargs)
    349 
    350         return wrapper

/nfs/geardata/anaconda2/lib/python2.7/site-packages/sklearn/utils/estimator_checks.pyc in check_estimators_dtypes(name, estimator_orig)
   1100         estimator = clone(estimator_orig)
   1101         set_random_state(estimator, 1)
-> 1102         estimator.fit(X_train, y)
   1103 
   1104         for method in methods:

<ipython-input-516-613d1ce7615e> in fit(self, X, y)
     10         else:
     11             L1_wt = 0
---> 12         self.results_ = self.model_.fit_regularized(alpha=self.alpha, L1_wt=L1_wt, method='sqrt_lasso')
     13         return self
     14     def predict(self, X):

/nfs/geardata/anaconda2/lib/python2.7/site-packages/statsmodels/regression/linear_model.pyc in fit_regularized(self, method, alpha, L1_wt, start_params, profile_scale, refit, **kwargs)
    779             start_params=start_params,
    780             profile_scale=profile_scale,
--> 781             refit=refit, **kwargs)
    782 
    783         from statsmodels.base.elastic_net import (

/nfs/geardata/anaconda2/lib/python2.7/site-packages/statsmodels/regression/linear_model.pyc in fit_regularized(self, method, alpha, L1_wt, start_params, profile_scale, refit, **kwargs)
    998                 RegularizedResults, RegularizedResultsWrapper
    999             )
-> 1000             params = self._sqrt_lasso(alpha, refit, defaults["zero_tol"])
   1001             results = RegularizedResults(self, params)
   1002             return RegularizedResultsWrapper(results)

/nfs/geardata/anaconda2/lib/python2.7/site-packages/statsmodels/regression/linear_model.pyc in _sqrt_lasso(self, alpha, refit, zero_tol)
   1052         G1 = cvxopt.matrix(0., (n+1, 2*p+1))
   1053         G1[0, 0] = -1
-> 1054         G1[1:, 1:p+1] = self.exog
   1055         G1[1:, p+1:] = -self.exog
   1056 

NotImplementedError: invalid type in assignment

Debug says shape of G1 and self.exog are same (self.exog is float, G1 also looks to be float):

ipdb> self.exog.shape
(20, 4)
ipdb> G1[1:, 1:p+1]
<20x4 matrix, tc='d'>

What might be wrong with my code? I am checking whether the result is correct, which may takes a little while.

Thanks.

I believe you're getting this error message due to a bug (type mismatch) in WLS. Compare:

import cvxopt
n =10
p = 5
G1 = cvxopt.matrix(0., (n+1, 2*p+1))

G1[0, 0] = -1
x = np.zeros((10,5))
G1[1:, 1:p+1] = x.astype("float64")

vs:

G1[1:, 1:p+1] = x.astype("float32")
NotImplementedError                       Traceback (most recent call last)
<ipython-input-82-d517da814a22> in <module>
      6 G1[0, 0] = -1
      7 x = np.zeros((10,5))
----> 8 G1[1:, 1:p+1] = x.astype("float32")

NotImplementedError: invalid type in assignment

This [particular] error may be corrected by:

class SMWrapper(BaseEstimator, RegressorMixin):
    def __init__(self, alpha=0, lasso=True):
        self.alpha = alpha
        self.lasso = lasso
    def fit(self, X, y):
        # unpack weight from X
        self.model_ = WLS(y, X[:,:-1].astype("float64"), weights=X[:,-1]) # note astype
        if self.lasso:
            L1_wt = 1
        else:
            L1_wt = 0
        self.results_ = self.model_.fit_regularized(alpha=self.alpha, L1_wt=L1_wt, method='sqrt_lasso')
        return self
    def predict(self, X):
        return self.results_.predict(X[:,:-1])

but then you will run into another error: check_complex_data (you may see definition here )

The problem you're facing check_estimator is way too strict on what checks an estimator (WLS in your case) should pass. You may see the list of all checks with:

from sklearn.utils.estimator_checks import check_estimator
gen = check_estimator(SMWrapper(), generate_only=True)
for x in iter(gen):
    print(x)

WLS is not passing all the checks, like for complex numbers (we moved from line 2 to line 11), but works with your data in practice, so you can live with it (or recode it from scratch).

EDIT

A valid question could be "which test run and which fail". To do this you may wish to check https://scikit-learn.org/stable/auto_examples/release_highlights/plot_release_highlights_0_22_0.html#checking-scikit-learn-compatibility-of-an-estimator and sklearn.utils.estimator_checks._yield_checks for a generator of available checks for your estimator

EDIT 2

An alternative for v0.24 might be:

check_estimator(SMWrapper(), strict_mode=False)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM