【问题标题】:Missing object in randomForest model when predicting on test dataset在测试数据集上进行预测时,randomForest 模型中缺少对象
【发布时间】:2017-04-27 15:40:49
【问题描述】:

对不起,如果已经问过了,但我在半小时内找不到它,所以如果你能指出一些方向,我将不胜感激。

我在模型中缺少对象时遇到了麻烦,而我在构建模型时实际上并没有使用这个对象,它只是存在于数据集中。 (如下例所示)。

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

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

我希望实现的是使用我已经构建的模型,因为在不丢失变量的情况下重做它们会很昂贵。

感谢您的建议!

【问题讨论】:

  • 我想到的最佳解决方案是通过这种方式从模型中的输入数据集中删除列:rf_model &lt;- randomForest(Species ~ . - Sepal.Length, data = train[,-which(colnames(data) %in% c('Sepal.Length'))] 但这需要在训练模型时而不是之后指定:/

标签: r random-forest


【解决方案1】:

因为您的模型已经建成。在运行模型之前,您需要将缺失的列添加回测试集。只需添加值为 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 

【讨论】:

  • 您好伊恩,感谢您的回答,我按照您建议的方式进行了操作,但我希望会有更优雅的解决方案。因为当我在 gbm 模型中使用完全相同的公式时,我没有得到任何错误,所以我认为可以调整模型的某些设置以忽略丢失的列。
  • 我通过展示如何获取丢失的列并将它们设置为 0 来使其更加通用。
  • 如果两天后没有更好的答案,我会将您的答案标记为正确并继续:)
  • 我也对此感到惊讶,在 randomForest 中寻找被忽略的特性的实现显然有些奇怪。它可能值得运行或至少提交一个错误。
猜你喜欢
  • 2016-01-02
  • 2019-12-25
  • 2021-12-23
  • 2020-12-07
  • 2020-02-13
  • 2020-08-29
  • 1970-01-01
  • 2019-01-28
  • 2017-01-11
相关资源
最近更新 更多