sklearn学习——递归特征消除法(RFE)

news/2025/5/24 2:21:23

sklearn学习——递归特征消除法(RFE)

1 作用

  1. 消除特征之间的冗余,选取最优特征组合。
  2. 降低特征维数。

2 步骤

  1. 将筛选的k个特征作为初始特征子集输入到随机森林分类器中,计算得到每个特征的重要性,并利用交叉验证方法得到初始特征子集的分类精度;
  2. 从当前特征子集中移除特征重要性最低的一个特征,得到一个新的特征子集,再次输入到随机森林分类器中,计算新的特征子集中每个特征的重要性,并利用交叉验证方法得到新的特征子集的分类精度。
  3. 递归的重复步骤2,直至特征子集为空,最后一共得到k个不同特征数量的特征子集,选择分类精度最高的特征子集作为最优特征组合

3 数据

WFs1

4 代码实现

import pandas as pd
from sklearn.ensemble import RandomForestClassifier as RFC
from sklearn.model_selection import cross_val_score
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler
from sklearn.feature_selection import RFECV
from sklearn.feature_selection import RFE
# 1.读取训练数据集
data = pd.read_csv(r"WFs1.csv")
X = data.iloc[:, 1:]
Y = data.iloc[:, 0]
print(X.shape)# 1.标准化处理
scaler = StandardScaler()
X_train = scaler.fit_transform(X)# 2.构建RF模型
RFC_ = RFC()                               # 随机森林
c = RFC_.fit(X, Y).feature_importances_    # 特征重要性
print("重要性:")
print(c)# 3. 交叉验证递归特征消除法
selector = RFECV(RFC_, step=1, cv=10)       # 采用交叉验证,每次排除一个特征,筛选出最优特征
selector = selector.fit(X, Y)
X_wrapper = selector.transform(X)          # 最优特征
score =cross_val_score(RFC_ , X_wrapper, Y, cv=10).mean()   # 最优特征分类结果
print(score)
print("最佳数量和排序")
print(selector.support_)                                    # 选取结果
print(selector.n_features_)                                 # 选取特征数量
print(selector.ranking_)                                    # 依次排数特征排序# 4.递归特征消除法
selector1 = RFE(RFC_, n_features_to_select=3, step=1).fit(X, Y)       # n_features_to_select表示筛选最终特征数量,step表示每次排除一个特征
selector1.support_.sum()
print(selector1.ranking_)                                             # 特征排除排序
print(selector1.n_features_)                                          # 选择特征数量
X_wrapper1 = selector1.transform(X)                                   # 最优特征
score =cross_val_score(RFC_, X_wrapper1, Y, cv=9).mean()
print(score)# 5.递归特征消除法和曲线图选取最优特征数量
score = []                                                            # 建立列表
for i in range(1, 8, 1):X_wrapper = RFE(RFC_, n_features_to_select=i, step=1).fit_transform(X, Y)    # 最优特征once = cross_val_score(RFC_, X_wrapper, Y, cv=9).mean()                      # 交叉验证score.append(once)                                                           # 交叉验证结果保存到列表
print(max(score), (score.index(max(score))*1)+1)                                 # 输出最优分类结果和对应的特征数量
print(score)
plt.figure(figsize=[20, 5])
plt.plot(range(1, 8, 1), score)
plt.xticks(range(1, 8, 1))
plt.show()

5 结果

在这里插入图片描述


https://dhexx.cn/news/show-2654225.html

相关文章

Java Code Review清单

2019独角兽企业重金招聘Python工程师标准>>> 整洁的代码 清单项目分类使用可以表达实际意图(Intention-Revealing)的名称有意义的名称每一个概念只用一个词有意义的名称使用方案/问题领域名称有意义的名称类应该是比较小的!类函数应该是比较小的!函数只做一件事函数…

LeetCode Generate Parentheses

题目: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. For example, given n 3, a solution set is: "((()))", "(()())", "(())()", "()(())", "()()(…

python起步——可变对象和不可变对象

学习python了一小段时间,觉得整体上还是真的让程序更好写了。   学习过程中,突然想到一个问题——我之前博客写过的一篇文章,关于不用第三个数交换a、b的问题:http://www.cnblogs.com/FreeAquar/archive/2012/07/22/2603381.htm…

Java学习笔记(1)——常用cmd命令与Java编制编译

Java学习笔记——常用cmd命令与Java编制编译 1 JDK下载安装与环境配置 附上链接 2 常用cmd命令 dir 列出当前目录下的文件以及文件夹md 创建目录rd 删除目录cd 进入指定目录cd… 退回到上一级目录del 删除文件 3 Java特点 简单性面向对象分布式健壮性安全性体系结构中立…

华为防火墙-适合CSSIP方向

新版的OS初始console的用户名:admin,密码:Admin123连接console进入设备: Copyright(C) 2010-2013 Huawei Technologies Co., Ltd. *All rights reserved *Without the owners prior written consent, *no decompiling or reverse-…

LeetCode Letter Combinations of a Phone Number

题目: Given a digit string, return all possible letter combinations that the number could represent. A mapping of digit to letters (just like on the telephone buttons) is given below. Input:Digit string "23" Output: ["ad", &q…

Java学习笔记(2)——基础语法

Java学习——基础语法 1 第一个Java程序 public class 后面采用的类名和文件名保持一样,一个Java程序里面只有一个public class;class后面类名必须以字母开头,后面可以跟字母和数字的任意组合;System.out.println(&a…

LeetCode Clone Graph

题目: Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors. OJs undirected graph serialization: Nodes are labeled uniquely. We use # as a separator for each node, and , as a separator for node label and …

彩票问题,长度为6的int型数组,要求取值为1-30,同时元素值各不相同

题目 创建一个长度为6的int型数组&#xff0c;要求取值为1-30&#xff0c;同时元素值各不相同 解法 class CaiPiaoNumber {public static void main(String[] args) {int[] arr new int[6]; // 创建数组for (int i 0; i <arr.length ; i) { …

Nginx 学习笔记(三)Nginx + flv

环境 ubuntu 12.04 搭建视频服务器&#xff0c;播放flv和MP4文件&#xff0c;webserver用Nginx&#xff0c;编译增加http_flv_module;播放器使用开源的jw player。 nginx在ubuntu上用apt-get安装默认编译选项里面没有http_flv_module,所以需要重新编译一遍&#xff0c;顺便升级…