randomForest分类预测器限制

时间:2016-06-30 13:00:18

标签: r random-forest

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

以下脚本创建了一个数据框,以便我们可以预测“职业”。可以理解的是,由于'college_id'变量,在'df'上尝试运行randomForest()时,我得到“无法处理超过53个类别的分类预测变量”错误。

但是,当我将我的数据集修剪为仅包含前40个大学ID时,我得到了相同的错误。我是否遗漏了一些保留所有类别的基本数据框架概念,即使现在只有40个数据框填充在'df2'数据框中?我可以使用什么解决方法选项?

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)

1 个答案:

答案 0 :(得分:1)

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

df2$college_id <- factor(df2$college_id)
相关问题