我想知道Sklearn的RFECV是否可以选择固定数量的最重要特征。例如,在一个具有617个特征的数据集上工作,我一直在尝试使用RFECV来确定哪5个特征是最重要的。然而,与令我困惑的RFE不同,RFECV没有参数'n_features_to_select'。我该如何处理?
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]
我知道这是一个老问题,但我认为它仍然相关。
我不认为shanmuga的解决方案是正确的,因为同一级别内的功能并没有按重要性排序。也就是说,如果selector.ranking_
有3个等级为1的特征,我不认为列表中的第一个比第二个或第三个更重要。
解决这个问题的一个天真的方法是在设置n_features_to_select
为所需数量并进行“手动”交叉验证的同时运行RFE
。
如果您想从最佳m个特征中选择n个特征(其中n<m),可以执行以下操作:
# 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]]
您需要注意的是,多个功能可能具有相同的重要性或系数,您在使用此方法时可能会将它们忽略。