在一台64位Linux机器上,使用 R 3.2.0 版本、caret 6.0-41 版本和 randomForest 4.6-10 版本。当尝试对使用公式训练的randomForest对象应用caret包中的train()函数进行预测时,使用predict()方法会返回错误。但是,如果使用randomForest()进行训练并且使用x=和y=而不是公式,则一切都能够平稳运行。
以下是一个可工作的示例:
library(randomForest)
library(caret)
data(imports85)
imp85 <- imports85[, c("stroke", "price", "fuelType", "numOfDoors")]
imp85 <- imp85[complete.cases(imp85), ]
imp85[] <- lapply(imp85, function(x) if (is.factor(x)) x[,drop=TRUE] else x) ## Drop empty levels for factors.
modRf1 <- randomForest(numOfDoors~., data=imp85)
caretRf <- train( numOfDoors~., data=imp85, method = "rf" )
modRf2 <- caretRf$finalModel
modRf3 <- randomForest(x=imp85[,c("stroke", "price", "fuelType")], y=imp85[, "numOfDoors"])
caretRf <- train(x=imp85[,c("stroke", "price", "fuelType")], y=imp85[, "numOfDoors"], method = "rf")
modRf4 <- caretRf$finalModel
p1 <- predict(modRf1, newdata=imp85)
p2 <- predict(modRf2, newdata=imp85)
p3 <- predict(modRf3, newdata=imp85)
p4 <- predict(modRf4, newdata=imp85)
在最后4行中,只有第二行p2 <- predict(modRf2, newdata=imp85)
返回以下错误:
Error in predict.randomForest(modRf2, newdata = imp85) :
variables in the training data missing in newdata
看起来这个错误的原因是predict.randomForest
方法使用rownames(object$importance)
来确定用于训练随机森林object
的变量名称。当查看
rownames(modRf1$importance)
rownames(modRf2$importance)
rownames(modRf3$importance)
rownames(modRf4$importance)
我们看到:
[1] "stroke" "price" "fuelType"
[1] "stroke" "price" "fuelTypegas"
[1] "stroke" "price" "fuelType"
[1] "stroke" "price" "fuelType"
使用 caret
中的 train()
函数并带有公式,会导致 randomForest
对象的 importance
字段中的(因子)变量名称发生更改。
这是否意味着公式版本和非公式版本的 caret train()
函数之间存在不一致性?还是我漏掉了什么?
modRf3 <- randomForest(x=dataTrain[,c("stroke", "price", "fuelType")], y=dataTrain[, "numOfDoors"], data=imp85) Error in randomForest(x = dataTrain[, c("stroke", "price", "fuelType")], : object 'dataTrain' not found
- user3710546dataTrain
,这意味着问题无法重现。如果我们无法运行代码并获得与您相同的结果,那么帮助您并不容易。 - MrFlickdataTrain
应该是imp85
,我在原始问题的代码中进行了编辑。同时,在显式地提到x
和y
的调用中,我删除了选项data=imp85
,因为它没有用处。 - Adrien Combaz