通过 Sklearn 的 RFECV(带有交叉验证的递归特征消除)选择特定数量的特征

toe*_*uce 4 python machine-learning feature-extraction scikit-learn cross-validation

我想知道 Sklearn 的 RFECV 是否可以选择固定数量的最重要的功能。例如,在处理具有 617 个特征的数据集时,我一直在尝试使用 RFECV 来查看其中哪 5 个特征最重要。然而,RFECV 没有参数“n_features_to_select”,不像 RFE(这让我很困惑)。我该如何处理?

sha*_*uga 5

根据这个quora帖子

RFECV 对象有助于使用交叉验证来调整或查找此 n_f​​eatures 参数。对于消除“步骤”数量特征的每一步,它都会计算验证数据的分数。在验证数据上给出最大分数的步骤中剩余的特征数被认为是数据的“最佳 n_features”。

这表示 RFECV 确定最佳特征数 (n_features) 以获得最佳结果。
拟合RFECV对象包含ranking_ 具有特征排名的属性和support_用于选择找到的最佳特征的掩码。
但是,如果您必须从 RFECV 中选择 top n_features,则可以使用该ranking_属性

optimal_features = X[:, selector.support_] # selector is a RFECV fitted object

n = 6 # to select top 6 features
feature_ranks = selector.ranking_  # selector is a RFECV fitted object
feature_ranks_with_idx = enumerate(feature_ranks)
sorted_ranks_with_idx = sorted(feature_ranks_with_idx, key=lambda x: x[1])
top_n_idx = [idx for idx, rnk in sorted_ranks_with_idx[:n]]

top_n_features = X[:5, top_n_idx]
Run Code Online (Sandbox Code Playgroud)

参考: sklearn 文档Quora 帖子