99网
您的当前位置:首页如何用Python计算特征重要性?

如何用Python计算特征重要性?

来源:99网
如何⽤Python计算特征重要性?

特征重要性评分是⼀种为输⼊特征评分的⼿段,其依据是输⼊特征在预测⽬标变量过程中的有⽤程度。

特征重要性有许多类型和来源,尽管有许多⽐较常见,⽐如说统计相关性得分,线性模型的部分系数,基于决策树的特征重要性和经过随机排序得到重要性得分。

特征重要性在预测建模项⽬中起着重要作⽤,包括提供对数据、模型的见解,以及如何降维和选择特征,从⽽提⾼预测模型的的效率和有效性。

在本教程中,我将会阐述⽤于python机器学习的特征重要性。完成本教程后,你将会知道:

特征重要性在预测建模中的作⽤

如何计算和查看来⾃线性模型和决策树的特征重要性如何计算和查看随机排序重要性得分现在让我们开始吧.

教程概述

本教程分为五部分,分别是:1.特征重要性2.准备

2.1. 检查Scikit-Learn版本2.2. 创建测试数据集3.特征重要性系数

3.1. 基于线性回归系数的特征重要性3.2. 基于Logistic回归的特征重要性4.基于决策树的特征重要性4.1. 基于CART的特征重要性4.2. 基于随机森林的特征重要性4.3. 基于XGBoost的特征重要性5.随机排序特征重要性

5.1. 随机排序(回归)中的特征重要性5.2. 随机排序(分类)中的特征重要性

1.特征重要性

特征重要性是⼀种为预测模型的输⼊特征评分的⽅法,该⽅法揭⽰了进⾏预测时每个特征的相对重要性。可以为涉及预测数值的问题(称为回归)和涉及预测类别标签的问题(称为分类)计算特征重要性得分。这些得分⾮常有⽤,可⽤于预测建模问题中的多种情况,例如:

更好地理解数据更好地理解模型减少输⼊特征的数量

特征重要性得分可以帮助了解数据集

相对得分可以突出显⽰哪些特征可能与⽬标最相关,反之则突出哪些特征最不相关。这可以由⼀个领域专家解释,并且可以⽤作收集更多的或不同的数据的基础。

特征重要性得分可以帮助了解模型

⼤多数重要性得分是通过数据集拟合出的预测模型计算的。查看重要性得分可以洞悉该特定模型,以及知道在进⾏预测时哪些特征最重要和哪些最不重要。这是⼀种模型解释,适⽤于那些⽀持它的模型。

特征重要性可⽤于改进预测模型

可以使⽤的重要性得分来选择要删除的特征(最低得分)或要保留的特征(最⾼得分)。这是⼀种特征选择,可以简化正在建模的问题,加快建模过程(删除特征称为降维),在某些情况下,还可以改善模型的性能。

特征重要性得分可以被输⼊到包装器模型,如SelectFromModel或SelectKBest,以进⾏特征选择。有许多⽅法和模型可以计算特征重要性得分。

也许最简单的⽅法是计算每个特征和⽬标变量之间的统计学相关系数。在本教程中,我们将研究三种⽐较⾼级的特征重要性,即:

从模型系数得知的特征重要性。决策树中的特征重要性。随机排序检验中的特征重要性。现在让我们深⼊了解这三个!

2.准备

在深⼊学习之前,我们先确认我们的环境并准备⼀些测试数据集。

检查Scikit-Learn版本

⾸先,确认你已安装最新版本的scikit-learn库。这⾮常重要,因为在本教程中,我们我们研究的⼀些模型需要最新版的库。您可以使⽤以下⽰例代码来查看已安装的库的版本:1. # check scikit-learn version2. import sklearn

3. print(sklearn.__version__)

运⾏⽰例代码将会打印出库的版本。在撰写本⽂时,⼤概是version 0.22。你需要使⽤此版本或更⾼版本的scikit-learn。1. 0.22.1

⽣成测试数据集

接下来,让我们⽣成⼀些测试数据集,这些数据集可以作为基础来证明和探索特征重要性得分。每个测试问题有五个重要特征和重要的特征,看看哪种⽅法可以根据其重要性找到或区分特征可能会⽐较有意思。

分类数据集

我们将使⽤make_classification()函数创建⼀个⽤于测试的⼆进制分类数据集。

数据集将包含1000个实例,且包含10个输⼊特征,其中五个将会提供信息,其余五个是多余的。为了确保每次运⾏代码时都得到相同的实例,我们将使⽤假随机数种⼦。下⾯列出了创建数据集的⽰例。1. # test classification dataset

2. from sklearn.datasets import make_classification

3. # define dataset

4. X, y = make_classification(n_samples=1000, n_features=10, n_informative=5, n_redundant=5, random_state=1)5. # summarize the dataset6. print(X.shape, y.shape)

运⾏⽰例,创建数据集,并确保所需的样本和特征数量。1. (1000, 10) (1000,)

回归数据集

我们将使⽤make_regression()函数创建⼀个⽤于测试的回归数据集。

像分类数据集⼀样,回归数据集将包含1000个实例,且包含10个输⼊特征,其中五个将会提供信息,其余五个是多余的。1. # test regression dataset

2. from sklearn.datasets import make_regression3. # define dataset

4. X, y = make_regression(n_samples=1000, n_features=10, n_informative=5, random_state=1)5. # summarize the dataset6. print(X.shape, y.shape)

运⾏⽰例,创建数据集,并确保所需的样本和特征数量。1. (1000, 10) (1000,)

接下来,我们仔细看⼀下特征重要性系数。

3.特征重要性系数

线性的机器学习能够拟合出预测是输⼊值的加权和的模型。

案例包括线性回归,逻辑回归,和正则化的扩展案例,如岭回归和弹性⽹络。

所有这些算法都是找到⼀组要在加权求和中使⽤的系数,以便进⾏预测。这些系数可以直接⽤作粗略类型的特征重要性得分。

我们来仔细研究⼀下分类和回归中的特征重要性系数。我们将在数据集中拟合出⼀个模型以找到系数,然后计算每个输⼊特征的重要性得分,最终创建⼀个条形图来了解特征的相对重要性。

3.1线性回归特征重要性

我们可以在回归数据集中拟合出⼀个LinearRegression模型,并检索coeff_属性,该属性包含为每个输⼊变量(特征)找到的系数。这些系数可以为粗略特征重要性评分提供依据。该模型假设输⼊变量具有相同的⽐例或者在拟合模型之前已被按⽐例缩放。下⾯列出了针对特征重要性的线性回归系数的完整⽰例。1. # linear regression feature importance2. from sklearn.datasets import make_regression3. from sklearn.linear_model import LinearRegression4. from matplotlib import pyplot5. # define dataset

6. X, y = make_regression(n_samples=1000, n_features=10, n_informative=5, random_state=1)7. # define the model

8. model = LinearRegression()9. # fit the model10. model.fit(X, y)

11. # get importance

12. importance = model.coef_13. # summarize feature importance14. for i,v in enumerate(importance):15. print('Feature: %0d, Score: %.5f' % (i,v))16. # plot feature importance

17. pyplot.bar([x for x in range(len(importance))], importance)18. pyplot.show()

运⾏⽰例,拟合模型,然后输出每个特征的系数值。

得分表明,模型找到了五个重要特征,并⽤零标记了剩下的特征,实际上,将他们从模型中去除了。1. Feature: 0, Score: 0.000002. Feature: 1, Score: 12.444833. Feature: 2, Score: -0.000004. Feature: 3, Score: -0.000005. Feature: 4, Score: 93.322256. Feature: 5, Score: 86.508117. Feature: 6, Score: 26.746078. Feature: 7, Score: 3.285359. Feature: 8, Score: -0.0000010. Feature: 9, Score: 0.00000然后为特征重要性得分创建条形图。

这种⽅法也可以⽤于岭回归和弹性⽹络模型。

3.2 Logistic回归特征重要性

就像线性回归模型⼀样,我们也可以在回归数据集中拟合出⼀个LogisticRegression模型,并检索coeff_属性。这些系数可以为粗略特征重要性评分提供依据。该模型假设输⼊变量具有相同的⽐例或者在拟合模型之前已被按⽐例缩放。下⾯列出了针对特征重要性的Logistic回归系数的完整⽰例。1. # logistic regression for feature importance

2. from sklearn.datasets import make_classification3. from sklearn.linear_model import LogisticRegression4. from matplotlib import pyplot5. # define dataset

6. X, y = make_classification(n_samples=1000, n_features=10, n_informative=5, n_redundant=5, random_state=1)7. # define the model

8. model = LogisticRegression()9. # fit the model10. model.fit(X, y)11. # get importance

12. importance = model.coef_[0]13. # summarize feature importance14. for i,v in enumerate(importance):15. print('Feature: %0d, Score: %.5f' % (i,v))16. # plot feature importance

17. pyplot.bar([x for x in range(len(importance))], importance)18. pyplot.show()

运⾏⽰例,拟合模型,然后输出每个特征的系数值。

回想⼀下,这是有关0和1的分类问题。请注意系数既可以为正,也可以为负。正数表⽰预测类别1的特征,⽽负数表⽰预测类别0的特征。从这些结果,⾄少从我所知道的结果中,⽆法清晰的确定出重要和不重要特征。1. Feature: 0, Score: 0.163202. Feature: 1, Score: -0.3013. Feature: 2, Score: 0.484974. Feature: 3, Score: -0.461905. Feature: 4, Score: 0.184326. Feature: 5, Score: -0.119787. Feature: 6, Score: -0.406028. Feature: 7, Score: 0.037729. Feature: 8, Score: -0.5178510. Feature: 9, Score: 0.26540然后为特征重要性得分创建条形图。

现在我们已经看到了将系数⽤作重要性得分的⽰例,接下来让我们看向基于决策树的重要性得分的常见⽰例

4.基于决策树的特征重要性

决策树算法,⽐如说classification and regression trees(CART)根据Gini系数或熵的减少来提供重要性得分。这个⽅法也可⽤于随机森林和梯度提升算法。

OK.现在让我们看看相应的运⾏⽰例。

4.1基于CART的特征重要性

对于在scikit-learn中实现的特征重要性,我们可以将CART算法⽤于DecisionTreeRegressor和DecisionTreeClassifier类拟合后,模型提供feature_importances_属性,可以访问该属性以检索每个输⼊特征的相对重要性得分。让我们看⼀个⽤于回归和分类的⽰例。

基于CART(回归)的特征重要性

下⾯列出了拟合DecisionTreeRegressor和计算特征重要性得分的完整⽰例。1. # decision tree for feature importance on a regression problem2. from sklearn.datasets import make_regression3. from sklearn.tree import DecisionTreeRegressor4. from matplotlib import pyplot5. # define dataset

6. X, y = make_regression(n_samples=1000, n_features=10, n_informative=5, random_state=1)7. # define the model

8. model = DecisionTreeRegressor()9. # fit the model10. model.fit(X, y)11. # get importance

12. importance = model.feature_importances_13. # summarize feature importance14. for i,v in enumerate(importance):15. print('Feature: %0d, Score: %.5f' % (i,v))16. # plot feature importance

17. pyplot.bar([x for x in range(len(importance))], importance)18. pyplot.show()

运⾏⽰例,拟合模型,然后输出每个特征的系数值。结果表明,这⼗个特征中的三个可能对预测很重要。1. Feature: 0, Score: 0.002942. Feature: 1, Score: 0.005023. Feature: 2, Score: 0.003184. Feature: 3, Score: 0.001515. Feature: 4, Score: 0.5186. Feature: 5, Score: 0.438147. Feature: 6, Score: 0.027238. Feature: 7, Score: 0.002009. Feature: 8, Score: 0.0024410. Feature: 9, Score: 0.00106然后为特征重要性得分创建条形图。

基于CART(分类)的特征重要性

下⾯列出了拟合DecisionTreeClassifier和计算特征重要性得分的完整⽰例1. # decision tree for feature importance on a classification problem2. from sklearn.datasets import make_classification3. from sklearn.tree import DecisionTreeClassifier4. from matplotlib import pyplot5. # define dataset

6. X, y = make_classification(n_samples=1000, n_features=10, n_informative=5, n_redundant=5, random_state=1)7. # define the model

8. model = DecisionTreeClassifier()9. # fit the model10. model.fit(X, y)11. # get importance

12. importance = model.feature_importances_

13. # summarize feature importance14. for i,v in enumerate(importance):15. print('Feature: %0d, Score: %.5f' % (i,v))16. # plot feature importance

17. pyplot.bar([x for x in range(len(importance))], importance)18. pyplot.show()

运⾏⽰例,拟合模型,然后输出每个特征的系数值。结果表明,这⼗个特征中的四个可能对预测很重要。1. Feature: 0, Score: 0.014862. Feature: 1, Score: 0.010293. Feature: 2, Score: 0.183474. Feature: 3, Score: 0.302955. Feature: 4, Score: 0.081246. Feature: 5, Score: 0.006007. Feature: 6, Score: 0.1968. Feature: 7, Score: 0.0290. Feature: 8, Score: 0.1282010. Feature: 9, Score: 0.04745然后为特征重要性得分创建条形图。

4.2随机森林中的特征重要性

对于在scikit-learn中实现的特征重要性,我们可以将Random Forest算法⽤于DecisionTreeRegressor和DecisionTreeClassifier类。拟合后,模型提供feature_importances_属性,可以访问该属性以检索每个输⼊特征的相对重要性得分。这种⽅法也可以与装袋和极端随机树(extraTree)算法⼀起使⽤。让我们看⼀个⽤于回归和分类的⽰例。

随机森林(回归)中的特征重要性

下⾯列出了拟合RandomForestRegressor和计算特征重要性得分的完整⽰例1. # random forest for feature importance on a regression problem

2. from sklearn.datasets import make_regression

3. from sklearn.ensemble import RandomForestRegressor4. from matplotlib import pyplot5. # define dataset

6. X, y = make_regression(n_samples=1000, n_features=10, n_informative=5, random_state=1)7. # define the model

8. model = RandomForestRegressor()9. # fit the model10. model.fit(X, y)11. # get importance

12. importance = model.feature_importances_13. # summarize feature importance14. for i,v in enumerate(importance):15. print('Feature: %0d, Score: %.5f' % (i,v))16. # plot feature importance

17. pyplot.bar([x for x in range(len(importance))], importance)18. pyplot.show()

运⾏⽰例,拟合模型,然后输出每个特征的系数值。结果表明,这⼗个特征中的两个或三个可能对预测很重要。1. Feature: 0, Score: 0.002802. Feature: 1, Score: 0.005453. Feature: 2, Score: 0.002944. Feature: 3, Score: 0.0025. Feature: 4, Score: 0.529926. Feature: 5, Score: 0.420467. Feature: 6, Score: 0.026638. Feature: 7, Score: 0.003049. Feature: 8, Score: 0.0030410. Feature: 9, Score: 0.00283然后为特征重要性得分创建条形图。

随机森林(分类)中的特征重要性

下⾯列出了拟合RandomForestClassifier和计算特征重要性得分的完整⽰例1. # random forest for feature importance on a classification problem2. from sklearn.datasets import make_classification3. from sklearn.ensemble import RandomForestClassifier4. from matplotlib import pyplot5. # define dataset

6. X, y = make_classification(n_samples=1000, n_features=10, n_informative=5, n_redundant=5, random_state=1)7. # define the model

8. model = RandomForestClassifier()9. # fit the model10. model.fit(X, y)11. # get importance

12. importance = model.feature_importances_13. # summarize feature importance14. for i,v in enumerate(importance):15. print('Feature: %0d, Score: %.5f' % (i,v))16. # plot feature importance

17. pyplot.bar([x for x in range(len(importance))], importance)18. pyplot.show()

运⾏⽰例,拟合模型,然后输出每个特征的系数值。结果表明,这⼗个特征中的两个或三个可能对预测很重要。1. Feature: 0, Score: 0.065232. Feature: 1, Score: 0.107373. Feature: 2, Score: 0.157794. Feature: 3, Score: 0.204225. Feature: 4, Score: 0.087096. Feature: 5, Score: 0.099487. Feature: 6, Score: 0.100098. Feature: 7, Score: 0.04551

9. Feature: 8, Score: 0.0883010. Feature: 9, Score: 0.04493然后为特征重要性得分创建条形图。

4.3基于XGBoost的特征重要性

XGBoost是⼀个库,它提供了随机梯度提升算法的⾼效实现。可以通过XGBRegressor和XGBClassifier类将此算法与scikit-learn⼀起使⽤。

拟合后,模型提供feature_importances_属性,可以访问该属性以检索每个输⼊特征的相对重要性得分。

scikit-learn还通过GradientBoostingClassifier和GradientBoostingRegressor提供了该算法,并且可以使⽤相同的特征选择⽅法⾸先,安装XGBoost库,例如:1. sudo pip install xgboost

然后,通过检查版本号来确认该库已正确安装并且可以正常⼯作。1. # check xgboost version2. import xgboost

3. print(xgboost.__version__)

运⾏该⽰例,你应该看到以下版本号或者更⾼版本。1. 0.90

有关XGBoost库的更多信息,请看:

XGBoost with Python

让我们看⼀个⽤于回归和分类问题的⽰例。

基于XGBoost(回归)的特征重要性

下⾯列出了拟合XGBRegressor并且计算特征重要性得分的完整⽰例1. # xgboost for feature importance on a regression problem2. from sklearn.datasets import make_regression3. from xgboost import XGBRegressor4. from matplotlib import pyplot

5. # define dataset

6. X, y = make_regression(n_samples=1000, n_features=10, n_informative=5, random_state=1)7. # define the model8. model = XGBRegressor()9. # fit the model10. model.fit(X, y)11. # get importance

12. importance = model.feature_importances_13. # summarize feature importance14. for i,v in enumerate(importance):15. print('Feature: %0d, Score: %.5f' % (i,v))16. # plot feature importance

17. pyplot.bar([x for x in range(len(importance))], importance)18. pyplot.show()

运⾏⽰例,拟合模型,然后输出每个特征的系数值。结果表明,这⼗个特征中的两个或三个可能对预测很重要。1. Feature: 0, Score: 0.000602. Feature: 1, Score: 0.019173. Feature: 2, Score: 0.000914. Feature: 3, Score: 0.001185. Feature: 4, Score: 0.493806. Feature: 5, Score: 0.423427. Feature: 6, Score: 0.050578. Feature: 7, Score: 0.004199. Feature: 8, Score: 0.0012410. Feature: 9, Score: 0.00491然后为特征重要性得分创建条形图。

基于XGBoost(分类)的特征重要性

下⾯列出了拟合XGBClassifier并且计算特征重要性得分的完整⽰例

1. # xgboost for feature importance on a classification problem2. from sklearn.datasets import make_classification3. from xgboost import XGBClassifier4. from matplotlib import pyplot5. # define dataset

6. X, y = make_classification(n_samples=1000, n_features=10, n_informative=5, n_redundant=5, random_state=1)7. # define the model8. model = XGBClassifier()9. # fit the model10. model.fit(X, y)11. # get importance

12. importance = model.feature_importances_13. # summarize feature importance14. for i,v in enumerate(importance):15. print('Feature: %0d, Score: %.5f' % (i,v))16. # plot feature importance

17. pyplot.bar([x for x in range(len(importance))], importance)18. pyplot.show()

运⾏⽰例,拟合模型,然后输出每个特征的系数值。结果表明,这⼗个特征中有七个可能对预测很重要。1. Feature: 0, Score: 0.0242. Feature: 1, Score: 0.081533. Feature: 2, Score: 0.1251. Feature: 3, Score: 0.284005. Feature: 4, Score: 0.126946. Feature: 5, Score: 0.107527. Feature: 6, Score: 0.086248. Feature: 7, Score: 0.048209. Feature: 8, Score: 0.0935710. Feature: 9, Score: 0.02220然后为特征重要性得分创建条形图。

5.基于随机排序的特征重要性

随机排序特征重要性(Permutation feature importance)可以计算相对重要性,与所使⽤的模型⽆关。

⾸先,在数据集中拟合出⼀个模型,⽐如说⼀个不⽀持本地特征重要性评分的模型。然后,尽管对数据集中的特征值进⾏了⼲扰,但仍可以使⽤该模型进⾏预测。对数据集中的每个特征进⾏此操作。然后,再将整个流程重新操作3、5、10或更多次。我们得到每个输⼊特征的平均重要性得分(以及在重复的情况下得分的分布)。

此⽅法可以⽤于回归或分类,要求选择性能指标作为重要性得分的基础,例如回归中的均⽅误差和分类中的准确性。可以通过permutation_importance()函数(以模型和数据集为参数)和评分函数进⾏随机排序特性选择。让我们看下这个特征选择⽅法,其算法并不⽀持特征选择,尤其是k近邻算法( k-nearest neighbors)。

5.1随机排序(回归)特征重要性

下⾯列出了拟合KNeighborsRegressor并且计算特征重要性得分的完整⽰例。1. # permutation feature importance with knn for regression2. from sklearn.datasets import make_regression3. from sklearn.neighbors import KNeighborsRegressor4. from sklearn.inspection import permutation_importance5. from matplotlib import pyplot6. # define dataset

7. X, y = make_regression(n_samples=1000, n_features=10, n_informative=5, random_state=1)8. # define the model

9. model = KNeighborsRegressor()10. # fit the model11. model.fit(X, y)

12. # perform permutation importance

13. results = permutation_importance(model, X, y, scoring='neg_mean_squared_error')14. # get importance

15. importance = results.importances_mean16. # summarize feature importance17. for i,v in enumerate(importance):18. print('Feature: %0d, Score: %.5f' % (i,v))19. # plot feature importance

20. pyplot.bar([x for x in range(len(importance))], importance)21. pyplot.show()

运⾏⽰例,拟合模型,然后输出每个特征的系数值。结果表明,这⼗个特征中的两个或三个可能对预测很重要。1. Feature: 0, Score: 175.520072. Feature: 1, Score: 345.801703. Feature: 2, Score: 126.605784. Feature: 3, Score: 95.900815. Feature: 4, Score: 9666.1466. Feature: 5, Score: 8036.790337. Feature: 6, Score: 929.585178. Feature: 7, Score: 139.674169. Feature: 8, Score: 132.0624610. Feature: 9, Score: 84.94768然后为特征重要性得分创建条形图。

5.2随机排序(分类)特征重要性

下⾯列出了拟合KNeighborsClassifier并且计算特征重要性得分的完整⽰例。1. # permutation feature importance with knn for classification2. from sklearn.datasets import make_classification3. from sklearn.neighbors import KNeighborsClassifier4. from sklearn.inspection import permutation_importance5. from matplotlib import pyplot6. # define dataset

7. X, y = make_classification(n_samples=1000, n_features=10, n_informative=5, n_redundant=5, random_state=1)8. # define the model

9. model = KNeighborsClassifier()10. # fit the model11. model.fit(X, y)

12. # perform permutation importance

13. results = permutation_importance(model, X, y, scoring='accuracy')14. # get importance

15. importance = results.importances_mean16. # summarize feature importance17. for i,v in enumerate(importance):18. print('Feature: %0d, Score: %.5f' % (i,v))19. # plot feature importance

20. pyplot.bar([x for x in range(len(importance))], importance)21. pyplot.show()

运⾏⽰例,拟合模型,然后输出每个特征的系数值。结果表明,这⼗个特征中的两个或三个可能对预测很重要。1. Feature: 0, Score: 0.047602. Feature: 1, Score: 0.066803. Feature: 2, Score: 0.052404. Feature: 3, Score: 0.093005. Feature: 4, Score: 0.051406. Feature: 5, Score: 0.055207. Feature: 6, Score: 0.079208. Feature: 7, Score: 0.055609. Feature: 8, Score: 0.0562010. Feature: 9, Score: 0.03080然后为特征重要性得分创建条形图。

总结

在本教程中,您知道了在Python机器学习中的特征重要性得分。具体来说,您了解到:

特征重要性在预测建模问题中的作⽤

如何从线性模型和决策树中计算和查看特征重要性如何计算和查看随机排序特征重要性得分

因篇幅问题不能全部显示,请点此查看更多更全内容