繁体   English   中英

使用一个变量运行随机森林算法

[英]Running random forest algorithm with one variable

我通过使用一个预测器来使用随机森林算法。

  RF_MODEL <- randomForest(x=Data_[,my_preds], y=as.factor(Data_$P_A), data=Data_, ntree=1000, importance =T)

但我收到了这个错误信息:

Error in if (n == 0) stop("data (x) has 0 rows") : 
 l'argument est de longueur nulle

这是否意味着我们不能将 RF 与一个变量一起使用?

这里的问题是,当您在randomForest中指定x时, x应该是“数据框或预测变量矩阵,或描述要拟合的 model 的公式”。 您正在指定一个向量Data_[, my_preds]我假设my_preds是一个描述列名的字符串。 指定数据框的一列时,默认情况下会得到一个向量。

您可以使用drop = FALSE来确保x保留为数据框列。

RF_MODEL <- randomForest(x = Data_[,my_preds, drop = FALSE], 
                         y = as.factor(Data_$P_A), 
                         data = Data_, 
                         ntree = 1000, importance = TRUE)

我们可以演示使用iris数据集。

library(randomForest)

randomForest(x = iris[, "Sepal.Width"], y = iris$Species, data = iris)

Error in if (n == 0) stop("data (x) has 0 rows") : 
  argument is of length zero

使用 drop = FALSE:

randomForest(x = iris[, "Sepal.Width", drop = FALSE], y = iris$Species, data = iris)

Call:
 randomForest(x = iris[, "Sepal.Width", drop = FALSE], y = iris$Species,      data = iris) 
               Type of random forest: classification
                     Number of trees: 500
No. of variables tried at each split: 1

        OOB estimate of  error rate: 52.67%
Confusion matrix:
           setosa versicolor virginica class.error
setosa         31          2        17        0.38
versicolor      3         20        27        0.60
virginica      17         13        20        0.60

您也可以考虑使用公式来避免此问题:

randomForest(Species ~ Sepal.Width, data = iris)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM