首页 文章

小鼠r包随机森林实施中的错误

提问于
浏览
2

这里只是示例数据:

# generation of correlated data   
matrixCR <- matrix(NA, nrow = 100, ncol = 100)
diag(matrixCR) <- 1
matrixCR[upper.tri (matrixCR, diag = FALSE)] <- 0.5
matrixCR[lower.tri (matrixCR, diag = FALSE)] <- 0.5
matrixCR[1:10,1:10]
L = chol(matrixCR)# Cholesky decomposition
nvars = dim(L)[1]
nobs = 200
set.seed(123)
rM = t(L) %*% matrix(rnorm(nvars*nobs), nrow=nvars, ncol=nobs)
rM1 <- t(rM)
rownames(rM1) <- paste("S", 1:200, sep = "") 
colnames(rM1) <- paste("M", 1:100, sep = "")
# introducing missing value to the dataset 
N <- 2000*0.05 # 5% random missing values 
inds <- round ( runif(N, 1, length(rM1)) )
rM1[inds] <- NA


# using random forest implemented in mice package 
require(mice)
out.imp <- mice(rM1, m = 5, method ="rf")
imp.data <- complete(out.imp)

我收到以下错误:

iter imp variable
  1   1  M1  M2Error in apply(forest, MARGIN = 1, FUN = function(s) sample(unlist(s),  : 
  dim(X) must have a positive length

我不确定是什么导致了这个问题?

1 回答

  • 1

    正如我在评论中提到的,当 method 设置为randomforest( rf )时, mice 函数每当到达只有一个 NA 值的列时就会抛出错误,但是对于任何其他数量的 NA 值运行正常 .

    我检查了包的作者,这似乎是一个错误 . 在修复之前,您可以为具有单个 NA 值的列选择不同的插补方法 . 例如:

    # Count number of NA in each column
    NAcount = apply(rM1, 2, function(x) sum(is.na(x)))
    
    # Create a vector giving the imputation method to use for each column. 
    # Set it to "rf" unless that column has exactly one NA value.
    method = rep("rf", ncol(rM1))
    method[which(NAcount==1)] = "norm"
    
    # Run the imputation with the new "method" selections
    out.imp <- mice(rM1, m = 5, method = method)
    

    我意识到为了保持一致性,您可能希望对所有列使用相同的插补方法,但如果您使用randomforest方法设置,则上面为您提供了一个选项 .

相关问题