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']
相关推荐
kkzhang43 分钟前
Concept Bottleneck Models-概念瓶颈模型用于可解释决策:进展、分类体系 与未来方向综述
深度学习
木非哲2 小时前
机器学习--随机森林--从一棵树的直觉到一片林的哲学
人工智能·随机森林·机器学习
程序员打怪兽2 小时前
详解YOLOv8网络结构
人工智能·深度学习
A尘埃3 小时前
保险公司车险理赔欺诈检测(随机森林)
算法·随机森林·机器学习
饭饭大王6664 小时前
CANN 生态中的轻量化部署利器:`lite-inference` 项目实战解析
深度学习
MSTcheng.4 小时前
CANN ops-math:AI 硬件端高效数学运算的算子设计与工程化落地方法
人工智能·深度学习·cann
Dev7z4 小时前
基于深度学习的肺部听诊音疾病智能诊断方法研究
人工智能·深度学习
像风一样的男人@5 小时前
python --读取psd文件
开发语言·python·深度学习
大江东去浪淘尽千古风流人物6 小时前
【SLAM新范式】几何主导=》几何+学习+语义+高效表示的融合
深度学习·算法·slam
yuanyuan2o26 小时前
【深度学习】全连接、卷积神经网络
人工智能·深度学习·cnn