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']
相关推荐
小鸡吃米…4 小时前
机器学习 - K - 中心聚类
人工智能·机器学习·聚类
MM_MS5 小时前
Halcon变量控制类型、数据类型转换、字符串格式化、元组操作
开发语言·人工智能·深度学习·算法·目标检测·计算机视觉·视觉检测
齐齐大魔王6 小时前
Pascal VOC 数据集
人工智能·深度学习·数据集·voc
Hcoco_me7 小时前
RNN(循环神经网络)
人工智能·rnn·深度学习
武子康8 小时前
大数据-209 深度理解逻辑回归(Logistic Regression)与梯度下降优化算法
大数据·后端·机器学习
柠柠酱10 小时前
【深度学习Day5】决战 CIFAR-10:手把手教你搭建第一个“正经”的卷积神经网络 (附调参心法)
深度学习
gravity_w10 小时前
Hugging Face使用指南
人工智能·经验分享·笔记·深度学习·语言模型·nlp
少林码僧11 小时前
2.29 XGBoost、LightGBM、CatBoost对比:三大梯度提升框架选型指南
人工智能·机器学习·ai·数据挖掘·数据分析·回归
春日见11 小时前
控制算法:PP(纯跟踪)算法
linux·人工智能·驱动开发·算法·机器学习
Yeats_Liao11 小时前
MindSpore开发之路(二十六):系列总结与学习路径展望
人工智能·深度学习·学习·机器学习