首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在测试数据集上进行预测时randomForest模型中缺少对象

在测试数据集上进行预测时randomForest模型中缺少对象
EN

Stack Overflow用户
提问于 2017-04-27 15:40:49
回答 1查看 438关注 0票数 0

如果已经有人问了,很抱歉,但我在半小时内找不到,所以如果你能给我指点方向,我会很感激的。

在模型中缺少对象时我遇到了问题,虽然我在构建模型时没有实际使用这个对象,但它只是存在于dataset中。(如下面的示例所示)。

这是一个问题,因为我已经训练了一些射频模型,我正在将模型加载到环境中,并且我正在重复使用它们。测试数据集不包含在构建模型的dataset中存在的一些变量,但它们不用于模型本身!

代码语言:javascript
复制
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)

当我试图预测测试数据集时,我会得到一个错误:

代码语言:javascript
复制
Error in eval(expr, envir, enclos) : object 'Sepal.Length' not found

我希望实现的是,使用我已经构建的模型,因为在不丢失变量的情况下重做将花费很大的代价。

谢谢你的建议!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-04-27 16:23:16

因为你的模型已经造好了。在运行模型之前,您需要将缺少的列添加回测试集。只需添加值为0的缺失列,如下所示。

代码语言:javascript
复制
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 
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43662257

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档