【问题标题】:Subscript out of bound error in predict function of randomforest随机森林预测函数中的下标越界误差
【发布时间】:2017-12-20 13:04:32
【问题描述】:

我正在使用随机森林进行预测,在 predict(fit, test_feature) 行中,我收到以下错误。有人可以帮我克服这个问题。我对另一个数据集执行了相同的步骤并且没有错误。但我在这里得到错误。

Error: Error in x[, vname, drop = FALSE] : subscript out of bounds

training_index <- createDataPartition(shufflled[,487], p = 0.8, times = 1)
training_index <- unlist(training_index)

train_set <- shufflled[training_index,]
test_set <- shufflled[-training_index,]

accuracies<- c()
k=10
n= floor(nrow(train_set)/k)

for(i in 1:k){
  sub1<- ((i-1)*n+1)
  sub2<- (i*n)
  subset<- sub1:sub2
  train<- train_set[-subset, ]
  test<- train_set[subset, ]
  test_feature<- test[ ,-487]

  True_Label<- as.factor(test[ ,487])
  fit<- randomForest(x= train[ ,-487], y= as.factor(train[ ,487]))

  prediction<- predict(fit, test_feature)  #The error line
  correctlabel<- prediction == True_Label
  t<- table(prediction, True_Label)
}

【问题讨论】:

    标签: r random-forest prediction


    【解决方案1】:

    你的问题不是很清楚,反正我尽量帮你。 首先检查您的数据以查看各种预测变量和结果的水平分布。 您可能会发现您的某些预测变量水平或结果水平非常偏斜,或者某些结果或预测变量水平非常罕见。当我尝试使用经过严格调整的随机森林预测一个非常罕见的结果时,我遇到了这个错误,因此一些预测器级别实际上不在训练数据中。因此,训练数据认为超出范围的测试数据中出现了一个因子水平。

    或者,检查变量的名称。 在调用 predict() 以确保变量名称匹配之前。 没有您的数据文件,很难说出您的第一个示例为何有效。 例如你可以试试:

    names(test) <- names(train)
    

    【讨论】:

    • 我已经测试了我的训练和测试数据集。此外,当我为测试和测试数据运行 unique(lable) 时,我得到相同的标签。我还检查了变量的名称,但仍然是同样的错误
    【解决方案2】:

    几周前我遇到了类似的问题。

    要解决这个问题,你可以这样做:

    df$label <- factor(df$label)
    

    而不是 as.factor 尝试只考虑泛型函数。另外,请先尝试命名您的标签变量。

    【讨论】:

      【解决方案3】:

      在您的训练和验证 x 中是否有相同的列名?

      我收到了同样的错误消息,并通过重命名列名来解决它,因为我的数据是一个矩阵并且它们的列名都是空的,即“”。

      【讨论】:

        【解决方案4】:

        添加表达式

        dimnames(test_feature) <- NULL
        

        之前

        prediction <- predict(fit, test_feature)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-10-20
          • 2014-08-07
          • 2021-07-12
          • 2021-03-21
          • 2019-05-04
          • 2014-09-28
          • 2021-12-22
          相关资源
          最近更新 更多