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

Plot Feature Importance with feature names

在 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,但找不到方法。

不确定您要找什么。从 here 派生了一个例子。如评论中所述:如果要自定义功能标签,可以将 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()

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

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

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

更详细的答案,有完整的例子:

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

nlargest(n) 是一种 pandas 系列方法,它将 return 具有最大 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!

哪个会给你这个:

可以只传递 df.columns 作为 plt.xticks() 的参数:

plt.bar( range(len(model.feature_importances_)), model.feature_importances_)
plt.xticks(range(len(model.feature_importances_)), train_features.columns)
plt.show()