从随机森林中提取一棵树,然后将提取的树用于预测

问题描述 投票:0回答:1

作为示例,让我们使用虹膜数据集。

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()”一样,有没有直接执行此功能的函数?

提前谢谢您

r machine-learning classification random-forest decision-tree
1个回答
0
投票

您可以通过将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

© www.soinside.com 2019 - 2024. All rights reserved.