簡體   English   中英

下標超出隨機誤差的隨機森林預測函數

[英]Subscript out of bound error in predict function of randomforest

我正在使用隨機森林進行預測,在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)
}

您的訓練和驗證x中是否有相同的列名?

我有相同的錯誤消息,並通過重命名列名來解決它,因為我的數據是一個矩陣,並且它們的名稱全為空,即“”。

您的問題不是很清楚,無論如何我會盡力幫助您。 首先,檢查數據以查看各種預測變量和結果的水平分布。 您可能會發現某些預測因子水平或結果水平高度偏斜,或者某些預測因子水平或結果水平非常罕見。 當我試圖通過大量調整的隨機森林來預測非常罕見的結果時,我遇到了該錯誤,因此某些預測因子水平實際上不在訓練數據中。 因此,因子水平出現在訓練數據認為超出范圍的測試數據中。

或者,檢查變量的名稱。 在調用predict()之前,請確保變量名稱匹配。 沒有數據文件,很難說出第一個示例為何起作用。 例如,您可以嘗試:

names(test) <- names(train)

幾周前我也遇到過類似的問題。

要解決該問題,您可以執行以下操作:

df$label <- factor(df$label)

代替as.factor嘗試僅使用因數泛型函數。 另外,請嘗試先命名標簽變量。

添加表達式

dimnames(test_feature) <- NULL

之前

prediction <- predict(fit, test_feature)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM