我正在尝试进行特征选择,并使用RFECV
和LogisticRegression
。为此,我需要缩放数据,因为否则回归将不会收敛。然而,我认为如果我首先缩放完整的数据,它将是有偏见的(基本上数据正在泄漏到测试集)。
这是我到目前为止的代码:
from sklearn.feature_selection import RFECV
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold
from sklearn.preprocessing import MinMaxScaler
from sklearn.pipeline import Pipeline
cv = StratifiedKFold(5)
scaler = MinMaxScaler()
reg = LogisticRegression(max_iter=1000, solver="newton-cg")
pipeline = Pipeline(steps=[("scale",scaler),("lr",reg)])
visualizer = RFECV(pipeline, cv=cv, scoring='f1_weighted')
但是它给了我这个错误:
Traceback (most recent call last):
File "<ipython-input-267-0073ead26d52>", line 1, in <module>
visualizer.fit(x_6, y_6) # Fit the data to the visualizer
File "C:\ProgramData\Anaconda3\lib\site-packages\sklearn\feature_selection\_rfe.py", line 550, in fit
scores = parallel(
File "C:\ProgramData\Anaconda3\lib\site-packages\sklearn\feature_selection\_rfe.py", line 551, in <genexpr>
func(rfe, self.estimator, X, y, train, test, scorer)
File "C:\ProgramData\Anaconda3\lib\site-packages\sklearn\feature_selection\_rfe.py", line 33, in _rfe_single_fit
return rfe._fit(
File "C:\ProgramData\Anaconda3\lib\site-packages\sklearn\feature_selection\_rfe.py", line 204, in _fit
raise RuntimeError('The classifier does not expose '
RuntimeError: The classifier does not expose "coef_" or "feature_importances_" attributes
我甚至还没有把它与数据相匹配。
我试着搜索,但找不到任何有用的东西。有什么想法可能会失败吗?
发布于 2021-05-21 00:15:34
对于Pipeline
对象来说,这是一个非常常见的问题。默认情况下,它们不会暴露拟合估计器的固有特征重要性度量和其他属性。所以你必须定义一个自定义的管道对象。
此答案here已经提供了一个公开功能重要性度量的解决方案:
class MyPipeline(Pipeline):
@property
def coef_(self):
return self._final_estimator.coef_
@property
def feature_importances_(self):
return self._final_estimator.feature_importances_
使用此方法,您可以创建管道对象,如下所示:
pipeline = MyPipeline(steps=[("scale",scaler),("lr",reg)])
现在,RFECV
对象可以毫无问题地访问拟合的LogisticRegression
模型的系数。
https://stackoverflow.com/questions/67281155
复制相似问题