随机森林——R中的随机森林报告对象中的缺失值,但向量中没有NAs



我试图在R中使用randomForest包,但我遇到了一个问题,R告诉我在响应向量中缺少数据。

> rf_blackcomb_earlyGame <- randomForest(max_cohort ~ ., data=blackcomb_earlyGame[-c(1,2), ])
Error in na.fail.default(list(max_cohort = c(47, 25, 20, 37, 1, 0, 23,  : 
missing values in object

指定的错误足够清楚。我以前遇到过这种情况,过去确实有丢失数据,但这次没有任何丢失数据。

> class(blackcomb_earlyGame$max_cohort)
[1] "numeric"
> which(is.na(blackcomb_earlyGame$max_cohort))
integer(0)

我试过用na。我想看看这是否有帮助,但是我得到了以下错误:

Error in na.roughfix.data.frame(list(max_cohort = c(47, 25, 20, 37, 1,  : 
na.roughfix only works for numeric or factor

我检查了每个向量以确保它们都不包含任何NAs,它们都不包含。

有人有什么建议吗?

randomForest可能由于数据的几种不同类型的问题而失败。缺少值(NA), NaN, Inf-Inf的值,以及没有转换为因子的字符类型都将失败,并出现各种错误消息。

我们可以在下面看到由这些问题产生的错误消息的一些示例:

my.df <- data.frame(a = 1:26, b=letters, c=(1:26)+rnorm(26))
rf <- randomForest(a ~ ., data=my.df)
# this works without issues, because b=letters is cast into a factor variable by default
my.df$d <- LETTERS    # Now we add a character column
rf <- randomForest(a ~ ., data=my.df)
# Error in randomForest.default(m, y, ...) : 
#   NA/NaN/Inf in foreign function call (arg 1)
# In addition: Warning message:
#   In data.matrix(x) : NAs introduced by coercion
rf <- randomForest(d ~ ., data=my.df)
# Error in y - ymean : non-numeric argument to binary operator
# In addition: Warning message:
#   In mean.default(y) : argument is not numeric or logical: returning NA
my.df$d <- c(NA, rnorm(25))
rf <- randomForest(a ~ ., data=my.df)
rf <- randomForest(d ~ ., data=my.df)
# Error in na.fail.default(list(a = 1:26, b = 1:26, c = c(3.14586293058335,  : 
#   missing values in object
my.df$d <- c(Inf, rnorm(25))
rf <- randomForest(a ~ ., data=my.df)
rf <- randomForest(d ~ ., data=my.df)
# Error in randomForest.default(m, y, ...) : 
#   NA/NaN/Inf in foreign function call (arg 1)

有趣的是,您收到的错误消息是由数据帧中具有character类型(请参阅注释)引起的,这是我在NA的数字列中看到的错误。这表明可能存在(1)不同版本randomForest的错误差异,或者(2)错误信息以更复杂的方式依赖于数据结构。无论哪种方式,对于任何收到此类错误的人来说,建议都是查找上面列出的数据的所有可能问题,以便追踪原因。

也许有Inf-Inf值?

is.na(c(1, NA, Inf, NaN, -Inf))
#[1] FALSE  TRUE FALSE  TRUE FALSE
is.finite(c(1, NA, Inf, NaN, -Inf))
#[1]  TRUE FALSE FALSE FALSE FALSE

最新更新