我使用plot_importance来显示重要变量。但是有些变量是分类变量,所以我对它们进行了一些转换。在我转换了变量类型后,当我绘制重要特征时,图表并未显示特征名称。我附上了我的代码和图表。dataset = data.values X = dataset[1:100,0:-2]
predictors=dataset[1:100,-1]X = X.astype(str)encoded_x = Nonefor i in range(0, X.shape[1]): label_encoder = LabelEncoder() feature = label_encoder.fit_transform(X[:,i]) feature = feature.reshape(X.shape[0], 1) onehot_encoder = OneHotEncoder(sparse=False) feature = onehot_encoder.fit_transform(feature) if encoded_x is None: encoded_x = feature else: encoded_x = np.concatenate((encoded_x, feature), axis=1)print("X shape: : ", encoded_x.shape)response='Default'#predictors=list(data.columns.values[:-1])# Randomly split indexesX_train, X_test, y_train, y_test = train_test_split(encoded_x,predictors,train_size=0.7, random_state=5)model = XGBClassifier()model.fit(X_train, y_train)plot_importance(model)plt.show()[enter image description here][1] [1]: https://i.sstatic.net/M9qgY.png
回答:
这是预期的行为- sklearn.OneHotEncoder.transform()
返回的是一个numpy二维数组而不是输入的pd.DataFrame
(我假设这是你的dataset
的类型)。所以这不是一个bug,而是一个特性。看起来在sklearn API中没有办法手动传递特征名称(在原生训练API中创建xgb.Dmatrix
时可以设置这些)。
然而,你的问题可以很容易地通过使用pd.get_dummies()
来解决,而不是你实现的LabelEncoder
+ OneHotEncoder
组合。我不知道你为什么选择使用它(如果需要处理测试集时它可能有用,但那时你需要一些额外的技巧),但我建议使用pd.get_dummies()
。