matplotlib:使用要素名称绘制要素重要性

add*_*ons 8 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])
Run Code Online (Sandbox Code Playgroud)

然后使用以下绘图功能:

>> pyplot.bar(range(len(model.feature_importances_)), model.feature_importances_)
>> pyplot.show()
Run Code Online (Sandbox Code Playgroud)

我得到了一个条形图,但我希望得到带有标签的条形图,同时重要性以有条理的方式水平显示.我也在探索seaborn,但无法找到方法.

for*_*rdy 25

对于没有时间浪费的数据科学家的快速回答:

将要素重要性加载到由列名索引的pandas系列中,然后使用其绘图方法.对于model使用X以下方法训练的分类器

feat_importances = pd.Series(model.feature_importances_, index=X.columns)
feat_importances.nlargest(20).plot(kind='barh')
Run Code Online (Sandbox Code Playgroud)

一个完整的例子稍微详细一点的答案:

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

nlargest(n)是一个pandas Series方法,它将返回具有最大值的系列的子集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!
Run Code Online (Sandbox Code Playgroud)

哪个会给你这个:

sklearn随机森林特征重要性

  • @ArtTatum 调用 `invert_yaxis()` - 示例用法 `pd.Series(model.feature_importances_, index=X.columns).nlargest(4).plot(kind='barh').invert_yaxis()` (3认同)
  • 如果我想在 y 轴上翻转该图怎么办?例如,先显示年龄,然后显示票价等 (2认同)

Y. *_*Luo 8

不完全确定你在寻找什么.从这里得到一个例子.如评论中所述:如果要自定义要素标签indices,可以在行中更改为标签列表plt.yticks(range(X.shape[1]), indices).

import numpy as np
import matplotlib.pyplot as plt

from sklearn.datasets import make_classification
from sklearn.ensemble import ExtraTreesClassifier

# Build a classification task using 3 informative features
X, y = make_classification(n_samples=1000,
                           n_features=10,
                           n_informative=3,
                           n_redundant=0,
                           n_repeated=0,
                           n_classes=2,
                           random_state=0,
                           shuffle=False)

# Build a forest and compute the feature importances
forest = ExtraTreesClassifier(n_estimators=250,
                              random_state=0)

forest.fit(X, y)
importances = forest.feature_importances_
std = np.std([tree.feature_importances_ for tree in forest.estimators_],
             axis=0)
indices = np.argsort(importances)

# Plot the feature importances of the forest
plt.figure()
plt.title("Feature importances")
plt.barh(range(X.shape[1]), importances[indices],
       color="r", xerr=std[indices], align="center")
# If you want to define your own labels,
# change indices to a list of labels on the following line.
plt.yticks(range(X.shape[1]), indices)
plt.ylim([-1, X.shape[1]])
plt.show()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述