我如何从R中的随机森林预测函数中按类别求和选票? [英] How can I sum votes by category from the randomForest predict function in R?
本文介绍了我如何从R中的随机森林预测函数中按类别求和选票?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
此示例代码创建一个dataframe,其初始列表示10个树中的多数票。接下来的10列包含模型中每棵树的分类投票。我想创建一个图表来显示每一行的选票分布。执行此操作的最佳方式是什么?
library(tidyverse)
library(caret)
library(randomForest)
train_index_cars <- as.vector(createDataPartition(mtcars[['cyl']],p=.8,list=FALSE,times=1))
mytrain <- mtcars[train_index_cars, ]
mytest <- mtcars[-train_index_cars, ]
car_forest <- randomForest(factor(cyl) ~., data= mytrain, ntree = 10, predict.all = T)
cartest_predicted <- as.data.frame(predict(car_forest, newdata = mytest, predict.all = TRUE))
cartest_predicted
中Merc 280行的输出如下所示(不包括最后6棵树)
id | 聚合率 | 个人1 | 个人2 | 个人.3 | 个人.4 |
---|---|---|---|---|---|
Merc 280 | 6 | 6 | 8 | 6 | 4 |
我想在每一行中添加三列,其中包含树中每个类别(4、6、8)的选票计数。我设想的输出如下:
个人。10 | Votes_4 | Votes_6 | Votes_8 |
---|---|---|---|
6 | 2 | 7 | 1 |
推荐答案
这应该可以工作:
# Defining temporarily function, to be passed within apply().
temp.fun = function(x) sum(x == i)
for (i in unique(cartest_predicted$aggregate)) # Iterating over possible votes.
{
i = as.integer(i)
cartest_predicted$temp = apply(cartest_predicted[, -1], MARGIN = 1, temp.fun) # Requested results.
colnames(cartest_predicted)[dim(cartest_predicted)[[2]]] = paste("Votes", i, sep = "_") # Renaming new column.
}
需要for
循环来迭代树可以投出的所有可能的选票。创建一个临时函数来执行每个i
,即每个可能的投票所需的操作。然后在apply()
内使用该函数,以应用于cartest_predict
(注意MARGIN = 1
)的每一行。最后,paste
用于重命名列。
这篇关于我如何从R中的随机森林预测函数中按类别求和选票?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文