r语言 - 文本分类 - 随机森林. 新数据中缺少训练数据中的变量



我对统计学习等完全陌生,但对文本分类特别感兴趣。我正在关注我在这里找到的关于该主题的实验室:https://cfss.uchicago.edu/text_classification.html#fnref1。不幸的是,在训练好的模型可用于新数据之前,实验室就结束了,所以我试图弄清楚如何自己完成它。

我训练了我的模型,我使用随机森林。当我尝试在新数据上使用predict()时,它会抛出错误:Error in predict.randomForest(modelFit, newdata) : variables in the training data missing in newdata

在我看来,这没有意义,因为测试数据实际上是原始数据的子集。我认为这个错误与我如何构建模型与测试数据的数据结构有关,但老实说,我没有足够的能力弄清楚如何解决错误或它实际上源于何处(尽管我假设我犯了一些荒谬的错误(。

还有其他帖子具有相同的错误,但我认为他们的错误来源与我的不同,我整天都在努力寻找解决方法!

我在下面使用的完整代码:

library(tidyverse)
library(tidytext)
library(stringr)
library(caret)
library(tm)
data(USCongress, package = "RTextTools")
test <- congress[1:100, ]
congress <- congress[100:nrow(congress), ]
(congress <- as_tibble(USCongress) %>%
mutate(text = as.character(text)))
(congress_tokens <- congress %>%
unnest_tokens(output = word, input = text) %>%
# remove numbers
filter(!str_detect(word, "^[0-9]*$")) %>%
# remove stop words
anti_join(stop_words) %>%
# stem the words
mutate(word = SnowballC::wordStem(word)))
(congress_dtm <- congress_tokens %>%
# get count of each token in each document
count(ID, word) %>%
# create a document-term matrix with all features and tf weighting
cast_dtm(document = ID, term = word, value = n))
congress_dtm <- removeSparseTerms(congress_dtm, sparse = .99)
congress_rf <- train(x = as.matrix(congress_dtm),
y = factor(congress$major),
method = "rf",
ntree = 200,
trControl = trainControl(method = "oob"))
final_predictions <- predict(congress_rf, newdata = test)

最后一行(final_predictions <- predict(congress_rf, newdata = test(是出现错误的地方,在此之前没有出现错误消息。

问题是test不是拟合模型的数据的子集(congress_dtm(。如果创建congress_dtm的子集,它确实有效:

#....
congress_dtm <- removeSparseTerms(congress_dtm, sparse = .99)
test <- congress_dtm[100, ]
congress_rf <- train(x = as.matrix(congress_dtm),
y = factor(congress$major),
method = "rf",
ntree = 200,
trControl = trainControl(method = "oob"))
final_predictions <- predict(congress_rf, newdata = test)
final_predictions
#> [1] 12
#> Levels: 1 2 3 4 5 6 7 8 10 12 13 14 15 16 17 18 19 20 21 99

最新更新