【问题标题】:Apply MinMaxScaler() to RFECV() with a pipeline使用管道将 MinMaxScaler() 应用于 RFECV()
【发布时间】:2021-07-20 16:24:58
【问题描述】:

我正在尝试进行功能选择,我正在使用 RFECVLogisticRegression。为此,我需要缩放数据,因为否则回归不会收敛。 但是,我认为如果我先对完整数据进行缩放,那将是有偏差的(基本上数据会泄漏到测试集)。

这是我目前的代码:

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

我什至还没有将它与数据相匹配。

我尝试搜索,但找不到任何有用的东西。有什么想法可能会失败吗?

【问题讨论】:

    标签: python scikit-learn pipeline feature-selection rfe


    【解决方案1】:

    这是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 模型的系数。

    【讨论】:

    猜你喜欢
    • 2021-05-14
    • 2016-08-03
    • 2021-09-21
    • 2022-10-15
    • 2016-09-08
    • 1970-01-01
    • 1970-01-01
    • 2021-04-15
    • 2019-01-09
    相关资源
    最近更新 更多