Sklearn Random Forest Feature Importance - Plot Using Matplotlib

Python

A code snippet showing how to plot a horizontal bar chart showing the features importances for an Sklearn Random Forest model.

 1|  import matplotlib.pyplot as plt
 2|  from sklearn.ensemble import RandomForestRegressor
 3|  
 4|  # Step 1: Train Random Forest model
 5|  model = RandomForestRegressor()
 6|  model.fit(X_train, y_train)
 7|  
 8|  # Step 2: Plot feature importances
 9|  features = X_train.columns
10|  importance_values = model.feature_importances_
11|  
12|  plt.barh(y=range(len(features)),
13|           width=importance_values,
14|           tick_label=features)
15|  plt.show()
Did you find this snippet useful?

Sign up for free to to add this to your code library