2013-06-27 47 views
5

當欲以randomForest輸出到新的數據進行分類(或者甚至是原始訓練數據),我收到以下錯誤:新因子水平在培訓數據中不存在

> res.rf5 <- predict(model.rf5, train.rf5) 
Error in predict.randomForest(model.rf5, train.rf5) : 
    New factor levels not present in the training data 

這個錯誤是什麼意思?爲什麼即使當我嘗試預測與之前訓練的數據相同的數據時,也會發生此錯誤?

下面是一個可用於重現錯誤的小例子。

train.rf5 <- structure(
    list(A = structure(c(2L, 1L, 1L, 1L, 1L, 1L, 3L, 1L, 1L, 3L), 
        .Label = c("(-0.1,19.9]", "(19.9,40]", "(80.1,100]"), 
        class = c("ordered", "factor")), 
     B = structure(c(3L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 4L), 
        .Label = c("1", "2", "4", "5"), 
        class = c("ordered", "factor")), 
     C = structure(c(1L, 1L, 2L, 1L, 1L, 2L, 2L, 1L, 1L, 2L), 
        .Label = c("FALSE", "TRUE"), 
        class = "factor")), 
    .Names = c("A", "B", "C"), 
    row.names = c(7L, 8L, 10L, 11L, 13L, 15L, 16L, 17L, 18L, 19L), 
    class = "data.frame") 

#    A B  C 
# 7 (19.9,40] 4 FALSE 
# 8 (-0.1,19.9] 1 FALSE 
# 10 (-0.1,19.9] 1 TRUE 
# 11 (-0.1,19.9] 1 FALSE 
# 13 (-0.1,19.9] 1 FALSE 
# 15 (-0.1,19.9] 1 TRUE 
# 16 (80.1,100] 2 TRUE 
# 17 (-0.1,19.9] 1 FALSE 
# 18 (-0.1,19.9] 1 FALSE 
# 19 (80.1,100] 5 TRUE 

require(randomForest) 
model.rf5 <- randomForest(C ~ ., data = train.rf5) 
res.rf5 <- predict(model.rf5, train.rf5) # Causes error 

我看到所以一些可能相關的問題,但我不認爲他們解決我的問題直接

  1. dropping factor levels in a subsetted data frame in R
  2. Random forest package in R shows error during prediction() if there are new factor levels present in test data. Is there any way to avoid this error?

不同於1),我做的沒有數據中沒有表示的因子水平,而不像2),我的列車中的因子水平和測試數據是相同的。

編輯:附加信息:

sessionInfo() 
R version 3.0.1 (2013-05-16) 
Platform: x86_64-pc-linux-gnu (64-bit) 

locale: 
[1] LC_CTYPE=en_US.UTF-8  LC_NUMERIC=C    
[3] LC_TIME=en_US.UTF-8  LC_COLLATE=en_US.UTF-8  
[5] LC_MONETARY=en_US.UTF-8 LC_MESSAGES=en_US.UTF-8 
[7] LC_PAPER=C     LC_NAME=C     
[9] LC_ADDRESS=C    LC_TELEPHONE=C    
[11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C  

attached base packages: 
[1] stats  graphics grDevices utils  datasets methods base  

other attached packages: 
[1] randomForest_4.6-7 

loaded via a namespace (and not attached): 
[1] tools_3.0.1 
+0

我敢打賭,它與訂購的因素有關。 –

回答

5

我測試了我的猜測,有序因素是問題的根源,並沒有錯誤時,我唯一能做的就是從類中刪除「命令」的結構。在文檔中我沒有看到命令因素是不允許的,但我也沒有看到它們被特別考慮。這可能以前沒有出現過。看起來,訂購會增加額外的複雜性,並且如果您希望對訂單進行會計處理,您可以向RF算法提供as.numeric(.)「分數」。

+0

謝謝迪文,我從2008年看到一個與之相關的舊線索,可能是同一個問題。 https://stat.ethz.ch/pipermail/r-help/2008-April/160833.html – cyang

+0

艾哈。看起來它從安迪的雷達上掉下來了。我希望我的建議使用來自有序因子的得分變量仍然有優點。 –