2017-06-13 6 views
1

Rには、ランダムフォレストモデルの機能の重要性をプロットするための事前ビルドされた関数があります。しかし、Pythonでこのようなメソッドが欠落しているようです。私はmatplotlibの方法を探します。その後matplotlib:機能名によるプロット機能の重要性

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]) 

次プロット機能使用::私はbarplotを取得するが、重要性がソートされた形で水平に見せながら、私はラベルでbarplot取得したいと思い

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

model.feature_importancesは私に次のようになります。私もseabornを探していて、方法を見つけることができませんでした。

+1

あなたは 'barh'(水平バープロット)を探しています。フィーチャー名を 'tick_label'として渡します。 – DyZ

答えて

4

あなたが探しているものが正確ではありません。例を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() 

enter image description here

0

これはパンダプロット()メソッドを使用して、かなり無痛です。私たちのsklearnランダムフォレストモデルからトップ20の最も重要な機能をプロットしてみましょう、Xを使用して訓練:

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

このアプローチは自由のために、同様のプロットのy軸上の変数名を表示します。