我在没有找到解决方案的情况下进行了广泛的研究。我按如下方式清理了我的数据集:
library("raster")
impute.mean <- function(x) replace(x, is.na(x) | is.nan(x) | is.infinite(x) ,
mean(x, na.rm = TRUE))
losses <- apply(losses, 2, impute.mean)
colSums(is.na(losses))
isinf <- function(x) (NA <- is.infinite(x))
infout <- apply(losses, 2, is.infinite)
colSums(infout)
isnan <- function(x) (NA <- is.nan(x))
nanout <- apply(losses, 2, is.nan)
colSums(nanout)
问题出现了运行预测算法:
options(warn=2)
p <- predict(default.rf, losses, type="prob", inf.rm = TRUE, na.rm=TRUE, nan.rm=TRUE)
所有的研究都说它应该是数据中的NA或Inf或NaN,但我找不到。我正在将数据和randomForest摘要提供给[删除]进行调查 回溯并没有透露太多(对我而言):
4: .C("classForest", mdim = as.integer(mdim), ntest = as.integer(ntest),
nclass = as.integer(object$forest$nclass), maxcat = as.integer(maxcat),
nrnodes = as.integer(nrnodes), jbt = as.integer(ntree), xts = as.double(x),
xbestsplit = as.double(object$forest$xbestsplit), pid = object$forest$pid,
cutoff = as.double(cutoff), countts = as.double(countts),
treemap = as.integer(aperm(object$forest$treemap, c(2, 1,
3))), nodestatus = as.integer(object$forest$nodestatus),
cat = as.integer(object$forest$ncat), nodepred = as.integer(object$forest$nodepred),
treepred = as.integer(treepred), jet = as.integer(numeric(ntest)),
bestvar = as.integer(object$forest$bestvar), nodexts = as.integer(nodexts),
ndbigtree = as.integer(object$forest$ndbigtree), predict.all = as.integer(predict.all),
prox = as.integer(proximity), proxmatrix = as.double(proxmatrix),
nodes = as.integer(nodes), DUP = FALSE, PACKAGE = "randomForest")
3: predict.randomForest(default.rf, losses, type = "prob", inf.rm = TRUE,
na.rm = TRUE, nan.rm = TRUE)
2: predict(default.rf, losses, type = "prob", inf.rm = TRUE, na.rm = TRUE,
nan.rm = TRUE)
1: predict(default.rf, losses, type = "prob", inf.rm = TRUE, na.rm = TRUE,
nan.rm = TRUE)
答案 0 :(得分:15)
您的代码不是完全可重现的(没有运行实际的randomForest
算法)但您不用列向量替换Inf
值。这是因为na.rm = TRUE
函数中对mean()
的调用中的impute.mean
参数与其说的完全相同 - 删除了NA
个值(而不是Inf
个值)。
您可以通过以下方式看到这一点:
impute.mean <- function(x) replace(x, is.na(x) | is.nan(x) | is.infinite(x), mean(x, na.rm = TRUE))
losses <- apply(losses, 2, impute.mean)
sum( apply( losses, 2, function(.) sum(is.infinite(.))) )
# [1] 696
要摆脱无限值,请使用:
impute.mean <- function(x) replace(x, is.na(x) | is.nan(x) | is.infinite(x), mean(x[!is.na(x) & !is.nan(x) & !is.infinite(x)]))
losses <- apply(losses, 2, impute.mean)
sum(apply( losses, 2, function(.) sum(is.infinite(.)) ))
# [1] 0
答案 1 :(得分:8)
错误消息的一个原因:
外部函数调用中的NA / NaN / Inf(arg X)
训练randomForest时,data.frame中有character
个类变量。如果它附带警告:
强制引入的NAs
检查以确保所有字符变量都已转换为因子。
示例强>
set.seed(1)
dat <- data.frame(
a = runif(100),
b = rpois(100, 10),
c = rep(c("a","b"), 100),
stringsAsFactors = FALSE
)
library(randomForest)
randomForest(a ~ ., data = dat)
收率:
randomForest.default(m,y,...)出错:外国人的NA / NaN / Inf 函数调用(arg 1)另外:警告消息:在data.matrix(x)中 :强制引入的NAs
但是删除stringsAsFactors = FALSE
参数并运行。