【发布时间】:2015-07-17 19:53:51
【问题描述】:
在 64 位 Linux 机器上使用带有插入符号 6.0-41 和 randomForest 4.6-10 的 R 3.2.0。
尝试对使用公式通过 caret 包中的 train() 函数训练的 randomForest 对象使用 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 字段中的(因子)变量的名称。
插入符号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 -
正如所指出的,您没有在示例中定义
dataTrain,这意味着问题不是reproducible。如果我们无法运行代码并获得与您相同的结果,那么帮助您并不容易。 -
我的错,
dataTrain应该是imp85,我编辑了原始问题中的代码。我还在调用中删除了选项data=imp85,其中明确提到了x和y,因为它没有用处。
标签: r formula random-forest r-caret predict