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個變量與級別不匹配造成的問題。
如果測試數據中存在新的因子級別,[R中的隨機森林包可能在預測()期間顯示錯誤。有什麼辦法可以避免這個錯誤?](https://stackoverflow.com/questions/17059432/random-forest-package-in-r-shows-error-during-prediction-if-there-are-new-fact ) – RUser
我看過那篇文章,並試圖實現解決方案,但錯誤是一樣的。 –
如果運行'testdata < - factor(testdata,levels = levels(trainingdata))'''predict()'函數''之前,不應該有任何問題。 – Prem