You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

RFECV推荐3个最优特征,如何选择1或2个特征构建模型?

如何在RFECV推荐3个特征时选择1个或2个特征

你可以借助已训练完成的rfecv对象及相关工具,从以下几种实用方法中选择适合的方式来筛选1个或2个特征:

方法1:利用RFECV的特征排名直接筛选

RFECV在递归消除过程中会为每个特征生成排名,排名为1的是最终保留的最优3个特征。如果要选1个或2个特征,优先从排名靠前的特征里挑选即可:

# 获取所有特征的排名,数值越小排名越靠前
feature_ranks = rfecv.ranking_
# 按排名从小到大排序,得到特征索引列表
sorted_feature_indices = sorted(range(len(feature_ranks)), key=lambda i: feature_ranks[i])

# 提取排名前1的特征索引
top_1_features = sorted_feature_indices[:1]
# 提取排名前2的特征索引
top_2_features = sorted_feature_indices[:2]

print("排名前1的特征索引:", top_1_features)
print("排名前2的特征索引:", top_2_features)

方法2:结合交叉验证得分曲线选择

参考你代码生成的交叉验证得分图,查看特征数为1和2时的模型性能,再结合特征排名确定最终选择:

# 提取不同特征数量对应的平均验证得分
feature_counts = range(min_features_to_select, n_scores + min_features_to_select)
score_map = dict(zip(feature_counts, rfecv.cv_results_["mean_test_score"]))

# 查看1个、2个特征时的平均准确率
print("1个特征时的平均准确率:", score_map[1])
print("2个特征时的平均准确率:", score_map[2])

如果1个特征的性能符合预期,直接选排名第一的特征;如果2个特征的性能更优,就选排名前两位的特征。

方法3:用RFE手动指定特征数量

直接使用RFE类(区别于自动选数量的RFECV),手动设置要保留的特征数,能直接得到对应数量的最优特征:

from sklearn.feature_selection import RFE

# 筛选1个特征
rfe_1 = RFE(estimator=clf, n_features_to_select=1, step=1)
rfe_1.fit(X, y)
top_1_features_rfe = [idx for idx, is_selected in enumerate(rfe_1.support_) if is_selected]

# 筛选2个特征
rfe_2 = RFE(estimator=clf, n_features_to_select=2, step=1)
rfe_2.fit(X, y)
top_2_features_rfe = [idx for idx, is_selected in enumerate(rfe_2.support_) if is_selected]

print("RFE选出的1个特征索引:", top_1_features_rfe)
print("RFE选出的2个特征索引:", top_2_features_rfe)

补充提示

由于你的数据包含冗余特征,不同方法选出的特征可能略有差异。如果有业务场景,建议优先选择业务上更易解释的特征,同时确保模型性能在可接受范围内。

内容的提问来源于stack exchange,提问作者user2543622

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 22:13:08