从随机森林中提取一棵树,然后使用提取的树进行预测

Extract a tree from a random forest and then use the extracted tree for prediction

例如,让我们使用鸢尾花数据集。

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.all 参数设置为 TRUE 来直接使用 randomForest 包中的 predict 函数。

请参阅以下可重现的代码以了解如何使用它:另请参阅 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