使用ranger进行变量重要性分析

24

我使用caret + ranger训练了一个随机森林。

fit <- train(
    y ~ x1 + x2
    ,data = total_set
    ,method = "ranger"
    ,trControl = trainControl(method="cv", number = 5, allowParallel = TRUE, verbose = TRUE)
    ,tuneGrid = expand.grid(mtry = c(4,5,6))
    ,importance = 'impurity'
)

现在我想要讲述变量的重要性。然而,这些都无法正常工作:

> importance(fit)
Error in UseMethod("importance") : no applicable method for 'importance' applied to an object of class "c('train', 'train.formula')"
> fit$variable.importance
NULL
> fit$importance
NULL

> fit
Random Forest 

217380 samples
    32 predictors

No pre-processing
Resampling: Cross-Validated (5 fold) 
Summary of sample sizes: 173904, 173904, 173904, 173904, 173904 
Resampling results across tuning parameters:

  mtry  RMSE        Rsquared 
  4     0.03640464  0.5378731
  5     0.03645528  0.5366478
  6     0.03651451  0.5352838

RMSE was used to select the optimal model using  the smallest value.
The final value used for the model was mtry = 4. 

有什么办法可以获取它吗?

谢谢。

3个回答

19

varImp(fit)会为您获取它。

为了弄清楚这一点,我查看了names(fit),这引导我到names(fit$modelInfo) - 然后你会看到varImp是其中一个选项。


10
同时我也通过查看 caret 的文档找到了它。感谢你提供的这种寻找信息的有用方法!然而,对于大多数使用 carettrain() 训练出来的模型,似乎 varImp() 是获取变量重要性的方法。未来的用户需注意:我并不确定,并且没有时间去验证,但据我所知,在 train() 中,需要将参数 importance = 'impurity'(我猜也可以传入 importance = 'permutation')以便使用 varImp() - François M.
10
另一个注意事项:似乎如果你使用ranger但没有用caret训练模型,那么importance(fit)将是获取变量重要性的正确方式。同上,我认为参数importance ='impurity'(或'permutation')需要在train()中。 - François M.
1
奇怪,它对我不起作用。没有可用的重要性值... 嗯 - Hack-R
1
这对我不起作用。该函数存在,但返回的重要值不可用? - KillerSnail
10
只是为了明确,ranger 的默认设置是不计算 importance 的。您必须显式指定 importance = 'impurity'importance = 'permutation' 以使任何这些方法工作,即使您正在使用 train - John M
1
由于我找了很久才找到这个,所以请注意 varImp 也适用于使用 caret 训练的 Rborist 模型。 - cuttlefish

13
根据 @fmalaussena 的说法
set.seed(123)
ctrl <- trainControl(method = 'cv', 
                     number = 10,
                     classProbs = TRUE,
                     savePredictions = TRUE,
                     verboseIter = TRUE)

rfFit <- train(Species ~ ., 
               data = iris, 
               method = "ranger",
               importance = "permutation", #***
               trControl = ctrl,
               verbose = T)

你可以将 "permutation" 或者 "impurity" 传递给参数 importance。 这两个值的描述可以在这里找到:https://alexisperrier.com/datascience/2015/08/27/feature-importance-random-forests-gini-accuracy.html

抱歉,链接已失效。请考虑替换链接。 - undefined

9
对于“ranger”软件包,您可以使用以下命令调用重要性:

importance(ranger)

fit$variable.importance

顺便提一下,您可以使用str()函数查看模型的所有可用输出。

str(fit)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接