【问题标题】:R Random Forest prediction not workingR随机森林预测不起作用
【发布时间】:2014-08-17 23:35:42
【问题描述】:

我是 R 中随机森林的新手,我正在尝试做出预测。我使用以下代码构建了一个随机森林模型,效果很好

library(randomForest)
RF_model = randomForest(trainrows[,col_truth]~.
                    ,data = trainrows[,cols_to_use]
                    ,ntree=100
                    ,do.trace=T)

如果我打印出 RF_model,我会得到以下输出

Call:
 randomForest(formula = trainrows[, col_truth] ~ ., data = trainrows[,      cols_to_use], ntree = 100, do.trace = T) 
               Type of random forest: classification
                     Number of trees: 100
No. of variables tried at each split: 4

        OOB estimate of  error rate: 19.23%
Confusion matrix:
     0    1 class.error
0 7116 1640   0.1873001
1 1725 7015   0.1973684

然后,当我尝试使用模型进行预测时,出现以下错误

> predict(RF_model)
Error in 1:dim(data)[1] : argument of length 0

我尝试向 predict 方法提供数据,但我得到了同样的错误。有谁知道发生了什么以及如何解决它?

编辑

为了提供更多数据,我尝试将随机森林与鸢尾花数据集结合使用。

rf = randomForest(iris[,1]~., data=iris[,c(1, 2)], ntree=100)
predict(rf)
Error in 1:dim(data)[1] : argument of length 0

我认为这与我的数据无关,而是我的 R 版本有问题。有什么想法吗?

【问题讨论】:

  • 请包含示例数据以制作您的示例reproducible。随意使用内置数据集,但除非我们可以运行相同的代码并得到相同的错误,否则很难提供帮助。
  • rf = randomForest(iris[,1]~., data=iris[,c(1, 2)], ntree=100) ; predict(rf) 工作正常,因此此问题可能特定于您的数据集。请附上一个可重现的例子。
  • 如果我不得不猜测,问题可能与您的公式规范有关,它不遵循 R 中指定公式的任何约定。公式包含列的名称。不要将子集混合到您的公式中。永远。
  • 我刚刚调整了我的问题,显示更多数据

标签: r prediction random-forest


【解决方案1】:

当您使用预测函数时,您正在尝试预测测试集的结果或标签。

rf_predict <- predict(RF_model, test_set)

您可以创建混淆矩阵以通过使用表函数来比较随机林的准确性

table(observed, rf_predict)

注意:观察到的是测试集的正确标签

【讨论】:

    猜你喜欢
    • 2019-05-04
    • 2019-01-22
    • 2014-08-07
    • 2019-02-19
    • 2021-03-21
    • 2019-07-10
    • 2021-06-23
    • 2021-07-12
    相关资源
    最近更新 更多