我想使用随机森林方法来估算缺失值。我读过一些声称MICE随机森林比参数鼠标表现更好的论文。
在我的情况下,我已经为默认鼠标运行了一个模型,并得到了结果并与它们一起玩。但是,当我有方法随机森林的选项,我得到一个错误,我不知道为什么。我已经看到一些与随机森林和老鼠的错误有关的问题,但那些不是我的情况。我的变量不止一个NA。
imp <- mice(data1, m=70, pred=quickpred(data1), method="pmm", seed=71152, printFlag=TRUE)
impRF <- mice(data1, m=70, pred=quickpred(data1), method="rf", seed=71152, printFlag=TRUE)
iter imp variable
1 1 Vac
Error in if (n == 0) stop("data (x) has 0 rows") : argument is of length zero
任何人都知道我为什么会收到这个错误?
修改
我尝试将所有变量更改为数字而不是使用虚拟变量,并返回相同的错误和一些警告()
impRF <- mice(data, m=70, pred=quickpred(data), method="rf", seed=71152, printFlag=TRUE)
iter imp variable
1 1 Vac CliForm
Error in if (n == 0) stop("data (x) has 0 rows") : argument is of length zero
In addition: There were 50 or more warnings (use warnings() to see the first 50)
50: In randomForest.default(x = xobs, y = yobs, ntree = 1, ... :
The response has five or fewer unique values. Are you sure you want to do regression?
EDIT1
我只尝试了5个插补和一个较小的数据子集,只有2000行并且出现了一些不同的错误:
> imp <- mice(data2, m=5, pred=quickpred(data2), method="rf", seed=71152, printFlag=TRUE)
iter imp variable
1 1 Vac Radio Origin Job Alc Smk Drugs Prison Commu Hmless Symp
Error in randomForest.default(x = xobs, y = yobs, ntree = 1, ...) : NAs in foreign
function call (arg 11)
In addition: Warning messages:
1: In randomForest.default(x = xobs, y = yobs, ntree = 1, ...) : invalid mtry: reset to within valid range
2: In max(ncat) : no non-missing arguments to max; returning -Inf
3: In randomForest.default(x = xobs, y = yobs, ntree = 1, ...) : NAs introduced by coercion
答案 0 :(得分:2)
当我只有一个完全观察到的变量时,我也遇到了这个错误,我猜这也是你案例的原因。我的同事Anoop Shah向我提供了一个解决方案(下图),van Buuren教授(老鼠的作者)表示他将把它包含在下一次更新包中。
在R中输入以下内容,以便重新定义rf impute功能。 fixInNamespace(“mice.impute.rf”,“mice”)
要粘贴的已更正功能是:
mice.impute.rf <- function (y, ry, x, ntree = 100, ...){
ntree <- max(1, ntree)
xobs <- as.matrix(x[ry, ])
xmis <- as.matrix(x[!ry, ])
yobs <- y[ry]
onetree <- function(xobs, xmis, yobs, ...) {
fit <- randomForest(x = xobs, y = yobs, ntree = 1, ...)
leafnr <- predict(object = fit, newdata = xobs, nodes = TRUE)
nodes <- predict(object = fit, newdata = xmis, nodes = TRUE)
donor <- lapply(nodes, function(s) yobs[leafnr == s])
return(donor)
}
forest <- sapply(1:ntree, FUN = function(s) onetree(xobs,
xmis, yobs, ...))
impute <- apply(forest, MARGIN = 1, FUN = function(s) sample(unlist(s),
1))
return(impute)
}