Как построить топ5 features_importances, используя RandomForestRegressor - PullRequest
0 голосов
/ 31 мая 2019

Я пытаюсь построить feature_importance модели RandomForestRegressor. Тем не менее, в моем наборе данных есть 307 функций (после OneHotEncoding), поэтому построение их всех не очень полезно с эстетической точки зрения.

Как я могу построить только топ-5 (или топ-10)?

Вот мой фактический код:

# Help function to plot feature_importances 
def plot_feature_importances(model_to_plot, features_list, x_train_set):
    # Wichtigkeit der eizelnen Features plotten! 

    plt_x = np.linspace(0,len(features_list)-1,len(features_list))

    print("Features sorted by their score:")

    font = {'family' : 'normal',
            'weight' : 'normal',
            'size'   : 12}

    plt.rc('font', **font)

    plt.figure(figsize=(15,7))

    plt.bar(plt_x, model_to_plot.feature_importances_, width=0.5, color="blue",align='center')
    plt.gca().set_xticklabels(plt_x, rotation=60 )
    plt.title('Features importance in decision making', position=(.5,1.05), fontsize=20)
    plt.xticks(plt_x, features_list, fontsize=12)
    plt.yticks(fontsize=12)
    plt.ylabel('Relative Information %', fontsize=15)
    plt.xlabel('Features', fontsize=15)
    plt.show()

    print("Feature ranking:")

    importances = model_to_plot.feature_importances_
    std = np.std([tree.feature_importances_ for tree in model_to_plot.estimators_],
                 axis=0)
    indices = np.argsort(importances)[::-1]

    for f in range(x_train.shape[1]):
        print("%d. Feature %s (%.2f)" % (f + 1, x_train_set.columns[indices[f]], importances[indices[f]]))

и построение графика с использованием следующего кода дает мне что-то вроде этого:

plot_feature_importances(model, features, x_train)

plot feature importances

1 Ответ

0 голосов
/ 31 мая 2019

Вы не предоставили Минимальный, Полный и Проверяемый пример , поэтому я не могу дать окончательный рабочий ответ.Тем не менее, вы можете попробовать следующий модифицированный код.Я убрал строки для установки х-тиков.Но эта часть тривиальна

def plot_feature_importances(model_to_plot, features_list, x_train_set):
    to_plot = 5 # <---- Define the number to plot
    importances = model_to_plot.feature_importances_
    std = np.std([tree.feature_importances_ for tree in model_to_plot.estimators_],
                 axis=0)
    indices = np.argsort(importances)[::-1][0:to_plot] # <--- Take the top 5 

    font = {'family' : 'normal',
            'weight' : 'normal',
            'size'   : 12}

    plt.rc('font', **font)

    plt.figure(figsize=(15,7))

    plt.bar(range(to_plot), importances[indices], width=0.5, color="blue",align='center') # <--- Plot the top 5 
    plt.xticks(range(to_plot), features_list[indices], fontsize=12) # <--- add ticks
    plt.title('Features importance in decision making', position=(.5,1.05), fontsize=20)
    plt.yticks(fontsize=12)
    plt.ylabel('Relative Information %', fontsize=15)
    plt.xlabel('Features', fontsize=15)
    plt.show()

    for f in range(x_train.shape[1]):
        print("%d. Feature %s (%.2f)" % (f + 1, x_train_set.columns[indices[f]], importances[indices[f]]))

plot_feature_importances(model, features, x_train)
...