【问题标题】:xgboost in Python is not returning importance of features despite what is referred in the documentation尽管文档中提到了,但 Python 中的 xgboost 并未返回功能的重要性
【发布时间】:2019-07-09 10:20:24
【问题描述】:

根据 xgboost 文档 (https://xgboost.readthedocs.io/en/latest/python/python_api.html#module-xgboost.training),xgboost 返回特征重要性:

feature_importances_

特征重要性属性

注意

特征重要性仅针对树助推器定义。仅在选用决策树模型作为基础学习者时定义了重要性 ((booster=gbtree)。它没有为其他基础学习器类型定义,例如线性学习器 (booster=gblinear)。

返回: feature_importances_

返回类型: 形状数组 [n_features]

但是,这似乎并非如此,如下面的玩具示例所示:

import seaborn as sns
import xgboost as xgb

mpg = sns.load_dataset('mpg')

toy = mpg[['mpg', 'cylinders', 'displacement', 'horsepower', 'weight',
       'acceleration']]

toy = toy.sample(frac=1)

N = toy.shape[0]

N1 = int(N/2)

toy_train = toy.iloc[:N1, :]
toy_test = toy.iloc[N1:, :]

toy_train_x = toy_train.iloc[:, 1:]

toy_train_y = toy_train.iloc[:, 1]

toy_test_x = toy_test.iloc[:, 1:]

toy_test_y = toy_test.iloc[:, 1]

max_depth = 6
eta = 0.3
subsample = 0.8
colsample_bytree = 0.7
alpha = 0.1

params = {"booster" : 'gbtree' , 'objective' : 'reg:linear' , 'max_depth' : max_depth, 'eta' : eta,\
             'subsample' : subsample, 'colsample_bytree' : colsample_bytree, 'alpha' : alpha}

dtrain_toy = xgb.DMatrix(data = toy_train_x , label = toy_train_y)
dtest_toy = xgb.DMatrix(data = toy_test_x, label = toy_test_y)
watchlist = [(dtest_toy, 'eval'), (dtrain_toy, 'train')]

xg_reg_toy = xgb.train(params = params, dtrain = dtrain_toy, num_boost_round = 1000, evals = watchlist, \
                early_stopping_rounds = 20)

xg_reg_toy.feature_importances_
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-378-248f7887e307> in <module>()
----> 1 xg_reg_toy.feature_importances_

AttributeError: 'Booster' object has no attribute 'feature_importances_'

【问题讨论】:

  • 你试过xgboost sklearn,因为它对我有用
  • 是的,scikit learn API 确实返回了特征重要性。

标签: python xgboost


【解决方案1】:

您使用的是Learning API,但您引用的是Scikit-Learn API。并且只有 Scikit-Learn API 具有属性 feature_importances

【讨论】:

    【解决方案2】:

    对于像我这样不使用 Scikit-Learn API 的人来说,原因很明显。 从here 我了解到该功能的重要性:

    clf.get_score()
    

    另外,我正在研究更直观的表示 here

    from xgboost import plot_importance
    plot_importance(clf, max_num_features=10)
    

    这会按重要性顺序生成带有指定(可选)max_num_features 的条形图。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-23
      • 2018-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多