2017-07-14 67 views
1

OK不存在,因此與泰坦尼克號比賽的另一個新手問題:隨機森林在R:新因子水平在訓練數據

我試圖運行對我的測試數據的隨機森林預測。我所有的工作都是在測試和訓練數據結合的基礎上完成的。

我現在已經拆了2 TESTDATA和trainingdata

我有以下代碼:

trainingdata <- droplevels(data.combined[1:891,]) 
testdata <- droplevels(data.combined[892:1309,]) 

fitRF <- randomForest(as.factor(Survived) ~ Pclass + Sex + Age + SibSp 
+ Parch + Fare + Embarked 
        + new.title + family.size + FamilyID2, 
        data=trainingdata, 
        importance =T, 
        ntree=2000) 

varImpPlot(fitRF) 

#All works up to this point 


Prediction <- predict(fitRF, testdata) 
#This line above generates error 
submit <- data.frame(PassengerID = data.combined$PassengerId, Survived 
= Prediction) 
write.csv(submit, file="14072017_1_RF", row.names = F) 

當我運行的預測線,我得到以下錯誤:

> Prediction <- predict(fitRF, testdata) 
Error in predict.randomForest(fitRF, testdata) : 
    New factor levels not present in the training data 

當我運行 str(testdata)和str(訓練數據)時,我可以看到不再匹配的兩個因素

Trainingdata  
$ Parch   : Factor w/ 7 levels 

Testdata 
$ Parch   : Factor w/ 8 

Trainingdata 
$ FamilyID2  : Factor w/ 22 

Testdata 
$ FamilyID2  : Factor w/ 18 

難道是這些差異導致我的錯誤發生?如果是這樣,我該如何解決這個問題?

非常感謝

附加信息: 我從隨機森林創作行取出烘乾和FamilyID2,和現在的代碼工作的,所以它肯定是那些2個變量與級別不匹配造成的問題。

+0

如果測試數據中存在新的因子級別,[R中的隨機森林包可能在預測()期間顯示錯誤。有什麼辦法可以避免這個錯誤?](https://stackoverflow.com/questions/17059432/random-forest-package-in-r-shows-error-during-prediction-if-there-are-new-fact ) – RUser

+0

我看過那篇文章,並試圖實現解決方案,但錯誤是一樣的。 –

+0

如果運行'testdata < - factor(testdata,levels = levels(trainingdata))'''predict()'函數''之前,不應該有任何問題。 – Prem

回答

1

這裏是我的新手,我剛剛在泰坦尼克號附近玩耍。我認爲這doesn't意義有PARCH變量的一個因素,所以也許使它數字和可能解決的問題:

火車$ PARCH < - as.numeric(火車$ PARCH)

否則,測試數據有2個OBS與9烘乾的價值,這是不存在的訓練數據:

> table(train$Parch) 

0 1 2 3 4 5 6 
678 118 80 5 4 5 1 

> table(test$Parch) 

0 1 2 3 4 5 6 9 
324 52 33 3 2 1 1 2 
> 

另外,如果你需要的變量是一個因素,那麼你可以添加另一等級:

train$Parch <- as.factor(train$Parch) # in my data, Parch is type int 
train$Parch 
levels(train$Parch) <- c(levels(train$Parch), "9") 
train$Parch # now Parch has 7 levels 
table(train$Parch) # level 9 is empty