簡體   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