作为示例,让我们使用虹膜数据集。
library(randomForest)
data(iris)
smp_size <- floor(0.75 * nrow(iris))
train_ind <- sample(seq_len(nrow(iris)), size = smp_size)
train <- iris[train_ind, ]
test <- iris[-train_ind, ]
model <- randomForest(Species~., data = train, ntree=10)
如果我使用randomForest包中的getTree()函数,则可以毫无问题地提取出第三棵树。
treefit <- getTree(model, 3)
例如,如何使用该值(即treefit)对测试集进行预测?像“ predict()”一样,有没有直接执行此功能的函数?
提前谢谢您
您可以通过将predict
参数设置为randomForest
来直接使用predict.all
包中的TRUE
功能。
有关如何使用它的信息,请参见以下可复制代码:另请参见predict.randomForest here的帮助页面。
library(randomForest)
set.seed(1212)
x <- rnorm(100)
y <- rnorm(100, x, 10)
df_train <- data.frame(x=x, y=y)
x_test <- rnorm(20)
y_test <- rnorm(20, x_test, 10)
df_test <- data.frame(x = x_test, y = y_test)
rf_fit <- randomForest(y ~ x, data = df_train, ntree = 500)
# You get a list with the overall predictions and individual tree predictions
rf_pred <- predict(rf_fit, df_test, predict.all = TRUE)
rf_pred$individual[, 3] # Obtains the 3rd tree's predictions on the test data