【问题标题】:How to use sklearn RFECV to select the optimal features to pass to a dimensionality reduction step before fitting my estimator如何在拟合我的估计器之前使用 sklearn RFECV 选择最佳特征以传递给降维步骤
【发布时间】:2021-08-08 15:43:12
【问题描述】:

在使用 KNN 拟合我的估计器之前,如何使用 sklearn RFECV 方法选择最佳特征以传递给 LinearDiscriminantAnalysis(n_components=2) 方法以进行降维。

pipeline = make_pipeline(Normalizer(), LinearDiscriminantAnalysis(n_components=2), KNeighborsClassifier(n_neighbors=10))

X = self.dataset
y = self.postures

min_features_to_select = 1  # Minimum number of features to consider
rfecv = RFECV(svc, step=1, cv=None, scoring='f1_weighted', min_features_to_select=min_features_to_select)

rfecv.fit(X, y)

print(rfecv.support_)
print(rfecv.ranking_)
print("Optimal number of features : %d" % rfecv.n_features_)

Plot number of features VS. cross-validation scores
plt.figure()
plt.xlabel("Number of features selected")
plt.ylabel("Cross validation score (nb of correct classifications)")
plt.plot(range(min_features_to_select,
len(rfecv.grid_scores_) + min_features_to_select),
rfecv.grid_scores_)
plt.show()

我从这段代码中得到以下错误。如果我在没有 LinearDiscriminantAnalysis() 步骤的情况下运行此代码,则它可以工作,但这是我处理的重要部分。

*** ValueError: when `importance_getter=='auto'`, the underlying estimator Pipeline should have `coef_` or `feature_importances_` attribute. Either pass a fitted estimator to feature selector or call fit before calling transform.

【问题讨论】:

    标签: python scikit-learn linear-discriminant


    【解决方案1】:

    您的方法存在一个整体问题:KNeighborsClassifier 没有对特征重要性的内在度量。因此,它与 RFECV 不兼容,因为它的文档说明了分类器:

    具有拟合方法的监督学习估计器,通过 coef_ 属性或 feature_importances_ 属性提供有关特征重要性的信息。

    KNeighborsClassifier 肯定会失败。您肯定需要另一个分类器,例如 RandomForestClassifierSVC

    如果您可以选择另一个分类器,您的流水线仍需要公开估算器在您的流水线中的特征重要性。为此,您可以在此处参考此answer,它为此定义了一个自定义管道:

    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([
        ('normalizer', Normalizer()),
        ('ldm', LinearDiscriminantAnalysis(n_components=2)),
        ('rf', RandomForestClassifier())
    ])
    

    它应该可以工作。

    【讨论】:

    • 对不起,我觉得我说得不够清楚。我不知道如何使用我的代码中的管道让 RFECV 工作。我不断收到上面显示的值错误。但是,如果我不包括 LinearDiscriminantAnalysis() 步骤,它确实有效。
    • 但是你的方法是徒劳的,因为KNeighborsClassifier 没有内在的特征重要性度量。您需要一个可以计算此类度量的分类器才能使用RFECV
    • 你可以看看我更新的答案。
    • 谢谢你,现在有意义
    猜你喜欢
    • 2021-05-23
    • 2020-07-10
    • 2021-12-31
    • 2018-12-27
    • 2019-06-04
    • 2021-12-26
    • 2017-09-08
    • 2018-12-13
    • 2021-08-16
    相关资源
    最近更新 更多