首页 > 解决方案 > R 包 Ranger 产生与变量“无”相关的错误

问题描述

我正在使用 R 中的 Ranger 包来创建文本分类模型。但是,当其中一个变量为“无”时,我收到以下错误。

Error in intI(j, n = x@Dim[2], dn[[2]], give.dn = FALSE) : 
  index larger than maximal 5002

我还注意到变量“none”没有包含在模型中,即使它在数据集中。

我创建了一个可重现的示例

library(dplyr)
library(Matrix)
library(ranger)

Dataset <- tibble(
                  Y = sample(c(1,0), 1000, replace = T),
                  none = sample(c(1,0), 1000, replace = T), 
                  None = sample(c(1,0), 1000, replace = T),
                  NONE = sample(c(1,0), 1000, replace = T))


trainset <- sample(1:1000, 800)

Dataset2Train <- Dataset[trainset,] %>%
  as.matrix()  %>%
  Matrix(., sparse = TRUE)

Dataset2Test <- Dataset[-trainset,] %>%
  as.matrix()  %>%
  Matrix(., sparse = TRUE)

#Creates model with no messages
rf <- ranger(data = Dataset2Train,
                              dependent.variable.name = "Y", 
                              classification = TRUE)

#Creates model with no messages
rf2 <- ranger(data =  Dataset[trainset,],
                              dependent.variable.name = "Y", 
                              classification = TRUE)

#produces error message
rf3 <- ranger(data =  Dataset[trainset,] %>% setNames(c("Y", "w", "x", "z")),
                              dependent.variable.name = "Y", 
                              classification = TRUE)

#does not include the none variable
rf$forest$independent.variable.names
rf2$forest$independent.variable.names

#crashes Rstudio
predict(rf, data = Dataset[-trainset,],  type = "response", predict.all = T)

#creates a prediction
predict(rf2, data = Dataset[-trainset,],  type = "response", predict.all = T)

真正的数据集是适当稀疏的,并且在我预测时不会崩溃,而是返回问题开头提到的错误消息。

“无”不是 R 中的保留字,那么为什么会发生这种情况?

标签: rmodeling

解决方案


在游侠 0.10.6 中修复。在 CRAN 上进行更改之前,请通过以下方式安装

devtools::install_github("imbs-hl/ranger")

推荐阅读