使用随机森林包: -
#install.packages("randomForest")
library(randomForest)
我用了一个在线代码来运行我的系统上随机森林。我买了混淆矩阵和精度等的模型现在,我的数据是在训练和验证集的形式。我从这里得到的数据: - https://archive.ics.uci.edu/ml/machine-learning-databases/car/我在70%-30%的比例将其划分(训练 - 验证,分别地)。然后我跑了它的模型。模型结果给了我大约30观测错误归类为在其上运行的随机森林变量的一个特定值的答案。下面是样本数据: -
BuyingPrice Maintenance NumDoors NumPersons Bootspace Safety Condition
vhigh low 4 4 med low unacc
vhigh med 2 4 med high acc
vhigh med 2 more small high unacc
vhigh high 3 4 big high unacc
vhigh med 4 more small med unacc
low low 2 more med med acc
在随机森林是在预测的最后一个变量,“条件”运行。下面是模型摘要
Call:
randomForest(formula = Condition ~ ., data = TrainSet, ntree = 500,
mtry = 6, importance = TRUE)
Type of random forest: classification
Number of trees: 500
No. of variables tried at each split: 6
OOB estimate of error rate: 2.48%
Confusion matrix:
acc good unacc vgood class.error
acc 244 4 6 2 0.04687500
good 3 44 1 0 0.08333333
unacc 11 1 843 0 0.01403509
vgood 2 0 0 47 0.04081633
如果我们把表(一个只有我们以上)的第一行,我们看到的是价值“ACC”已经有244个正确的预测(95%)和12个错误的预测。同样,“好”已经有44个正确的预测(91%)和4个错误的预测。等等其他两个。错误的预测的总数目是30(12 + 4 + 12 + 2)现在,在技术上该模型的预测值应该从实际由30个错误分类值不同。现在,我试图用两种方法得到的预测值: -
1. First method :- model2$predicted.
2. Second method :- predTrain <- predict(model2, TrainSet, type = "class")
第一种方法使我的预测值集,从30位的实际的不同而第二种方法给我的数据集,则正好等于实际值。我认为第一种方法是正确的,但在链接的家伙已经用第二个。
https://www.r-bloggers.com/how-to-implement-random-forests-in-r/
不知道在我的概念是走错了,请帮忙。 PS: - 我知道的是,已经被问过类似的问题,但我觉得,无论是问题,它下面的答案是不够精细或容易解释我。这就是为什么,我问了一个新问题。
样品编号
set.seed(100)
train <- sample(nrow(data1),0.7*nrow(data1),replace=FALSE)
TrainSet <- data1[train,]
ValidSet <- data1[-train,]
model2 <- randomForest(Condition ~ ., data = TrainSet, ntree = 500, mtry=6,
importance = TRUE)
predTrain <- predict(model2, TrainSet, type = "class")
new1 <- data.frame(actual = TrainSet$Condition, predicted = predTrain)
new2 <- data.frame(actual = TrainSet$Condition, predicted =
model2$predicted)
new1$third <- 0
for(i in 1:nrow(new1))
{
if(new1[i,1] == new1[i,2])
{
new1[i,3] = 1
}else{
new1[i,3] = 0
}
}
new2$third <- 0
for(i in 1:nrow(new2))
{
if(new2[i,1] == new2[i,2])
{
new2[i,3] = 1
}else{
new2[i,3] = 0
}
}
谢谢,阿沛
据随机森林函数的文档:预测:基于外的袋样品输入数据的预测值。
因此,与不使用这种观察模型获得的观测值的预测值。
该预测功能适用学会了新的数据模型,不知道他们是用于训练。因此,任何观察同时用于学习和预测。
你应该使用的预测输出为每个预测值计算,而不用于训练相应的观察。