【发布时间】:2020-07-24 12:41:34
【问题描述】:
我正在评估我的决策树分类器,并且我正在尝试绘制特征重要性。该图可以正确打印,但它会打印所有(80 多个)特征,这会产生非常混乱的视觉效果。我试图弄清楚如何按重要性顺序将绘图限制在重要的变量上。
数据集的链接供您下载到您的工作目录,命名为(“文件”):https://github.com/Arsik36/Python
最小可重现代码:
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
file = 'file.xlsx'
my_df = pd.read_excel(file)
# Determining response variable
my_df_target = my_df.loc[ :, 'Outcome']
# Determining explanatory variables
my_df_data = my_df.drop('Outcome', axis = 1)
# Declaring train_test_split with stratification
X_train, X_test, y_train, y_test = train_test_split(my_df_data,
my_df_target,
test_size = 0.25,
random_state = 331,
stratify = my_df_target)
# Declaring class weight
weight = {0: 455, 1:1831}
# Instantiating Decision Tree Classifier
decision_tree = DecisionTreeClassifier(max_depth = 5,
min_samples_leaf = 25,
class_weight = weight,
random_state = 331)
# Fitting the training data
decision_tree_fit = decision_tree.fit(X_train, y_train)
# Predicting on the test data
decision_tree_pred = decision_tree_fit.predict(X_test)
# Declaring the number of features in the X_train data
n_features = X_train.shape[1]
# Setting the plot window
figsize = plt.subplots(figsize = (12, 9))
# Specifying the contents of the plot
plt.barh(range(n_features), decision_tree_fit.feature_importances_, align = 'center')
plt.yticks(pd.np.arange(n_features), X_train.columns)
plt.xlabel("The degree of importance")
plt.ylabel("Feature")
【问题讨论】:
-
在 plt.barh 中使用
decision_tree_fit.feature_importances_[tree.feature_importances_> 0.0.5] -
@CristianContrera 我试过这个,但不太奏效。条件外的特征仍然存在,只是它们的条形值消失了,它们不满足条件。您知道如何从不满足条件的图形中消除特征吗?当我尝试您的解决方案时,我收到以下错误:ValueError: shape mismatch: objects cannot be broadcast to a single shape
标签: python machine-learning decision-tree