python特征选择(一款非常棒的特征选择工具:feature-selector)

前言

       FeatureSelector是用于降低机器学习数据集的维数的工具。

       文章介绍地址
       项目地址

       本篇主要介绍一个基础的特征选择工具feature-selector,feature-selector是由Feature Labs的一名数据科学家williamkoehrsen写的特征选择库。feature-selector主要对以下类型的特征进行选择:

       1.具有高missing-values百分比的特征
       2.具有高相关性的特征
       3.对模型预测结果无贡献的特征(即zero importance)
       4.对模型预测结果只有很小贡献的特征(即low importance)
       5.具有单个值的特征(即数据集中该特征取值的集合只有一个元素)

       从上面可以看出feature-selector确实是非常基础的特征选择工具,正因为非常的基础,所以才非常的常用(这也是为什么williamkoehrsen要写这个特征选择库的原因),在拿到一个数据集的时候,往往都需要将上述类型的特征从数据集中剔除掉。针对上面五种类型的特征,feature-selector分别提供以下五个函数来对此处理:

       1.identify_missing()
       2.identify_collinear(
)
       3.identify_zero_importance()
       4.identify_low_importance(
)
       5.identify_single_unique(*)

1.数据集选择

       在这里使用自己的训练数据集。文章末尾附上链接。数据集采样代码如下:

import pandas as pd
import numpy as np
data = pd.read_csv('base_train_sum.csv')
data

在这里插入图片描述

2.feature-selector用法

       导入数据并创建feaure-selector实例
注意:
       作者并没有把feature-selector发布到pypi上,所以不能使用pip和conda进行安装,只能手动从github下载下来,然后把feature_selector.py文件放到当前工作目录,然后再进行import操作。

# feature-selector用法

# 导入数据并创建feaure-selector实例
import pandas as pd
from feature_selector import FeatureSelector
# 数据集中TARGET字段为对应样本的label
train_labels = data.flag
# 获取all features
train_features = data.drop(columns='flag')
# 创建 feature-selector 实例,并传入features 和labels
# fs = FeatureSelector(data = train_features,lables = train_labels)
fs = FeatureSelector(data = train_features, labels = train_labels)

3.具有高missing-values百分比的特征

       该方法用于选择出missing value 百分比大于60%的特征用于选择missing value 百分比大于指定值(通过missing_threshold指定百分比)的feature。该方法能应用于监督学习和非监督学习的特征选择。

fs.identify_missing(missing_threshold=0.6)
# 查看选择出的特征
# fs.ops['missing']
missing_features = fs.ops['missing']
print(missing_features[:10])
# 绘制所有特征missing value百分比的直方图
fs.plot_missing()

在这里插入图片描述
       说明咋没有属性缺失值达到 60%以上
       该方法内部使用pandas 统计数据集中所有feature的missing value 的百分比,然后选择出百分比大于阈值的特征,详见feature-selector.py的114-136行。
https://github.com/WillKoehrsen/feature-selector/blob/master/feature_selector/feature_selector.py#L114-L136

For detailed information on the missing fractions, we can access the missing_stats attribute, a dataframe of the missing fractions for all features.

fs.missing_stats.head(10)

在这里插入图片描述

4.具有高相关性的特征

       该方法用于选择相关性大于指定值(通过correlation_threshold指定值)的feature。该方法同样适用于监督学习和非监督学习。

# 不对feature进行one-hot encoding(默认为False), 然后选择出相关性大于0.0000005%的feature, 
fs.identify_collinear(correlation_threshold=0.0000005, one_hot=False)

在这里插入图片描述
       查看选择的feature

correlated_features = fs.ops['collinear']
correlated_features[:5]

在这里插入图片描述
中文显示设置

from pylab import *
mpl.rcParams['font.sans-serif'] = ['SimHei']

绘制选择的特征的相关性heatmap

fs.plot_collinear()

在这里插入图片描述
To plot all of the correlations in the data, we can pass in plot_all = True to the plot_collinear function.

fs.plot_collinear(plot_all=True)

在这里插入图片描述
To view the details of the corelations above the threshold, we access the record_collinear attribute which is a dataframe. The drop_feature will be removed and for each feature that will be removed, there may be several correlations it has with the corr_feature that are above the correlation_threshold.

fs.identify_collinear(correlation_threshold=0.0000005)
fs.plot_collinear()

在这里插入图片描述

5.对模型预测结果无贡献的特征

       该方法用于选择对模型预测结果毫无贡献的feature(即zero importance,从数据集中去除或者保留该feature对模型的结果不会有任何影响)。

       该方法以及之后的identify_low_importance都只适用于监督学习(即需要label,这也是为什么实例化feature-selector时需要传入labels参数的原因)。feature-selector通过用数据集训练一个梯度提升机(Gradient Boosting machine, GBM),然后由GBM得到每一个feature的重要性分数,对所有特征的重要性分数进行归一化处理,选择出重要性分数等于零的feature。

       为了使计算得到的feature重要性分数具有很小的方差,identify_zero_importance内部会对GBM训练多次,取多次训练的平均值,得到最终的feature重要性分数。同时为了防止过拟合,identify_zero_importance内部从数据集中抽取一部分作为验证集,在训练GBM的时候,计算GBM在验证集上的某一metric,当metric满足一定条件时,停止GBM的训练。

# 选择zero importance的feature,
#
# 参数说明:
#          task: 'classification' / 'regression', 如果数据的模型是分类模型选择'classificaiton',
#                否则选择'regression'
#          eval_metric: 判断提前停止的metric. for example, 'auc' for classification, and 'l2' for regression problem
#          n_iteration: 训练的次数
#          early_stopping: True/False, 是否需要提前停止
fs.identify_zero_importance(task = 'classification', eval_metric = 'auc', 
                            n_iterations = 10, early_stopping = True)

在这里插入图片描述
Running the gradient boosting model requires one hot encoding the features. These features are saved in the one_hot_features attribute of the FeatureSelector. The original features are saved in the base_features..

one_hot_features = fs.one_hot_features
base_features = fs.base_features
print('There are %d original features' % len(base_features))
print('There are %d one-hot features' % len(one_hot_features))

在这里插入图片描述

fs.data_all.head(10)

保存本地

fs.data_all.to_csv('xx.csv',index=False,index_label=False,encoding='utf-8-sig')

在这里插入图片描述
查看选择出的zero importance feature

zero_importance_features = fs.ops['zero_importance']
zero_importance_features

在这里插入图片描述

# 绘制feature importance 关系图
# 参数说明:
#          plot_n: 指定绘制前plot_n个最重要的feature的归一化importance条形图,如图4所示
#          threshold: 指定importance分数累积和的阈值,用于指定图4中的蓝色虚线.
#              蓝色虚线指定了importance累积和达到threshold时,所需要的feature个数。
#              注意:在计算importance累积和之前,对feature列表安装feature importance的大小
#                   进行了降序排序
fs.plot_feature_importances(threshold=0.99, plot_n=12)

在这里插入图片描述
在这里插入图片描述
21 features required for 0.99 of cumulative importance

All of the feature importances are accessible in the feature_importances attribute of the FeatureSelector

fs.feature_importances.head(21)

在这里插入图片描述
We could use these results to select only the ‘n’ most important features. For example, if we want the top 100 most importance, we could do the following.

one_hundred_features = list(fs.feature_importances.loc[:99, 'feature'])
one_hundred_features

在这里插入图片描述

len(one_hundred_features)

在这里插入图片描述

6.对模型预测结果只有很小贡献的特征

       该方法是使用identify_zero_importance计算的结果,选择出对importance累积和达到指定阈值没有贡献的feature(这样说有点拗口),即图5中蓝色虚线之后的feature。该方法只适用于监督学习。identify_low_importance有点类似于PCA中留下主要分量去除不重要的分量。

# 选择出对importance累积和达到99%没有贡献的feature
fs.identify_low_importance(cumulative_importance=0.99)

# 查看选择出的feature
fs.ops['low_importance']

在这里插入图片描述

7.具有单个值的特征

       该方法用于选择只有单个取值的feature,单个值的feature的方差为0,对于模型的训练不会有任何作用(从信息熵的角度看,该feature的熵为0)。该方法可应用于监督学习和非监督学习。

# 选择出只有单个值的feature
fs.identify_single_unique()

# 查看选择出的feature
fs.ops['single_unique']

#绘制所有feature unique value的直方图
fs.plot_unique()

在这里插入图片描述

8.从数据集去除选择的特征

       上面介绍了feature-selector提供的特征选择方法,这些方法从数据集中识别了feature,但并没有从数据集中将这些feature去除。feature-selector中提供了remove方法将选择的特征从数据集中去除,并返回去除特征之后的数据集。

# 去除所有类型的特征
#    参数说明:
#       methods: 
#               desc:  需要去除哪些类型的特征
#               type:  string / list-like object
#             values:  'all' 或者是 ['missing', 'single_unique', 'collinear', 'zero_importance', 'low_importance']
#                      中多个方法名的组合
#      keep_one_hot: 
#              desc: 是否需要保留one-hot encoding的特征
#              type: boolean
#              values: True/False
#              default: True
# train_removed = fs.remove(methods = 'all', keep_one_hot=False)
train_no_missing = fs.remove(methods = ['missing'])

在这里插入图片描述

train_no_missing_zero = fs.remove(methods = ['missing', 'zero_importance'])

在这里插入图片描述
To remove the features from all of the methods, pass in method=‘all’. Before we do this, we can check how many features will be removed using check_removal. This returns a list of all the features that have been idenfitied for removal.

all_to_remove = fs.check_removal()
all_to_remove[:25]

在这里插入图片描述
Now we can remove all of the features idenfitied.

train_removed = fs.remove(methods = 'all')

在这里插入图片描述
去除不需要的特征生成新的文件
在这里插入图片描述
在这里插入图片描述
Handling One-Hot Features

If we look at the dataframe that is returned, we may notice several new columns that were not in the original data. These are created when the data is one-hot encoded for machine learning. To remove all the one-hot features, we can pass in keep_one_hot = False to the remove method.

train_removed_all = fs.remove(methods = 'all', keep_one_hot=False)

在这里插入图片描述

print('Original Number of Features', train_features.shape[1])
print('Final Number of Features: ', train_removed_all.shape[1])

在这里插入图片描述
一次性选择所有类型的特征

feature-selector除了能每次运行一个identify_*函数来选择一种类型特征外,还可以使用identify_all函数一次性选择5种类型的特征选。

fs = FeatureSelector(data = train_features, labels = train_labels)

fs.identify_all(selection_params = {'missing_threshold': 0.6, 'correlation_threshold': 0.98, 
                                    'task': 'classification', 'eval_metric': 'auc', 
                                     'cumulative_importance': 0.99})

在这里插入图片描述

train_removed_all_once = fs.remove(methods = 'all', keep_one_hot = True)

在这里插入图片描述

fs.feature_importances.head(100)

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

个人微信公众号,专注于学习资源、笔记分享,欢迎关注。我们一起成长,一起学习。一直纯真着,善良着,温情地热爱生活,,如果觉得有点用的话,请不要吝啬你手中点赞的权力,谢谢我亲爱的读者朋友
五角钱的程序员,专注于学习资源、笔记分享。

Wisdom is often times nearer when we stoop than when we soar.
– William Wordsworth
「比起高飞的时候,智慧往往在我们俯身时更接近我们。」– 威廉‧华兹华斯

参考:https://cloud.tencent.com/developer/article/1374205

数据链接:https://pan.baidu.com/s/1YOYmaBlxaYD4Ouztwm_K_w
提取码:g2gt

9.结论

本笔记演示了如何使用FeatureSelector类从数据集中删除功能。此实现中有几个重要注意事项:

•在机器学习模型的多次运行中,属性重要性将发生变化

•决定是否保留从一个onehot创建的额外功能

•为各种参数尝试几个不同的值,以确定哪些参数最适合机器学习任务

•对于相同的参数,缺失、单一唯一和共线的输出将保持不变

•特征选择是机器学习工作流的关键步骤,可能需要多次迭代来优化

XiangLin
2020年3月13日于重庆城口
好好学习,天天向上,终有所获

  • 34
    点赞
  • 125
    收藏
    觉得还不错? 一键收藏
  • 33
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 33
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值