簡體   English   中英

在 R 中訪問隨機森林中每個元素的重要性

[英]Accessing Importance of each element in Random Forest in R

我有一個使用帶有滾動窗口的隨機森林的預測模型。 在每次迭代中,我都將 rf 模型的importance保存到一個列表中(比如 list1)。 最后,這個列表 (list1) 包括許多長度為 1 的列表 (list2)。在這些列表 (list2) 中的每一個中,我都有一個迭代的importance 我想訪問此列表 (list2) 中每個元素的%IncMSE 例如,我想達到 lag1.mat1 %IncMSE ,即 26.01262。

在此處輸入圖片說明

問題是列表 (list2) 的長度為 1,因此我無法訪問該值本身。

在此處輸入圖片說明

有什么辦法可以做到這一點嗎?

我猜你的數據是這樣的:

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

如果你只想要 cyl:

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

如果您需要一切:

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

至少查看部分代碼會很有幫助,但基本上,您可以通過以下方式訪問它們:假設您已經種植了這棵樹:

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

從那里你會得到你需要的列表。 要獲得更簡潔的答案,請發布您的代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM