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']
相关推荐
狂小虎2 小时前
亲测解决self.transform is not exist
python·深度学习
黑鹿0222 小时前
机器学习基础(四) 决策树
人工智能·决策树·机器学习
Fxrain2 小时前
[深度学习]搭建开发平台及Tensor基础
人工智能·深度学习
molunnnn3 小时前
day 18进行聚类,进而推断出每个簇的实际含义
机器学习·数据挖掘·聚类
Humbunklung3 小时前
机器学习算法分类
算法·机器学习·分类
一叶知秋秋3 小时前
python学习day39
人工智能·深度学习·学习
weixin_448781623 小时前
DenseNet算法 实现乳腺癌识别
pytorch·深度学习·神经网络
zzc9214 小时前
MATLAB仿真生成无线通信网络拓扑推理数据集
开发语言·网络·数据库·人工智能·python·深度学习·matlab
编程有点难5 小时前
Python训练打卡Day43
开发语言·python·深度学习
2301_805054565 小时前
Python训练营打卡Day48(2025.6.8)
pytorch·python·深度学习