【问题标题】:randomForest Categorical Predictor LimitsrandomForest 分类预测变量限制
【发布时间】:2016-06-30 13:00:18
【问题描述】:

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

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

但是,当我将数据集修剪为仅包含前 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)

【问题讨论】:

    标签: r random-forest


    【解决方案1】:

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

    df2$college_id <- factor(df2$college_id)
    

    【讨论】:

    • 就是这样...谢谢!
    猜你喜欢
    • 2014-07-06
    • 2019-04-27
    • 2022-06-28
    • 2016-12-07
    • 2014-09-27
    • 2019-02-26
    • 2020-08-10
    • 2015-05-24
    • 1970-01-01
    相关资源
    最近更新 更多