sklearn.feature_selection.SelectFromModel利用模型筛选特征

sklearn.feature_selection.SelectFromModel模型筛选特征

以随机森林为例,查看随机森林之类的模型使用的特征。有两种使用方式:

1, 使用未训练的模型
python 复制代码
from sklearn.feature_selection import SelectFromModel
from sklearn.ensemble import RandomForestClassifier
X = [[ 0.87, -1.34,  0.31 ],
     [-2.79, -0.02, -0.85 ],
     [-1.34, -0.48, -2.55 ],
     [ 1.92,  1.48,  0.65 ]]
y = [0, 1, 0, 1]

# 输入参数包括estimator, threshold:筛选阈值, prefit=False:是否训练过,max_features:最大特征数
selector = SelectFromModel(estimator=LogisticRegression(), threshold=0.5).fit(X, y)

# 筛选的特征的阈值
selector.threshold_ # 0.5

# 特征支持的布尔表
selector.get_support() # array([False,  True, False])

# 对输入进行特征筛选
X_new = selector.transform(X)

# 查看筛选出的特征名称,需要给出特征的名称列表,如果是pandas,就可以输入x.columns
selector.get_feature_names_out(['a', 'b', 'c']) # ['b']
2, 使用训练模型
python 复制代码
from sklearn.feature_selection import SelectFromModel
from sklearn.ensemble import RandomForestClassifier
X = [[ 0.87, -1.34,  0.31 ],
     [-2.79, -0.02, -0.85 ],
     [-1.34, -0.48, -2.55 ],
     [ 1.92,  1.48,  0.65 ]]
y = [0, 1, 0, 1]


rfc = rfc=RandomForestClassifier(n_estimators=9, max_depth=6,random_state=9)
rfc.fit(X, y)
selector = SelectFromModel(rfc, prefit=True)

# 筛选的特征的阈值
selector.threshold_ # 0.55249

# 特征支持的布尔表
selector.get_support() # array([False,  True, False])

# 对输入进行特征筛选
X_new = selector.transform(X)

# 查看筛选出的特征名称,需要给出特征的名称列表,如果是pandas,就可以输入x.columns
selector.get_feature_names_out(['a', 'b', 'c']) # ['b']
相关推荐
上进小菜猪37 分钟前
基于 YOLOv8 的多水果智能识别系统工程化实战 [目标检测完整源码]
深度学习
zylyehuo2 小时前
【强化学习的数学原理-赵世钰】随记
机器学习
MoonOutCloudBack2 小时前
VeRL 框架中的奖励 (reward) 与奖励模型:从 PPO 配置到实现细节
人工智能·深度学习·语言模型·自然语言处理
alfred_torres2 小时前
MedIA 2025 | TopoTxR:拓扑学“外挂”加持,深度学习精准预测乳腺癌化疗响应
人工智能·深度学习·拓扑学
小雨中_2 小时前
3.1 RLHF:基于人类反馈的强化学习
人工智能·python·深度学习·算法·动态规划
phoenix@Capricornus3 小时前
初等数学中点到直线的距离
人工智能·算法·机器学习
Fairy要carry3 小时前
面试-冷启动
深度学习
硅谷秋水4 小时前
通过测试-时强化学习实现VLA的动态自适应
深度学习·机器学习·计算机视觉·语言模型·机器人
小锋java12344 小时前
【技术专题】PyTorch2 深度学习 - 张量(Tensor)的定义与操作
pytorch·深度学习
小雨中_5 小时前
2.9 TRPO 与 PPO:从“信赖域约束”到“近端裁剪”的稳定策略优化
人工智能·python·深度学习·机器学习·自然语言处理