我很欣赏 Ben 的回答:LDA with topicmodels,我如何查看不同文档属于哪些主题?
我的问题是:如何在最后一步保留文档标题?例如:
在单独的文本文件中手动创建三个 .txt 文档并将它们存储在目录 ~Desktop/nature_corpus 中
第一个文件标题:nature.txt
第一篇文献内容:名词the natural world、Mother Nature、Mother Earth、the environment;野生动物、动植物、乡村;宇宙,宇宙。
第二个文件标题:conservation.txt
第二文件内容:名词theconservation oftropical forests:preservation,protection,protecting,safekeeping;照料、监护、饲养、监督;保养、维护、修理、修复;生态学,环保主义。
第三个文件标题:bird.txt
第三文献正文:名词养鸟:家禽;雏鸟、雏鸟、雏鸟;非正式的羽毛朋友,小鸟;鹦鹉; (鸟类)技术鸟类。
#install.packages("tm")
#install.packages("topicmodels")
library(tm)
# Create DTM
#. The file path is a Mac file path.
corpus_nature_1 <- Corpus(DirSource("/Users/[home folder name]/Desktop/nature_corpus"),readerControl=list(reader=readPlain,language="en US"))
corpus_nature_2 <- tm_map(corpus_nature_1,removeNumbers)
corpus_nature_3 <- tm_map(corpus_nature_2,content_transformer(tolower))
mystopwords <- c(stopwords(),"noun", "verb")
corpus_nature_4 <- tm_map(corpus_nature_3,removeWords, mystopwords)
corpus_nature_5 <- tm_map(corpus_nature_4,removePunctuation)
corpus_nature_6 <- tm_map(corpus_nature_5,stripWhitespace)
dtm_nature_1 <- DocumentTermMatrix(corpus_nature_6)
inspect(dtm_nature_1)
<<DocumentTermMatrix (documents: 3, terms: 42)>>
Non-/sparse entries: 42/84
Sparsity : 67%
Maximal term length: 16
Weighting : term frequency (tf)
Sample :
Terms
Docs avifauna birdie birds budgie chick feathered feeding fledgling fowl mother
bird.txt 1 1 2 1 1 1 1 1 1 0
conservation.txt 0 0 0 0 0 0 0 0 0 0
nature.txt 0 0 0 0 0 0 0 0 0 2
主题模型与 topicmodels 一起运行:
# Run topic model 2 topics
library(topicmodels)
topicmodels_LDA_nature_2 <- LDA(dtm_nature_1,2,method="Gibbs",control=list(seed=1),model=NULL)
terms(topicmodels_LDA_nature_2,3)
Topic 1 Topic 2
[1,] "birds" "avifauna"
[2,] "mother" "birdie"
[3,] "chick" "budgie"
如何在此处保留文档标题(在 inspect(dtm_nature_1) 行中可见)?
# Create CSV Matrix 2 topics
matrix_nature_2 <- as.data.frame(topicmodels_LDA_nature_2@gamma)
names(matrix_nature_2) <- c(1:2)
write.csv(matrix_nature_2,"matrix_nature_2.csv")
#. Rows in this table are documents, columns are topics.
1 2
1 0.46875 0.53125
2 0.52238806 0.47761194
3 0.555555556 0.444444444
谢谢。