首页 > 解决方案 > 如何从 R 中的 RandomForest 中提取节点大小默认值

问题描述

我知道如何nodesizeRandomForest. 但是,我想知道给定RandomForest模型的nodesize.

require(party)
require (data.table)
require (e1071)
require (randomForest)
dat1 <- fread('https://archive.ics.uci.edu/ml/machine-learning-databases/abalone/abalone.data',stringsAsFactors=T)

## split data to train and test
set.seed(123)
dat1 <- subset(dat1, !is.na(V1))
smp_size<-0.8*nrow(dat1)
train_ind <- sample(seq_len(nrow(dat1)), size = smp_size)
train <- dat1[train_ind, ]
test <- dat1[-train_ind, ]
rf1 <- randomForest(V1 ~ ., data = train,keep.inbag = TRUE)
rf2 <- randomForest(V1 ~ ., data = train, ntree = 50,keep.inbag = TRUE)

标签: rrandom-forest

解决方案


碰巧randomForest不返回节点大小参数。但是,它只有“三个”可能的值:要么由用户指定,要么由if (!is.null(y) && !is.factor(y)) 5 else 1(1 表示分类,5 表示回归)设置。因此,我们有

getNodesize <- function(x) {
  look <- pmatch(names(x$call), "nodesize")
  if(any(!is.na(look)))
    x$call[!is.na(look)][[1]]
  else if (!is.null(x$y) && !is.factor(x$y))
    5
  else
    1
}

rf1 <- randomForest(V1 ~ ., data = train)
getNodesize(rf1)
# [1] 1
rf1 <- randomForest(V1 ~ ., data = train, nodesi = 3)
getNodesize(rf1)
# [1] 3

推荐阅读