【发布时间】:2018-02-18 13:15:52
【问题描述】:
我正在尝试在 R 中实现一个简单的随机森林算法,只是为了了解 R 和随机森林的工作原理,并在测试集中测试准确性。
我的样本数据(五行共 561 行)是:
bulbasaur[1:5,]
Appt_date count no_of_reps PerReCount
1 2016-01-01 2 1 2.000000
2 2016-01-04 174 58 3.000000
3 2016-01-05 206 59 3.491525
4 2016-01-06 203 61 3.327869
5 2016-01-07 236 64 3.687500
我写的代码是:
install.packages("caret")
library(caret)
leaf <- bulbasaur
ctrl = trainControl(method="repeatedcv", number=100, repeats=50, selectionFunction = "oneSE")
in_train = createDataPartition(leaf$PerReCount, p=.75, list=FALSE)
#random forest
trf = train(PerReCount ~ ., data=leaf, method="rf", metric="RMSE",trControl=ctrl, subset = in_train)
#boosting
tgbm = train(PerReCount ~ ., data=leaf, method="gbm", metric="RMSE",
trControl=ctrl, subset = in_train, verbose=FALSE)
resampls = resamples(list(RF = trf, GBM = tgbm))
difValues = diff(resampls)
summary(difValues)
######Using it on test matrix
test = leaf[-in_train,]
test$pred.leaf.rf = predict(trf, test, "raw")
confusionMatrix(test$pred.leaf.rf, test$PerReCount)
但是,我收到以下错误:
Error in confusionMatrix.default(test$pred.leaf.rf, test$PerReCount) :
the data cannot have more levels than the reference
我尝试了一些更改,例如采用 leaf$PerReCount <- as.factors(leaf$PerReCount) 并添加 type = "class" ,但结果非常糟糕,我不想将其从回归更改为分类。如何在不转换为因子的情况下解决它,或者以任何其他方式解决问题,或者在不使用混淆矩阵的情况下获得准确度计数。谢谢
【问题讨论】:
-
混淆矩阵适用于分类器,当您的目标变量是数字时没有意义。现在,
PerReCount变量显然是一个连续的数值变量。您的问题不在于代码,而在于对数据的理解。
标签: r random-forest r-caret confusion-matrix