如果已经有人问了,很抱歉,但我在半小时内找不到,所以如果你能给我指点方向,我会很感激的。
在模型中缺少对象时我遇到了问题,虽然我在构建模型时没有实际使用这个对象,但它只是存在于dataset中。(如下面的示例所示)。
这是一个问题,因为我已经训练了一些射频模型,我正在将模型加载到环境中,并且我正在重复使用它们。测试数据集不包含在构建模型的dataset中存在的一些变量,但它们不用于模型本身!
library(randomForest)
data(iris)
smp_size <- floor(0.75*nrow(iris))
set.seed(123)
train_ind <- sample(seq_len(nrow(iris)), size = smp_size)
train <- iris[train_ind, ]
test <- iris[-train_ind, ]
test$Sepal.Length <- NULL # for the sake of example I drop this column
rf_model <- randomForest(Species ~ . - Sepal.Length, # I don't use the column in training model
data = train)
rf_prediction <- predict(rf_model, newdata = test)当我试图预测测试数据集时,我会得到一个错误:
Error in eval(expr, envir, enclos) : object 'Sepal.Length' not found我希望实现的是,使用我已经构建的模型,因为在不丢失变量的情况下重做将花费很大的代价。
谢谢你的建议!
发布于 2017-04-27 16:23:16
因为你的模型已经造好了。在运行模型之前,您需要将缺少的列添加回测试集。只需添加值为0的缺失列,如下所示。
library(randomForest)
library(dplyr)
data(iris)
smp_size <- floor(0.75*nrow(iris))
set.seed(123)
train_ind <- sample(seq_len(nrow(iris)), size = smp_size)
train <- iris[train_ind, ]
test <- iris[-train_ind, ]
test$Sepal.Length <- NULL
rf_model <- randomForest(Species ~ . - Sepal.Length,
data = train)
# adding the missing column to your test set.
missingColumns <- setdiff(colnames(train),colnames(test))
test[,missingColumns] <- 0
rf_prediction <- predict(rf_model, newdata = test)
rf_prediction
#showing this produce the same results
train2 <- iris[train_ind, ]
test2 <- iris[-train_ind, ]
test2$Sepal.Length <- NULL
train2$Sepal.Length <- NULL
rf_model2 <- randomForest(Species ~ .,
data = train2)
rf_prediction2 <- predict(rf_model2, newdata = test2)
rf_prediction2 == rf_prediction https://stackoverflow.com/questions/43662257
复制相似问题