Python matplotlib:用特征名称绘制特征重要性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44511636/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
matplotlib: Plot Feature Importance with feature names
提问by add-semi-colons
In R there are pre-built functions to plot feature importance of Random Forest model. But in python such method seems to be missing. I search for a method in matplotlib
.
在 R 中有预先构建的函数来绘制随机森林模型的特征重要性。但是在python中似乎缺少这种方法。我在matplotlib
.
model.feature_importances
gives me following:
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])
Then using following plotting function:
然后使用以下绘图功能:
>> pyplot.bar(range(len(model.feature_importances_)), model.feature_importances_)
>> pyplot.show()
I get a barplot but I would like to get barplot with labels while importance showing horizontally in a sorted fashion. I am also exploring seaborn
and was not able to find a method.
我得到一个条形图,但我想获得带有标签的条形图,同时重要性以排序方式水平显示。我也在探索seaborn
,但找不到方法。
回答by fordy
Quick answer for data scientists that ain't got no time to waste:
对于没有时间浪费的数据科学家的快速回答:
Load the feature importances into a pandas series indexed by your column names, then use its plot method. For a classifier model
trained using X
:
将特征重要性加载到由列名索引的 Pandas 系列中,然后使用其 plot 方法。对于使用model
训练的分类器X
:
feat_importances = pd.Series(model.feature_importances_, index=X.columns)
feat_importances.nlargest(20).plot(kind='barh')
Slightly more detailed answer with a full example:
带有完整示例的更详细的答案:
Assuming you trained your model with data contained in a pandas dataframe, this is fairly painless if you load the feature importance into a panda's series, then you can leverage its indexing to get the variable names displayed easily. The plot argument kind='barh'
gives us a horizontal bar chart, but you could easily substitute this argument for kind='bar'
for a traditional bar chart with the feature names along the x-axis if you prefer.
假设您使用包含在 Pandas 数据框中的数据训练模型,如果您将特征重要性加载到 Panda 的系列中,这将是相当轻松的,然后您可以利用它的索引来轻松显示变量名称。plot 参数kind='barh'
为我们提供了一个水平条形图,但kind='bar'
如果您愿意,您可以轻松地将此参数替换为具有沿 x 轴的特征名称的传统条形图。
nlargest(n)
is a pandas Series method which will return a subset of the series with the largest n
values. This is useful if you've got lots of features in your model and you only want to plot the most important.
nlargest(n)
是一个熊猫系列方法,它将返回具有最大值的系列的子集n
。如果您的模型中有很多特征并且您只想绘制最重要的特征,这将非常有用。
A quick complete example using the classic Kaggle Titanic dataset...
使用经典 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!
Which will give you this:
这会给你这个:
回答by Y. Luo
Not exactly sure what you are looking for. Derived a example from here. As mentioned in the comment: you can change indices
to a list of labels at line plt.yticks(range(X.shape[1]), indices)
if you want to customize feature labels.
不完全确定你在找什么。从这里推导出一个例子。如评论中所述:如果您想自定义功能标签,您可以indices
在 line 处更改为标签列表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()
回答by Ruthless Devil
It's possible to just pass df.columns
as the parameter for plt.xticks()
,i have written a sample implementation.
可以只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()