Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable importance with ranger

I trained a random forest using 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'
)

Now I'd like to see the importance of variables. However, none of these work :

> 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. 

Any idea if & how I can get it ?

Thanks.

like image 453
François M. Avatar asked May 17 '16 15:05

François M.


3 Answers

varImp(fit) will get it for you.

To figure that out, I looked at names(fit), which led me to names(fit$modelInfo) - then you'll see varImp as one of the options.

like image 144
Tchotchke Avatar answered Oct 24 '22 17:10

Tchotchke


For 'ranger' package you could call an importance with

fit$variable.importance

As a side note, you could see the all available outputs for the model using str()

str(fit)
like image 32
Polina Mamoshina Avatar answered Oct 24 '22 16:10

Polina Mamoshina


according to @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)

You can pass either "permutation" or "impurity" to argument importance. The description for both value can be found here: https://alexisperrier.com/datascience/2015/08/27/feature-importance-random-forests-gini-accuracy.html

like image 40
NaNxT Avatar answered Oct 24 '22 15:10

NaNxT