Agi
Agi

Reputation: 83

Accessing Importance of each element in Random Forest in R

I have a prediction model using random forest with rolling window. In each iteration, I am saving the importance of the rf model into a list (let's say list1). At the end, this list (list1) includes many lists (list2) of length 1. In each of these lists (list2), I have the importance of one iteration. I want to access the %IncMSE of each element in this list (list2). For example, I want to reach lag1.mat1 %IncMSE which is 26.01262.

enter image description here

The problem is that the list (list2) is of length one, so I am not able to access the value itself.

enter image description here

Is there any way I can do this?

Upvotes: 0

Views: 122

Answers (2)

StupidWolf
StupidWolf

Reputation: 46898

I am guessing your data looks like this:

library(randomForest)
lst = lapply(1:2,function(i){
list(randomForest(mpg~.,data=mtcars,importance=TRUE)$importance)
})

 str(lst)
List of 2
 $ :List of 1
  ..$ : num [1:10, 1:2] 6.921 9.651 7.495 0.984 9.178 ...
  .. ..- attr(*, "dimnames")=List of 2
  .. .. ..$ : chr [1:10] "cyl" "disp" "hp" "drat" ...
  .. .. ..$ : chr [1:2] "%IncMSE" "IncNodePurity"
 $ :List of 1
  ..$ : num [1:10, 1:2] 7.138 10.257 7.422 0.631 10.027 ...
  .. ..- attr(*, "dimnames")=List of 2
  .. .. ..$ : chr [1:10] "cyl" "disp" "hp" "drat" ...
  .. .. ..$ : chr [1:2] "%IncMSE" "IncNodePurity"

head(lst[[1]][[1]])
      %IncMSE IncNodePurity
cyl  6.9211021     170.12901
disp 9.6509747     248.54840
hp   7.4951588     206.99009
drat 0.9839875      64.95373
wt   9.1778411     246.08167
qsec 0.7464294      43.20173

If you only want cyl:

sapply(lst,function(x)x[[1]]["cyl","%IncMSE"])

If you need everything:

lapply(lst,function(x)x[[1]][,"%IncMSE"])

Upvotes: 1

It would have been helpful to see at least parts of your code, but basically, you can access them by doing this: Assuming you've grown this tree:

RF = purrr::accumulate( .init = update(rf_mod, ntree=1),
                          rep(1,100), randomForest::grow )
imp = purrr::map( RF, ~importance(.x)[,"%IncMSE"] )

From there you get the one you need in the list. For a more concise answer, post your code.

Upvotes: 0

Related Questions