首页 > 解决方案 > len(alg.feature_importances_) 与 len(输入变量) 不一致

问题描述

如果我询问我的 LightGBM 模型的特征重要性分数,我会得到比输入变量(预测变量)的数量更长的字符串:

 len(alg.feature_importances_) = 50
 len(predictors) = 46

我使用的预测设置如下:

    alg = lgb.LGBMClassifier(boosting_type = 'gbdt', colsample_bytree = 0.75,
                             importance_type = 'split',
                             learning_rate = 0.1, max_depth = 7,
                             n_estimators = 500,  num_leaves = 10, reg_lambda= 0.01, min_child_samples=25) 

alg.fit(train[predictors], train[target])
alg.predict(test[predictors])
alg.proba(test[predictors])

那么得到的特征重要性如下:alg.feature_importances_

array([83, 88, 14, 10, 17, 13,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
        0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
        0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0])

输入变量(预测变量)如下:print(predictors)

['Prob1',
 'Prob2',
 'Comeback1',
 'Comeback2',
 'compare srp_1',
 'compare srp_2',
 'meang-W5_1',
 'meang-W5_2',
 'ratings-W100_1',
 'ratings-W100_2',
 'meang-W100_1',
 'meang-W100_2',
 'meangr-W5_1',
 'meangr-W5_2',
 'meangr-W100_1',
 'meangr-W100_2',
 'meangs-W5_1',
 'meangs-W5_2',
 'meangs-W100_1',
 'meangs-W100_2',
 'meanp-W20_1',
 'meanp-W20_2',
 'meanp-W1000_1',
 'meanp-W1000_2',
 'meanrp-W20_1',
 'meanrp-W20_2',
 'meanrp-W1000_1',
 'meanrp-W1000_2',
 'meansp-W20_1',
 'meansp-W20_2',
 'meansp-W1000_1',
 'meansp-W1000_2',
 'meanrp + meansp-W20_1',
 'meanrp + meansp-W20_2',
 'meanrp + meansp-W100_1',
 'meanrp + meansp-W100_2',
 'scoregames_1',
 'scoregames_2',
 'setsscore_1',
 'setsscore_2',    
 'ratings_1',
 'ratings_2',
 'ratings-W100_1',
 'ratings-W100_2',
 'momentum_1',
 'momentum_2']

对我来说这是一个问题,因为我不知道哪个特征分数属于哪个变量。看起来某些特征/变量会产生多个特征分数。

标签: machine-learninglightgbm

解决方案


feature_importance仅返回一个 numpy 数组,因此缺少标签并不是模型没有特征名称的标志,而是常规行为。

我通常绘制特征重要性,其中显示标签。从代码中,我得到了实际需要做的事情。这是:

importance = booster.feature_importance(importance_type='gain') # or 'split'
feature_name = booster.feature_name()
list(zip(feature_name, importance))

如果您使用 sklearn api 并且没有助推器的句柄,您会得到它(如果 alg 是您训练的 sklearn 包装器对象):

booster= alg.booster_

如果你想直接绘制重要性,你可以这样做:

lightgbm.plot_importance(booster, importance_type='gain')

推荐阅读