使用 xgb 和 ranger 的特征重要性图。比较的最佳方式

Feature importance plot using xgb and also ranger. Best way to compare

我正在编写一个脚本来训练 ranger 随机森林和 xgb 回归。根据哪个基于 rmse 表现最好,一个或另一个用于测试保持数据。

我还想return以可比较的方式对两者的重要性进行描述。

使用 xgboost 库,我可以获得我的特征重要性 table 并像这样绘制:

> xgb.importance(model = regression_model)
                 Feature        Gain       Cover  Frequency
1:              spend_7d 0.981006272 0.982513621 0.79219969
2:                   IOS 0.006824499 0.011105014 0.08112324
3:  is_publisher_organic 0.006379284 0.002917203 0.06770671
4: is_publisher_facebook 0.005789945 0.003464162 0.05897036

然后我可以这样画:

> xgb.importance(model = regression_model) %>% xgb.plot.importance()

那是使用 xgboost 库及其函数。使用 ranger random forrest,如果我拟合回归模型,如果我在拟合模型时包含 importance = 'impurity',我可以获得特征重要性。那么:

regression_model$variable.importance
             spend_7d        d7_utility_sum  recent_utility_ratio                   IOS  is_publisher_organic is_publisher_facebook 
         437951687132                     0                     0             775177421             600401959            1306174807 

我可以创建一个 ggplot。但是 table 中的 ranger returns 和图中 xgb 显示的比例完全不同。

是否有开箱即用的库或解决方案,我可以在其中以可比较的方式绘制 xgb 或 ranger 模型的特征重要性?

XGboost 的 "Gain" 列和带有参数 "impurity" 的 ranger 的重要性都是通过给定变量拆分的杂质总减少量(因此增益)构建的。

唯一的区别似乎是,虽然 XGboost 自动以百分比形式生成重要性,但 ranger 将它们保留为原始值,因此平方和,这不是很容易绘制。因此,您可以通过将游侠重要性除以总和来转换游侠重要性的值,这样您将获得与 Xgboost 中相同的百分比。

由于使用杂质减少有时会产生误导,但我建议您通过排列计算(对于两个模型)变量的重要性。这使您能够以一种简单的方式获得重要性,这种方式对于不同的模型具有可比性,并且更加稳定。

我建议 this incredibly helpful post

这是其中定义的排列重要性(抱歉,它是 Python,不是 R):

def permutation_importances(rf, X_train, y_train, metric):
  baseline = metric(rf, X_train, y_train)
  imp = []
  for col in X_train.columns:
    save = X_train[col].copy()
    X_train[col] = np.random.permutation(X_train[col])
    m = metric(rf, X_train, y_train)
    X_train[col] = save
    imp.append(baseline - m)
return np.array(imp)

但是,ranger 还允许通过 importance="permutation" 计算排列重要性,xgboost 也可以这样做。