簡體   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