【问题标题】:retrieving selected features from RFECV inside gridsearchCV从 gridsearchCV 中的 RFECV 检索选定的特征
【发布时间】:2018-05-28 22:20:51
【问题描述】:

我想编写一个代码,它可以在几个处理器和预处理器上进行网格搜索,而且还可以搜索不同的功能组合。我通过在 gridsearchCV 中使用 RFECV 来做到这一点。但是,这需要很长时间才能运行。因此,我颠倒了顺序。我进行了网格搜索,然后将其放入 RFECV 中。现在,我想查看并打印在最佳模型中实际选择了哪些功能。我尝试了这个网站上的几个解决方案,但没有一个奏效。如何访问选定的功能? grid_dem.get_support(indices=True)grid_dem.support_ 都不起作用。我得到这个和其他类似的错误:AttributeError: 'RFECV' object has no attribute 'support_'

我的代码的相关部分是:

pipe = Pipeline([('preprocessing', StandardScaler()), ('rbf_svm', SVC(max_iter=1e6))])
param_grid ={'preprocessing': [StandardScaler(), MinMaxScaler(), Normalizer(), RobustScaler()],
     'rbf_svm__kernel': ['rbf', 'poly', 'linear', 'sigmoid'],
     'rbf_svm__C': np.logspace(-3,2,5), 'rbf_svm__gamma': np.logspace(-3,2,5)}

    # {'preprocessing': [StandardScaler(), MinMaxScaler(), Normalizer(), RobustScaler()],
    #  'rbf_svm': [LogisticRegression(max_iter=1e6)],
    #  'logisticregression__C': np.logspace(-3,2,5)}]

grid_dem = GridSearchCV(pipe, param_grid, cv=5,verbose=5,n_jobs=3)
grid_dem.fit(X_democrat_train,y_democrat_train)
grid_dem.score(X_democrat_test,y_democrat_test)
print(grid_dem.best_estimator_)
rfecv=RFECV(grid_dem, verbose=3)
print(rfecv)
print(rfecv.get_support(indices=True))
# rfecv=rfecv.fit_transform(X_democrat_train, y_democrat_train)
# print(rfecv.get_params())

正如您在最后两行中看到的,我也尝试转换 X,但这也不起作用。

【问题讨论】:

    标签: python scikit-learn feature-selection grid-search rfe


    【解决方案1】:

    您已将管道发送到 gridSearch。所以best_estimator_ 将返回一个管道。但是grid_dem 仍然是一个 GridSearchCV 对象。所以很明显get_support() 是行不通的。之后,您将这个grid_dem 传递给RFECV,但没有调用fit()。这就是support_ 不可用的原因。

    请像这样更新您的代码:

    rfecv=RFECV(grid_dem.best_estimator_, verbose=3)  <==Edited
    rfecv.fit(X_democrat_train,y_democrat_train)   #<==This is what you want
    print(rfecv.get_support(indices=True))  
    # rfecv=rfecv.fit_transform(X_democrat_train, y_democrat_train)
    # print(rfecv.get_params())mocrat_train,y_democrat_train)
    

    【讨论】:

    • 感谢您的回复。我尝试了您的更新,但出现以下错误:'RuntimeError:分类器未公开“coef_”或“feature_importances_”属性'。我该怎么办?
    • @Kate 是的。那是因为 GridSearchCV 没有这些,并且 RFECV 只能与具有这些属性之一的估计器一起使用。尝试编辑后的答案。
    • @VivekKumar 如果您知道答案,请告诉我:stackoverflow.com/questions/55650782/… 期待您的回音。非常感谢:)
    猜你喜欢
    • 2020-08-24
    • 2019-02-14
    • 2021-11-05
    • 2020-12-25
    • 2018-12-13
    • 2022-07-27
    • 2018-06-30
    • 2017-07-18
    • 2020-07-10
    相关资源
    最近更新 更多