sta*_*010 19 python machine-learning pandas xgboost
我正在使用XGBoost和Python,并使用train()
名为DMatrix
数据的XGBoost 函数成功训练了一个模型.矩阵是从Pandas数据框创建的,该数据框具有列的特征名称.
Xtrain, Xval, ytrain, yval = train_test_split(df[feature_names], y, \
test_size=0.2, random_state=42)
dtrain = xgb.DMatrix(Xtrain, label=ytrain)
model = xgb.train(xgb_params, dtrain, num_boost_round=60, \
early_stopping_rounds=50, maximize=False, verbose_eval=10)
fig, ax = plt.subplots(1,1,figsize=(10,10))
xgb.plot_importance(model, max_num_features=5, ax=ax)
Run Code Online (Sandbox Code Playgroud)
我现在想要使用该xgboost.plot_importance()
函数查看功能重要性,但结果图不显示功能名称.但是,这些功能被列为f1
,f2
,f3
等如下所示.
我认为问题是我将原来的Pandas数据帧转换为DMatrix.如何正确关联要素名称以使特征重要性图显示它们?
piR*_*red 21
您想feature_names
在创建时使用该参数xgb.DMatrix
dtrain = xgb.DMatrix(Xtrain, label=ytrain, feature_names=feature_names)
Run Code Online (Sandbox Code Playgroud)
如果您使用的是scikit-learn包装器,则需要访问基础XGBoost Booster并在其上设置功能名称,而不是scikit模型,如下所示:
model = joblib.load("your_saved.model")
model.get_booster().feature_names = ["your", "feature", "name", "list"]
xgboost.plot_importance(model.get_booster())
Run Code Online (Sandbox Code Playgroud)
train_test_split
将数据帧转换为numpy数组,该数组不再具有列信息.
您可以执行@piRSquared建议的操作,并将这些功能作为参数传递给DMatrix构造函数.或者,您可以将从返回的numpy数组转换train_test_split
为Dataframe,然后使用您的代码.
Xtrain, Xval, ytrain, yval = train_test_split(df[feature_names], y, \
test_size=0.2, random_state=42)
# See below two lines
X_train = pd.DataFrame(data=Xtrain, columns=feature_names)
Xval = pd.DataFrame(data=Xval, columns=feature_names)
dtrain = xgb.DMatrix(Xtrain, label=ytrain)
Run Code Online (Sandbox Code Playgroud)
小智 5
使用 Scikit-Learn Wrapper 接口“XGBClassifier”,plot_importance 返回类“matplotlib Axes”。所以我们可以使用axes.set_yticklabels。
plot_importance(model).set_yticklabels(['feature1','feature2'])