Created
August 27, 2020 23:31
-
-
Save jpiwowar/46f6c0e12c284e2473f38ea3eaebca3e to your computer and use it in GitHub Desktop.
Convenience function for displaying feature importance list from DT or RF.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def show_importance(model,title,X,y,n=10,show_score=True): | |
''' | |
Display feature importance list for a decision tree or | |
random forest model, optionally displaying the accuracy score | |
model: Decision tree or random forest model | |
title: title text for plot | |
X: Independent variables | |
y: Target variables | |
n: Number of important features to show (default=10 | |
show_score: calculate accuracy score (default=True) | |
''' | |
my_df=pd.DataFrame([model.feature_importances_], | |
columns=X.columns)\ | |
.sort_values(0,axis=1).iloc[:,-n:] | |
plt.figure(figsize=[8,6]) | |
plt.barh(my_df.columns,width=my_df.loc[0]) | |
plt.ylabel("Feature name") | |
plt.xlabel("Importance") | |
plt.title(f'{title}\n(top {n} features)') | |
plt.show() | |
if show_score: | |
print(f'Model parameters:{model.get_params}\n\n') | |
print(f'Model score:{model.score(X,y)}') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment