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

Selecting a Specific Number of Features via Sklearn's RFECV (Recursive Feature Elimination with Cross-validation)

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

据此quora post

The RFECV object helps to tune or find this n_features parameter using cross-validation. For every step where "step" number of features are eliminated, it calculates the score on the validation data. The number of features left at the step which gives the maximum score on the validation data, is considered to be "the best n_features" of your data.

这表示 RFECV 确定最佳特征数 (n_features) 以获得最佳结果。
拟合的 RFECV 对象包含具有特征排名的属性 ranking_,并且 support_ 屏蔽 select 找到的最佳特征。
但是,如果您 MUST select 来自 RFECV 的顶部 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]

参考: sklearn documentation, Quora post

我知道这是一个老问题,但我认为它仍然相关。

我认为 shanmuga 的解决方案不正确,因为同一等级内的特征未按重要性排序。也就是说,如果 selector.ranking_ 有 3 个等级为 1 的特征,我认为列表中的第一个不一定比第二个或第三个更重要。

这个问题的一个天真的解决方案是 运行 RFE 同时将 n_features_to_select 设置为所需的数字并“手动”交叉验证它。

如果你想从最优的 m 个特征中选择 n 个特征(n

# selector is a RFECV fitted object
feature_importance = selector.estimator_.feature_importances_  # or coef_
feature_importance_sorted = sorted(enumerate(feature_importance), key=lambda x: x[1])
top_n_idx = [idx for idx, _ in feature_importance_sorted[:n]]

您应该注意,多个特征可能具有相同的重要性或系数,您可能会用这种方法忽略它。