繁体   English   中英

尝试获取随机森林以进行文本分类运行

[英]Trying to get random forest for text classification running

我正在尝试为学校项目运行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都不熟悉,因此可能存在概念上的错误。 知道如何解决问题吗?

您的代码有几个问题:

首先您的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。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM