我正在尝试为学校项目运行randomForest。我正在尝试建立一个测试分类器,该分类器根据一些文本预测类别(列标签)。
很抱歉,我的文档术语矩阵似乎有问题,因此我感到很困惑。 这是错误:
> rfmodel <- randomForest(df$label, data = events_dtm)
Error in if (n == 0) stop("data (x) has 0 rows") :
argument is of length zero
这是当前代码的外观。数据具有代表性。
library(tidyverse)
library(tidytext)
library(stringr)
library(caret)
library(tm)
library(dplyr)
library(randomForest)
text = c("this is a random text",
"another rnd text",
"hi there",
"not so rnd",
"what's that?",
"kinda boring",
"this is a random text",
"another rnd text",
"hi there",
"not so rnd",
"what's that?",
"kinda boring")
label = c(1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2)
df <- data.frame(text= text, label=label)
df$label <- as.factor(df$label)
df$text <- as.character(df$text)
df$ID <- seq.int(nrow(df))
df <- df[1:5,]
as_tibble(df) %>%
mutate(text = as.character(text)) -> type
data("stop_words")
type %>%
unnest_tokens(output = word, input = text) %>%
anti_join(stop_words) %>%
mutate(word = SnowballC::wordStem(word)) -> type_tokens
type_tokens %>%
count(ID, word) %>%
cast_dtm(document = ID, term = word, value = n,
weighting = weightTfIdf) -> type_dtm
print(type_dtm)
rfmodel <- randomForest(df$label, data = type_dtm)
print(rfmodel)
dfT <- data.frame(text= text)
dfT$ID <- seq.int(nrow(dfT))
as_tibble(dfT) %>%
mutate(text = as.character(text)) -> typeT
typeT %>%
unnest_tokens(output = word, input = text) -> typeT
typeT %>%
count(ID, word) %>%
cast_dtm(document = ID, term = word, value = n,
weighting = weightTfIdf) -> typeT
pred_test <- predict(rfmodel, newdata = dfT, type = "class")
print(pred_test)
由于我对随机森林和R都比较陌生,因此可能存在概念上的错误。 知道如何解决问题吗?
答案 0 :(得分:0)
您的代码有几个问题:
首先,您的randomForest电话:
rfmodel <- randomForest(df$label, data = type_dtm)
您不能调用df $ label并在不存在标签的地方指定数据type_dtm。
其次,randomForest不接受稀疏性。您需要为此做些事情。您可以通过将标签信息与type_dtm合并来解决。搜索如何执行此操作。第三,您告诉randomForest y = label,但是您要么需要提供类似于label〜的公式接口。并指定data = ....或您需要将y和x指定为y =标签,而x = ...有关更多信息,请参见?randomForest
。
所有这些问题的总和导致您收到此错误。开始一个一个地解决它们,当您再次陷入困境时,提出一个问题。您的代码是创建可复制示例的良好起点,因此请为此+1。