R 中的随机森林:训练数据中不存在新的因子水平

Random Forest in R: New factor levels not present in the training data

好的,那么另一个与泰坦尼克号竞赛相关的新手问题:

我正在尝试 运行 对我的测试数据进行随机森林预测。我所有的工作都是在组合测试和训练数据上完成的。

我现在已经将 2 拆分为测试数据和训练数据

我有以下代码:

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) 我可以看到 2 个不再匹配的因素

Trainingdata      
$ Parch            : Factor w/ 7 levels 

Testdata
$ Parch            : Factor w/ 8

Trainingdata
$ FamilyID2        : Factor w/ 22 

Testdata
$ FamilyID2        : Factor w/ 18

是不是这些差异导致了我的错误发生?如果是这样,我该如何解决?

非常感谢

附加信息: 我已经从 RandomForest 创建行中删除了 Parch 和 FamilyID2,代码现在可以工作了,所以肯定是这 2 个变量导致了级别不匹配的问题。

各位新手,这几天就在玩泰坦尼克号。我认为将 Parch 变量作为一个因素是没有意义的,所以也许将其设为数字​​,这可能会解决问题:

火车$Parch <- as.numeric(火车$Parch)

否则,测试数据有2个obs,Parch的值为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