【问题标题】:Extract a tree from a random forest and then use the extracted tree for prediction从随机森林中提取一棵树,然后使用提取的树进行预测
【发布时间】:2020-09-02 17:05:24
【问题描述】:

我们以鸢尾花数据集为例。

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】:

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

【讨论】:

    猜你喜欢
    • 2014-03-01
    • 2013-12-31
    • 2020-02-28
    • 2017-12-24
    • 2020-12-13
    • 2018-05-27
    • 1970-01-01
    • 2018-04-06
    • 2019-10-07
    相关资源
    最近更新 更多