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']
相关推荐
烟锁池塘柳018 分钟前
【深度学习】强化学习(Reinforcement Learning, RL)主流架构解析
人工智能·深度学习·机器学习
Ronin-Lotus2 小时前
深度学习篇---Yolov系列
人工智能·深度学习
爱学习的茄子2 小时前
AI驱动的单词学习应用:从图片识别到语音合成的完整实现
前端·深度学习·react.js
AI数据皮皮侠3 小时前
中国区域10m空间分辨率楼高数据集(全国/分省/分市/免费数据)
大数据·人工智能·机器学习·分类·业界资讯
张德锋4 小时前
Pytorch实现天气识别
机器学习
晓13134 小时前
第七章 OpenCV篇——角点检测与特征检测
人工智能·深度学习·计算机视觉
Wilber的技术分享6 小时前
【机器学习实战笔记 14】集成学习:XGBoost算法(一) 原理简介与快速应用
人工智能·笔记·算法·随机森林·机器学习·集成学习·xgboost
19896 小时前
【零基础学AI】第26讲:循环神经网络(RNN)与LSTM - 文本生成
人工智能·python·rnn·神经网络·机器学习·tensorflow·lstm
victory04317 小时前
SpiceMix enables integrative single-cell spatial modeling of cell identity 文章解读
人工智能·深度学习
JoernLee7 小时前
机器学习算法:支持向量机SVM
人工智能·算法·机器学习