python - 使用特征名称绘制特征重要性

标签 python matplotlib random-forest seaborn

在 R 中有预建函数来绘制随机森林模型的特征重要性。但是在 python 中似乎缺少这种方法。我在 matplotlib 中搜索一种方法。

model.feature_importances 给我以下内容:

array([  2.32421835e-03,   7.21472336e-04,   2.70491223e-03,
         3.34521084e-03,   4.19443238e-03,   1.50108737e-03,
         3.29160540e-03,   4.82320256e-01,   3.14117333e-03])

然后使用以下绘图函数:

>> pyplot.bar(range(len(model.feature_importances_)), model.feature_importances_)
>> pyplot.show()

我得到了一个条形图,但我想得到带有标签的条形图,同时重要性以排序的方式水平显示。我也在探索 seaborn,但找不到方法。

最佳答案

为没有时间可浪费的数据科学家提供的快速答案:

将特征重要性加载到由您的列名索引的 pandas 系列中,然后使用其 plot 方法。对于使用 X 训练的分类器 model:

feat_importances = pd.Series(model.feature_importances_, index=X.columns)
feat_importances.nlargest(20).plot(kind='barh')

带有完整示例的更详细的答案:

假设您使用 pandas 数据框中包含的数据训练您的模型,如果您将特征重要性加载到 panda 的系列中,这将相当轻松,然后您可以利用其索引轻松显示变量名称。 plot 参数 kind='barh' 为我们提供了一个水平条形图,但您可以轻松地将此参数替换为 kind='bar' 以获得具有以下功能的传统条形图如果您愿意,可以沿 x 轴命名。

nlargest(n) 是一种 pandas 系列方法,它将返回系列中具有最大 n 值的子集。如果您的模型中有很多特征并且您只想绘制最重要的特征,这将很有用。

使用经典 Kaggle Titanic 数据集的快速完整示例...

import pandas as pd
from sklearn.ensemble import RandomForestClassifier
%matplotlib inline            # don't forget this if you're using jupyter!

X = pd.read_csv("titanic_train.csv")
X = X[['Pclass', 'Age', 'Fare', 'Parch', 'SibSp', 'Survived']].dropna()
y = X.pop('Survived')

model = RandomForestClassifier()
model.fit(X, y)

(pd.Series(model.feature_importances_, index=X.columns)
   .nlargest(4)
   .plot(kind='barh'))        # some method chaining, because it's sexy!

这会给你这个:

sklearn random forest feature importances

关于python - 使用特征名称绘制特征重要性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44511636/

相关文章:

python - 在 python 中使用多重处理折叠数组突变

linux - Linux 与 mswindows 中的 Matplotlib 绘图

python - 创建双箱线图 - 即每个 x 值有两个框

python - 如何从 Sklearn 管道中提取特征重要性

python - 有没有办法将 markdown 转换为解释性 RTF?

python - 将字典列表转换为 CSV

python - Django 休息框架 : Test serializers

python - 如何将轴标签绘制为时间(以小时、分钟等为单位)

python - 随机森林回归 - 如何分析其性能? - python ,sklearn

随机森林包预测,newdata 参数?