我在使用LightGBM中的LGBMClassifer构建一个二分类模型,类似如下所示:
# LightGBM模型 clf = LGBMClassifier( nthread=4, n_estimators=10000, learning_rate=0.005, num_leaves= 45, colsample_bytree= 0.8, subsample= 0.4, subsample_freq=1, max_depth= 20, reg_alpha= 0.5, reg_lambda=0.5, min_split_gain=0.04, min_child_weight=.05 random_state=0, silent=-1, verbose=-1)
接下来,在训练数据上拟合我的模型
clf.fit(train_x, train_y, eval_set=[(train_x, train_y), (valid_x, valid_y)], eval_metric= 'auc', verbose= 100, early_stopping_rounds= 200) fold_importance_df = pd.DataFrame() fold_importance_df["feature"] = feats fold_importance_df["importance"] = clf.feature_importances_
输出结果:
feature importancefeature13 1108feature21 1104feature11 774
-
到目前为止一切顺利,现在我想基于这个模型查看特征重要性度量。因此,我使用
feature_importance_()
函数来获取这些数据(但默认情况下它提供的是基于split
的特征重要性) -
虽然
split
可以让我了解到某个特征在分割中被使用了多少次,但我认为gain
可以更好地理解特征的重要性。 -
LightGBM booster类的Python API 中提到(https://lightgbm.readthedocs.io/en/latest/Python-API.html?highlight=importance):
feature_importance(importance_type='split', iteration=-1) 参数:importance_type (string, optional (default="split")) – 如果是“split”,结果包含特征在模型中使用的次数。如果是“gain”,结果包含使用该特征的分割的总收益。返回值: result – 包含特征重要性的数组。返回类型: numpy array`
然而,Sklearn API对于LightGBM的LGBMClassifier()
并没有提及任何内容(Sklearn API LGBM),它对该函数的参数描述仅如下:
feature_importances_array of shape = [n_features] – 特征重要性(数值越高,特征越重要)。
- 我的问题是如何从
sklearn
版本即LGBMClassifier()
中基于gain
获取特征重要性?
回答:
feature_importance()
是原始LGBM中Booster对象的一个方法。
sklearn API通过属性booster_
暴露了训练数据上的底层Booster,如API文档中所述。
所以你可以先访问这个booster对象,然后以与原始LGBM相同的方式调用feature_importance()
。
clf.booster_.feature_importance(importance_type='gain')