我将这个问题发布到 Cross Validated 论坛,后来意识到这可能会在 stackoverlfow 中找到合适的受众。
我正在寻找一种方法,可以使用从 python statsmodel 获得的 fit
对象(结果)输入到 scikit-learn cross_validation 方法的 cross_val_score
中?
所附链接表明这可能是可能的,但我没有成功。
我收到以下错误
estimator should a be an estimator implementing 'fit' method statsmodels.discrete.discrete_model.BinaryResultsWrapper object at 0x7fa6e801c590 was passed
最佳答案
事实上,您不能直接在statsmodels
对象上使用cross_val_score
,因为接口(interface)不同:在statsmodels 中
- 训练数据直接传递给构造函数
- 一个单独的对象包含模型估计的结果
但是,您可以编写一个简单的包装器来使 statsmodels
对象看起来像 sklearn
估计器:
import statsmodels.api as sm
from sklearn.base import BaseEstimator, RegressorMixin
class SMWrapper(BaseEstimator, RegressorMixin):
""" A universal sklearn-style wrapper for statsmodels regressors """
def __init__(self, model_class, fit_intercept=True):
self.model_class = model_class
self.fit_intercept = fit_intercept
def fit(self, X, y):
if self.fit_intercept:
X = sm.add_constant(X)
self.model_ = self.model_class(y, X)
self.results_ = self.model_.fit()
return self
def predict(self, X):
if self.fit_intercept:
X = sm.add_constant(X)
return self.results_.predict(X)
此类包含正确的fit
和predict
方法,可以与sklearn
一起使用,例如交叉验证或包含在管道中。喜欢这里:
from sklearn.datasets import make_regression
from sklearn.model_selection import cross_val_score
from sklearn.linear_model import LinearRegression
X, y = make_regression(random_state=1, n_samples=300, noise=100)
print(cross_val_score(SMWrapper(sm.OLS), X, y, scoring='r2'))
print(cross_val_score(LinearRegression(), X, y, scoring='r2'))
您可以看到两个模型的输出是相同的,因为它们都是 OLS 模型,以相同的方式进行交叉验证。
[0.28592315 0.37367557 0.47972639]
[0.28592315 0.37367557 0.47972639]
关于python - 将 statsmodel 估计与 scikit-learn 交叉验证结合使用是否可能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41045752/