簡體   English   中英

來自 statsmodels 的自定義估算器 WLS 的 sklearn check_estimator 錯誤

[英]sklearn check_estimator error for a custom estimator WLS from statsmodels

我創建了 sklearn 自定義估計器(statsmodels.regression.linear_model.WLS with Lasso)來使用交叉驗證。 check_estimator() 報告錯誤,但我沒有任何錯誤,而且它似乎在運行。

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)

我願意:

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

它給出了錯誤:

---------------------------------------------------------------------------
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 說 G1 和 self.exog 的形狀是一樣的(self.exog 是浮動的,G1 看起來也是浮動的):

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

我的代碼可能有什么問題? 我正在檢查結果是否正確,這可能需要一點時間。

謝謝。

我相信您收到此錯誤消息是由於 WLS 中的錯誤(類型不匹配)。 相比:

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")

對比:

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

這個[特定]錯誤可以通過以下方式糾正:

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])

但隨后您會遇到另一個錯誤: check_complex_data (您可能會在此處看到定義)

您面臨的問題check_estimator對估算器(在您的情況下為 WLS)應該通過的檢查過於嚴格。 您可能會看到所有檢查的列表:

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

WLS 並沒有通過所有檢查,比如復數(我們從第 2 行移到第 11 行),而是在實踐中處理您的數據,因此您可以接受它(或從頭開始重新編碼)。

編輯

一個有效的問題可能是“哪個測試運行,哪個失敗”。 為此,您可能希望檢查https://scikit-learn.org/stable/auto_examples/release_highlights/plot_release_highlights_0_22_0.html#checking-scikit-learn-compatibility-of-an-estimatorsklearn.utils.estimator_checks._yield_checks為您的估算器生成可用檢查的生成器

編輯 2

v0.24 的替代方案可能是:

check_estimator(SMWrapper(), strict_mode=False)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM