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']
相关推荐
自学机械人的小白ing20 分钟前
深度学习系统学习
人工智能·深度学习·学习
HyperAI超神经22 分钟前
128K长上下文+智能体强化训练!LFM2.5-2.6B解锁端侧大模型高效部署;DETR用Transformer斩断NMS与Anchor,重塑目标检测
人工智能·深度学习·目标检测·计算机视觉·数据集·transformer
watersink29 分钟前
机器学习PCA
人工智能·机器学习
逻辑君36 分钟前
科技逆向外语|20260808
人工智能·科技·机器学习
ShallWeL1 小时前
【机器学习】(40)—— 流水线监控
人工智能·机器学习·流水线监控
Uncommon.2 小时前
使用pandas处理csv并转为张量
pytorch·python·深度学习·pandas
安逸Ai2 小时前
Batch Normalization 和 Layer Normalization 有什么用?
人工智能·机器学习·程序员
柳叶方舟2 小时前
Nature Medicine IF=50.0 | 公众医疗助手LLM可靠性存隐忧:真人交互表现未优于对照组,现有评估基准失效
论文阅读·人工智能·深度学习·交互·健康医疗
手写码匠3 小时前
华为云Flexus+DeepSeek征文|Dify 多 Agent 评测实战:用 DeepSeek-R1 当裁判,打造多智能体系统的自动化质量保障体系
人工智能·深度学习·算法·aigc