(给数据分析与开发加星标,提升数据技能)

英文:Sugandha Lahoti,转自:数据派(ID:datapi),翻译:李洁

注:本文节选自Ankit Dixit所著的《集成机器学习》(Ensemble Machine Learning)一书。这本书组合强大的机器学习算法来建立优化模型,可以作为初学者的指南。

在本文中,我们将研究从数据集中选择特征的不同方法;同时通过使用Python中Scikit-learn (sklearn)库实现讨论了特征选择算法的类型:

  • 单变量选择

  • 递归特征消除(RFE)

  • 主成分分析(PCA)

  • 选择重要特征(特征重要度)

我们简要介绍了前三种算法及其实现。然后我们将详细讨论在数据科学社区中广泛使用的选择重要特征(特性重要度)部分的内容。

单变量选择

统计测试可用于选择那些与输出变量关系最强的特征。

scikit-learn库提供了SelectKBest类,它可以与一组不同的统计测试一起使用,以选择特定数量的特征。

下面的例子使用chi²非负性特征的统计测试,从皮马印第安人糖尿病发病数据集中选择了四个最好的特征:

#Feature Extraction with Univariate Statistical Tests (Chi-squared for classification)

#Import the required packages

#Import pandas to read csv import pandas

#Import numpy for array related operations import numpy

#Import sklearn's feature selection algorithm

from sklearn.feature_selection import SelectKBest

#Import chi2 for performing chi square test from sklearn.feature_selection import chi2

#URL for loading the dataset

url ="https://archive.ics.uci.edu/ml/machine-learning-databases/pima-indians diabetes/pima-indians-diabetes.data"

#Define the attribute names

names = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class']

#Create pandas data frame by loading the data from URL

dataframe = pandas.read_csv(url, names=names)

#Create array from data values

array = dataframe.values

#Split the data into input and target

X = array[:,0:8]

Y = array[:,8]

#We will select the features using chi square

test = SelectKBest(score_func=chi2, k=4)

#Fit the function for ranking the features by score

fit = test.fit(X, Y)

#Summarize scores numpy.set_printoptions(precision=3) print(fit.scores_)

#Apply the transformation on to dataset

features = fit.transform(X)

#Summarize selected features print(features[0:5,:])

你可以看到每个参数的得分,以及所选择的四个参数(得分最高的):plas、test、mass和age。

每个特征的分数为:

[111.52   1411.887 17.605 53.108  2175.565   127.669 5.393

181.304]

被选出的特征是:

[[148. 0. 33.6 50. ]

[85. 0. 26.6 31. ]

[183. 0. 23.3 32. ]

[89. 94. 28.1 21. ]

[137. 168. 43.1 33. ]]

递归特征消除(RFE)

RFE的工作方式是递归地删除参数并在保留的参数上构建模型。它使用模型精度来判断哪些属性(以及属性的组合)对预测目标参数贡献最大。你可以在scikit-learn的文档中了解更多关于RFE类的信息。

下面的示例使用RFE和logistic回归算法来选出前三个特征。算法的选择并不重要,只需要熟练并且一致:

#Import the required packages

#Import pandas to read csv import pandas

#Import numpy for array related operations import numpy

#Import sklearn's feature selection algorithm from sklearn.feature_selection import RFE

#Import LogisticRegression for performing chi square test from sklearn.linear_model import LogisticRegression

#URL for loading the dataset

url =

"https://archive.ics.uci.edu/ml/machine-learning-databases/pima-indians-dia betes/pima-indians-diabetes.data"

#Define the attribute names

names = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class']

#Create pandas data frame by loading the data from URL

dataframe = pandas.read_csv(url, names=names)

#Create array from data values

array = dataframe.values

#Split the data into input and target

X = array[:,0:8]

Y = array[:,8]

#Feature extraction

model = LogisticRegression() rfe = RFE(model, 3)

fit = rfe.fit(X, Y)

print("Num Features: %d"% fit.n_features_) print("Selected Features: %s"% fit.support_) print("Feature Ranking: %s"% fit.ranking_)

执行完上述代码后,我们可以得到:

Num Features: 3

Selected Features: [ True False False False False   True  True False]

Feature Ranking: [1 2 3 5 6 1 1 4]

你可以看到RFE选择了前三个特性,即preg、mass和pedi。这些在support_数组中被标记为True,在ranking_数组中被标记为首选(标记为1)。

主成分分析

PCA使用线性代数将数据集转换为压缩格式。通常,它被认为是一种数据约简技术。PCA的一个属性是,你可以选择转换结果中的维数或主成分的数量。

在接下来的例子中,我们使用PCA并选择了三个主成分:

#Import the required packages

#Import pandas to read csv import pandas

#Import numpy for array related operations import numpy

#Import sklearn's PCA algorithm

from sklearn.decomposition import PCA

#URL for loading the dataset

url =

"https://archive.ics.uci.edu/ml/machine-learning-databases/pima-indians diabetes/pima-indians-diabetes.data"

#Define the attribute names

names = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class']

dataframe = pandas.read_csv(url, names=names)

#Create array from data values

array = dataframe.values

#Split the data into input and target

X = array[:,0:8]

Y = array[:,8]

#Feature extraction

pca = PCA(n_components=3) fit = pca.fit(X)

#Summarize components

print("Explained Variance: %s") % fit.explained_variance_ratio_

print(fit.components_)

你可以看到,转换后的数据集(三个主成分)与源数据几乎没有相似之处:

Explained Variance: [ 0.88854663   0.06159078  0.02579012]

[[ -2.02176587e-03    9.78115765e-02 1.60930503e-02    6.07566861e-02

9.93110844e-01          1.40108085e-02 5.37167919e-04   -3.56474430e-03]

[ -2.26488861e-02   -9.72210040e-01              -1.41909330e-01  5.78614699e-02 9.46266913e-02   -4.69729766e-02               -8.16804621e-04  -1.40168181e-01

[ -2.24649003e-02 1.43428710e-01                 -9.22467192e-01  -3.07013055e-01 2.09773019e-02   -1.32444542e-01                -6.39983017e-04  -1.25454310e-01]]

选择重要特征(特性重要度)

特征重要度是一种利用训练好的有监督分类器来选择特征的技术。当我们训练分类器(如决策树)时,我们计算每个参数以创建分割;我们可以使用这个度量作为特征选择器。让我们来详细了解一下。

随机森林由于其相对较好的准确性、鲁棒性和易用性而成为最受欢迎的机器学习方法之一。它们还提供了两种简单易行的特征选择方法——均值降低杂质和均值降低准确度。

随机森林由许多决策树组成。决策树中的每个节点都是一个基于单个特征的条件,其设计目的是将数据集分割成两个,以便相似的响应值最终出现在相同的集合中。选择(局部)最优条件的度量叫做杂质。对于分类问题,它通常是基尼杂质或信息增益/熵,而对于回归树,它是方差。因此,当训练一棵树时,可以通过每个特征减少的树中加权杂质的多少来计算。对于森林,可以对每个特征的杂质减少量进行平均,并根据该方法对特征进行排序。

让我们看一下如何使用随机森林分类器来进行特征选择,并评估特征选择前后分类器的准确性。我们将使用Otto数据集。该数据集可从kaggle免费获得(你需要注册kaggle才能下载该数据集)。你可以从https://www.kaggle.com/c/otto-group-product- classifics-challenge/data下载训练集train.csv.zip,然后将解压缩的train.csv文件放在你的工作目录中。

这个数据集描述了超过61,000个产品的93个模糊细节,这些产品被分成10个产品类别(例如,时尚类、电子产品类等)。输入参数是某种类型的不同事件的计数。

训练目标是对新产品作为10个类别中每一个类别的概率数组做出预测,并使用多级对数损失(也称为交叉熵)对模型进行评估。

我们将从导入所有库开始:

#Import the supporting libraries

#Import pandas to load the dataset from csv file

from pandas import read_csv

#Import numpy for array based operations and calculations

import numpy as np

#Import Random Forest classifier class from sklearn

from sklearn.ensemble import RandomForestClassifier

#Import feature selector class select model of sklearn

        from sklearn.feature_selection

        import SelectFromModel

         np.random.seed(1)

定义一个方法用于将我们的数据集分为训练数据和测试数据;我们将在训练数据部分对数据集进行训练,测试数据部分将用于训练模型的评估:

#Function to create Train and Test set from the original dataset def getTrainTestData(dataset,split):

np.random.seed(0) training = [] testing = []

np.random.shuffle(dataset) shape = np.shape(dataset)

trainlength = np.uint16(np.floor(split*shape[0]))

for i in range(trainlength): training.append(dataset[i])

for i in range(trainlength,shape[0]): testing.append(dataset[i])

training = np.array(training) testing = np.array(testing)

return training,testing

还需要添加一个函数来评估模型的准确性;以预测输出和实际输出为输入,计算准确率百分比:

#Function to evaluate model performance

def getAccuracy(pre,ytest): count = 0

for i in range(len(ytest)):

if ytest[i]==pre[i]: count+=1

acc = float(count)/len(ytest)

return acc

现在要导入数据集。我们将导入train.csv文件;该文件包含61,000多个训练实例。我们的示例将使用50000个实例,其中使用35,000个实例来训练分类器,并使用15,000个实例来测试分类器的性能:

#Load dataset as pandas data frame

data = read_csv('train.csv')

#Extract attribute names from the data frame

feat = data.keys()

feat_labels = feat.get_values()

#Extract data values from the data frame

dataset = data.values

#Shuffle the dataset

np.random.shuffle(dataset)

#We will select 50000 instances to train the classifier

inst = 50000

#Extract 50000 instances from the dataset

dataset = dataset[0:inst,:]

#Create Training and Testing data for performance evaluation

train,test = getTrainTestData(dataset, 0.7)

#Split data into input and output variable with selected features

Xtrain = train[:,0:94] ytrain = train[:,94] shape = np.shape(Xtrain)

print("Shape of the dataset ",shape)

#Print the size of Data in MBs

print("Size of Data set before feature selection: %.2f MB"%(Xtrain.nbytes/1e6))

注意下这里的数据大小;由于我们的数据集包含约35000个训练实例,带有94个参数;我们的数据集非常大。让我们来看一下:

Shape of the dataset (35000, 94)

Size of Data set before feature selection: 26.32 MB

如你所见,我们的数据集中有35000行和94列,数据大小超过26MB。

在下一个代码块中,我们将配置我们的随机森林分类器;我们会使用250棵树,最大深度为30,随机特征的数量为7。其他超参数将是sklearn的默认值:

#Lets select the test data for model evaluation purpose

Xtest = test[:,0:94] ytest = test[:,94]

#Create a random forest classifier with the following Parameters

trees            = 250

max_feat     = 7

max_depth = 30

min_sample = 2

clf = RandomForestClassifier(n_estimators=trees,

max_features=max_feat,

max_depth=max_depth,

min_samples_split= min_sample, random_state=0,

n_jobs=-1)

#Train the classifier and calculate the training time

import time

start = time.time() clf.fit(Xtrain, ytrain) end = time.time()

#Lets Note down the model training time

print("Execution time for building the Tree is: %f"%(float(end)- float(start)))

pre = clf.predict(Xtest)

Let's see how much time is required to train the model on the training dataset:Execution time for building the Tree is: 2.913641#Evaluate the model performance for the test dataacc = getAccuracy(pre, ytest)print("Accuracy of model before feature selection is %.2f"%(100*acc))

模型的精确度是:

Accuracy of model before feature selection is 98.82

正如所看到的,我们获得了非常好的精确度,因为我们将几乎99%的测试数据分类为正确的类别。这意味着我们在15,000个实例中对大概14,823个实例进行了正确的分类。

所以,现在问题是:我们应该进一步改进吗?好吧,为什么不呢?如果可能的话,我们一定需要进行更多的改进;在这里,我们将使用特征重要度来选择特征。如你所知,在树的建造过程中,我们使用杂质度量来选择节点。选择杂质最少的参数值作为树中的节点。我们可以使用类似的标准来选择特征。我们可以给杂质更少的特征更多的重要度,这可以使用sklearn库的feature_importances_函数来实现。让我们来看一下每个特征的重要度:

print(feature)

('id', 0.33346650420175183)

('feat_1', 0.0036186958628801214)

('feat_2', 0.0037243050888530957)

('feat_3', 0.011579217472062748)

('feat_4', 0.010297382675187445)

('feat_5', 0.0010359139416194116)

('feat_6', 0.00038171336038056165)

('feat_7', 0.0024867672489765021)

('feat_8', 0.0096689721610546085)

('feat_9', 0.007906150362995093)

('feat_10', 0.0022342480802130366)

正如你看到的,每个特征都有不同的重要度,这取决于它对最终预测的贡献值。

我们将使用这些重要度评分来对我们的特征进行排序;在接下来的部分中,我们将选取特征重要度大于0.01的特征进行模型训练:

#Select features which have higher contribution in the final prediction

sfm = SelectFromModel(clf, threshold=0.01) sfm.fit(Xtrain,ytrain)

这里,我们将根据所选的特征参数转换输入的数据集。在下一个代码块中,我们会转换数据集。然后,我们将检查新数据集的大小和形状:

#Transform input dataset

Xtrain_1 = sfm.transform(Xtrain) Xtest_1      = sfm.transform(Xtest)

#Let's see the size and shape of new dataset print("Size of Data set before feature selection: %.2f MB"%(Xtrain_1.nbytes/1e6))

shape = np.shape(Xtrain_1)

print("Shape of the dataset ",shape)

Size of Data set before feature selection: 5.60 MB Shape of the dataset (35000, 20)

看到数据集的形状了吗?经过特征选择后,我们只剩下20个特征,这使得数据库的大小从26MB减少到了5.60 MB,比原来的数据集减少了80%左右。

在下一个代码块中,我们将使用与前面相同的超参数训练一个新的随机森林分类器,并在测试集上进行了测试。我们来看看修改训练集后得到的精确度是多少:

#Model training time

start = time.time() clf.fit(Xtrain_1, ytrain) end = time.time()

print("Execution time for building the Tree is: %f"%(float(end)- float(start)))

#Let's evaluate the model on test data

pre = clf.predict(Xtest_1) count = 0

acc2 = getAccuracy(pre, ytest)

print("Accuracy after feature selection %.2f"%(100*acc2))

Execution time for building the Tree is: 1.711518 Accuracy after feature selection 99.97

看到了吗!使用修改后的数据集,我们获得了99.97%的准确率,这意味着我们把14,996个实例分到了正确的类别,而之前我们只正确地分类了14,823个实例。

这是我们在特征选择过程中取得的巨大进步;我们可以将所有的结果总结如下表:

评估标准

特征选择前

特征选择后

特征数量

94

20

数据集大小

26.32MB

5.60MB

训练时间

2.91 s

1.71 s

精确度

98.82%

99.97%

上表显示了特征选择的实际优势。可以看到我们显著地减少了特征的数量,这减少了模型的复杂性和数据集的维度。在减小维度后,我们需要更少的训练时间,最终我们克服了过拟合的问题,获得了比以前更高的精确度。

本文我们共探讨了机器学习中特征选择的4种方法。

如果你发现这篇文章很有用,请阅读《集成机器学习》一书,了解关于叠加泛化和其他技术的更多信息。

推荐阅读

(点击标题可跳转阅读)

你真的会正确地调试 TensorFlow 代码吗?

使用 Bert 预训练模型文本分类(内附源码)

从零开始用 Python 构建循环神经网络(附代码)

看完本文有收获?请转发分享给更多人

关注「数据分析与开发」加星标,提升数据技能

喜欢就点一下「好看」呗~

dataframe 选择输出_使用 Python 实现机器学习特征选择的 4 种方法相关推荐

  1. 独家 | 使用Python实现机器学习特征选择的4种方法(附代码)

    作者:Sugandha Lahoti 翻译:李洁 校对:杨光 本文约3500字,建议阅读13分钟. 本文中,我们将研究从数据集中选择特征的不同方法;同时通过使用Python中Scikit-learn  ...

  2. python单向认证_使用Python进行单向方差分析的四种方法

    python单向认证 The current post will focus on how to carry out between-subjects ANOVA using Python. As m ...

  3. python调用matlab函数_从 Python 调用 MATLAB 函数的三种方法

    0. 实验环境Ubuntu 16.04 Matlab R2015b 1. 借助于 mlab 库 安装方法非常简单,只需一行命令 sudo pip install mlab 即可. import num ...

  4. python读csv最快方法_使用Python读写csv文件的三种方法

    Python读写csv文件 觉得有用的话,欢迎一起讨论相互学习~Follow Me 前言 逗号分隔值(Comma-Separated Values,CSV,有时也称为字符分隔值,因为分隔字符也可以不是 ...

  5. python优先级排序_用Python实现优先级队列的3种方法

    微信公众号:冰咖啡与狗 1. 什么是优先级队列? 优先级队列是一种容器型数据结构,它能管理一队记录,并按照排序字段(例如一个数字类型的权重值)为其排序.由于是排序的,所以在优先级队列中你可以快速获取到 ...

  6. python读写csv文件方法总结_使用python读写CSV文件的三种方法

    Python读写csv文件 觉得有用的话,欢迎一起讨论相互学习~Follow Me 前言 逗号分隔值(Comma-Separated Values,CSV,有时也称为字符分隔值,因为分隔字符也可以不是 ...

  7. python mount回调函数_让Python脚本暂停执行的几种方法(小结)

    1.time.sleep(secs) 参考文档原文: Suspend execution for the given number of seconds. The argument may be a ...

  8. python图层合并_图层最新:Python叠加矩形框图层2种方法及效果_爱安网 LoveAn.com

    关于"图层"的最新内容 聚合阅读 这篇文章主要介绍了Python叠加矩形框图层2种方法及效果,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友 ...

  9. python怎么模拟浏览器交互_干货分享:python爬虫模拟浏览器的两种方法实例分析(赶紧收藏)...

    今天为大家带来的内容是:干货分享:python爬虫模拟浏览器的两种方法实例分析(赶紧收藏) 文章主要介绍了python爬虫模拟浏览器的两种方法,结合实例形式分析了Python爬虫模拟浏览器的两种常见操 ...

最新文章

  1. linux下调试thread 类_在 RISC-V 芯片 GD32V 上运行 RT-Thread
  2. ai算子是什么_肇观电子刷新端侧AI芯片性能记录并发布“5分钟部署”AI开发平台 - 企业资讯...
  3. 前端学习(3035):vue+element今日头条管理-关于问题的一个解析
  4. 列表元素的几种统计方法总结(嵌套列表)
  5. 一个文科小白的数据分析师之路
  6. 用Python爬取漫画并转换格式为pdf和mobi
  7. 基于Java的Minecraft游戏后端自定义插件 08VexView界面绘制与按钮和扩展VexView事件使用
  8. wifi路由器如何连接无线网络连接服务器,wifi路由器的使用方法 | 192路由网
  9. Kali Linux安装2019.2.28
  10. 嵌入式技术及应用基础实验
  11. iOS应用上传个人头像
  12. Macbook Pro(M1芯片)腾讯会议无法使用共享屏幕功能
  13. 1.13 新概念 否定疑问句 半否定 全否定
  14. 八、DOM(一) -- DOM对象
  15. 水果分割论文、代码和数据集汇总
  16. Norton推出基于云查杀免费小工具Norton Power Eraser
  17. 2022-2027年中国BOSS系统行业市场全景评估及发展战略规划报告
  18. 【Jupyter】【Matplotlib】无法显示中文问题
  19. 获取SongTaste歌曲下地地址
  20. 现代科技概论_现代科技概论课程:力与运动3

热门文章

  1. 5个构建Spring Boot API的实用技巧
  2. 一种通过变量插值读取属性的方法
  3. JSF:在正确的阶段进行验证(了解生命周期)
  4. 当null检查非常失败时
  5. 简而言之,JUnit:Hello World
  6. Gradle – Maven的观点
  7. Java顺序IO性能
  8. JBoss BRMS 5.3 –添加了业务活动监视(BAM)报告
  9. Spring @Configuration和FactoryBean
  10. 并发模式:生产者和消费者