由于“类别过多”,R中出现RandomForest时出错,

问题描述 投票:-1回答:1

我正在尝试在R中训练RF模型,但是当我尝试定义模型时:

rf <- randomForest(labs ~ .,data=as.matrix(dd.train))

它给我错误:

Error in randomForest.default(m, y, ...) :
  Can not handle categorical predictors with more than 53 categories.

知道是什么吗?

[不,在您说“您的分类变量超过53个类别”之前。不,除labs以外的所有变量都是数字。

Tim Biegeleisen:阅读我的问题的最后一行,您将看到为什么与您要链接的内容不一样!

r random-forest
1个回答
1
投票

已编辑以解决OP中的后续问题

我相信在这种情况下使用as.matrix会隐式创建因子。也不需要此软件包。您可以将其保留为数据帧,但需要通过使用droplevels(或类似方法)确保删除任何未使用的因子水平。数据集中可能有许多未使用的因素,但常见的原因是观察值下降。

下面是一个重现您的错误的快速示例:

library('randomForest')

#making a toy data frame
x <- data.frame('one' = c(1,1,1,1,1,seq(50) ),
       'two' = c(seq(54),NA),
       'three' = seq(55),
       'four' = seq(55) )

x$one <- as.factor(x$one)

x <- na.omit(x) #getting rid of an NA. Note this removes the whole row.

randomForest(one ~., data = as.matrix(x)) #your first error
randomForest(one ~., data = x) #your second error

x <- droplevels(x)

randomForest(one ~., data = x) #OK
© www.soinside.com 2019 - 2024. All rights reserved.