RFE
简单介绍
- 算法思想:wrapper的一种,递归特征删除法是不断训练模型,每次训练完毕删除掉n个重要性低的特征,然后对新的特征再次进行训练,又一次得到特征重要性,再次删除n个重要性低的特征,直到特征数满足自己的设定。
- sklearn中的RFE函数调用时,根据基模型的“coef_ 属性 或者 feature_importances_ ”属性来得到特征的重要性。
- 我们也可以自己实现递归特征删除方法。
具体实现
- 参数说明:estimator参数指明基模型,n_features_to_select指定最终要保留的特征数量,step为整数时设置每次要删除的特征数量,当小于1时,每次去除权重最小的特征。
1
2
3
4
5
6
7
8
9
10
11from sklearn import datasets
from sklearn.feature_selection import RFE
from sklearn.linear_model import LogisticRegression
all=datasets.load_iris()
model=LogisticRegression()
rfe=RFE(estimator=model,n_features_to_select=1,step=1)
rfemodel=rfe.fit(all.data,all.target)
print(rfe.support_)
print(rfe.ranking_)
RFECV
简单介绍
- 通过交叉验证来找到最优的特征数量,这里的交叉验证与我们经常见到的不同,不是不同行组合然后求平均,而是不同列的组合求均值,得到最优的特征数量。如果减少特征会造成性能损失,那么将不会去除任何特征。
- 这个方法用以选取单模型特征相当不错,但是有两个缺陷,一,计算量大,运行一次需要很久时间。二,随着学习器(评估器)的改变,最佳特征组合也会改变,有些时候会造成不利影响。因此适合在模型确定后进行特征再次选择。三、更改最小特征数,运行结果会发生变化(都没有达到最小特征数的情况下)。
- 首先计算没有删除任何特征的score;接着每次计算删除“step“个特征的情况,会计算所有组合情况,得到平均的score;以此类推,一直重复,直到到达最小删除特征数。然后会给出每个特征的评分,以及选出最优特征子集。
具体代码实现
- 参数说明:step整数时,每次去除的特征个数,小于1时,每次去除权重最小的特征;scoring字符串类型,选择sklearn中的scorer作为输入对象;cv默认为3;min_features_to_select:设定最少的特征数(如果模型有特征数量限制,比如随机森林设置了最大特征数,则此变量需要大于等于该值)。
- 代码说明:以下代码拷贝自sklearn官网,做了部分修改.
- grid_scores_:每个值代表了此次迭代所有特征组合得到的score的平均值。
- ranking_:每个特征的得分。
- support_:此特征是否入选最后特征。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30import matplotlib.pyplot as plt
from sklearn.svm import SVC
from sklearn.model_selection import StratifiedKFold
from sklearn.feature_selection import RFECV
from sklearn.datasets import make_classification
## 将n_classes=8改为2,应该想要尝试scroing=‘roc_auc’,这个只适用于二分类。
# Build a classification task using 3 informative features
X, y = make_classification(n_samples=1000, n_features=25, n_informative=3,
n_redundant=2, n_repeated=0, n_classes=2,
n_clusters_per_class=1, random_state=0)
# Create the RFE object and compute a cross-validated score.
svc = SVC(kernel="linear")
# The "accuracy" scoring is proportional to the number of correct
# classifications
rfecv = RFECV(estimator=svc, step=1, cv=StratifiedKFold(2),
scoring='roc_auc')
rfecv.fit(X, y)
print("Optimal number of features : %d" % rfecv.n_features_)
print(ranking_)
print(support_)
print(rfecv.grid_scores_)
# Plot number of features VS. cross-validation scores
plt.figure()
plt.xlabel("Number of features selected")
plt.ylabel("Cross validation score (nb of correct classifications)")
plt.plot(range(1, len(rfecv.grid_scores_) + 1), rfecv.grid_scores_)
plt.show()