我在randomForest的R包中遇到了一个错误,在我使用Caret将数据拆分成训练和测试之后,当我去预测时,我遇到了错误:
Error in predict.randomForest(randomForestFit, type = "response", newdata =testing$GEN)
:number of variables in newdata does not match that in the training data
我从完全相同的文件中拆分了训练和测试中的文件。任何数据中都没有N/A或缺失值。下面是我的完整代码,但我不认为其中有错误。我不知道为什么会发生这个错误。任何想法都将不胜感激!
library(caret)
require(foreign)
set.seed(825)
data <- read.spss("C:/MODEL_SAMPLE.sav",use.value.labels=TRUE, to.data.frame = TRUE)
inTraining <- createDataPartition(data$GEN, p = 0.75, list = FALSE)
training <- data[inTraining, ]
testing <- data[-inTraining, ]
library(randomForest)
library(foreach)
start.time <- Sys.time()
randomForestFit <- foreach(ntree=rep(63, 8), .combine=combine, .packages='randomForest')
%dopar% randomForest(training[-201],
training$GEN,
mtry = 40,
ntree=ntree,
verbose = TRUE,
importance = TRUE,
keep.forest=TRUE,
do.trace = TRUE)
randomForestFit
predict = predict(randomForestFit, type="response", newdata=testing$GEN)
stopCluster(cl)
end.time <- Sys.time()
time.taken <- end.time - start.time
time.taken
发布于 2014-07-02 08:24:39
没有数据,任何人都很难确切地说出问题所在。
三点建议:
首先,检查SPSS文件中是否有数据中的杂乱字符。
其次,检查read.spss中的选项是否正确设置: reencode = NA,use.missings =to.data.frame。您可以使用后一个选项来指定要转换为NA的非数字字符。
第三,使用str(df),useNA=(df,“如果有”),并确保包括响应在内的因子变量实际上是因子。将as.numeric(as.character())应用于数据框中的数值数据,如果数据框中有类似VALUE!,#NA这样的表达式,则会生成NA值。
您也可以从SPSS导出到csv,然后再次执行上述操作。
发布于 2020-05-17 09:38:03
密钥如下所示
:number of variables in newdata does not match that in the training data
因此,我猜测训练数据和测试数据是不同的,特别是列名。也许它会在这条线上断掉?
inTraining <- createDataPartition(data$GEN, p = 0.75, list = FALSE)
为了更好地理解这个问题,您可能需要发布3行训练和测试数据集(带有列名!)。
我希望这能帮到你!
https://stackoverflow.com/questions/24493556
复制