randomForest 分类预测变量限制

randomForest Categorical Predictor Limits

我理解并赞赏 R 的 randomForest 函数只能处理少于 54 个类别的分类预测变量。但是,当我 trim 我的分类预测器减少到少于 54 个类别时,我仍然得到错误。我在 Whosebug 上看到的关于分类预测变量限制的唯一问题是如何绕过这个类别限制,但我试图 trim 我的类别数量以遵循函数的限制,但我仍然遇到错误。

以下脚本创建了一个数据框,因此我们可以预测 'profession'。可以理解的是,由于 'college_id' 变量,我在 'df' 上尝试 运行 randomForest() 时出现 "Can not handle categorical predictors with more than 53 categories" 错误。

但是当我 trim 我的数据集只包含前 40 个大学 ID 时,我得到了同样的错误。我是否缺少一些保留所有类别的基本数据框概念,即使 'df2' 数据框中现在只填充了 40 个类别?我可以使用什么解决方法?

library(dplyr)
library(randomForest)

# create data frame
df <- data.frame(profession = sample(c("accountant", "lawyer", "dentist"), 10000, replace = TRUE),
             zip = sample(c("32801", "32807", "32827", "32828"), 10000, replace = TRUE),
             salary = sample(c(50000:150000), 10000, replace = TRUE),
             college_id = as.factor(c(sample(c(1001:1040), 9200, replace = TRUE),
                                      sample(c(1050:9999), 800, replace = TRUE))))


# results in error, as expected
rfm <- randomForest(profession ~ ., data = df)


# arrange college_ids by count and retain the top 40 in the 'df' data frame
sdf <- df %>% 
  dplyr::group_by(college_id) %>% 
  dplyr::summarise(n = n()) %>% 
  dplyr::arrange(desc(n))
sdf <- sdf[1:40, ]
df2 <- dplyr::inner_join(df, sdf, by = "college_id")
df2$n <- NULL


# confirm that df2 only contains 40 categories of 'college_id'
nrow(df2[which(!duplicated(df2$college_id)), ])


# THIS IS WHAT I WANT TO RUN, BUT STILL RESULTS IN ERROR
rfm2 <- randomForest(profession ~ ., data = df2)

我认为您的变量中仍然包含所有因子水平。在再次适应森林之前尝试添加此行:

df2$college_id <- factor(df2$college_id)