r - 如何在不丢失行的情况下创建 dtm
问题描述
我尝试运行一个lda。
我必须使用它将其转换为适当的格式
但是,有了这个,我不知道为什么我会从最初的输入中丢失 2-3 个文档。
dtm <- convert(myDfm, to = "topicmodels")
结果,我可以将主题与初始数据框合并
我虽然可以使用 dfm,但它在 lda() 中是不可接受的格式
toks <- toks %>% tokens_wordstem()
myDfm <- dfm(toks, ngrams = 1)
不幸的是,我无法提供示例输入,因为它大约有 30000 行。如果我将其测试为五行的小示例,则该解决方案可以正常工作。
有什么建议么?
解决方案
转换后的 dfm 正在删除空的“文档”,这可能是因为通过频率修剪或模式匹配(例如删除停用词)删除了特征。LDA 无法处理空文档,因此默认情况下,空文档会从 LDA 格式(“topicmodels”、“stm”等)中删除。
从 v1.5 开始,在convert()
called中有一个选项,如果您想保留零特征文档omit_empty = TRUE
,可以将其设置为。FALSE
library("quanteda")
## Package version: 1.5.1
txt <- c("one two three", "and or but", "four five")
dfmat <- tokens(txt) %>%
tokens_remove(stopwords("en")) %>%
dfm()
dfmat
## Document-feature matrix of: 3 documents, 5 features (66.7% sparse).
## 3 x 5 sparse Matrix of class "dfm"
## features
## docs one two three four five
## text1 1 1 1 0 0
## text2 0 0 0 0 0
## text3 0 0 0 1 1
这是设置omit_empty = FALSE
造成的差异:
# with and without the empty documents
convert(dfmat, to = "topicmodels")
## <<DocumentTermMatrix (documents: 2, terms: 5)>>
## Non-/sparse entries: 5/5
## Sparsity : 50%
## Maximal term length: 5
## Weighting : term frequency (tf)
convert(dfmat, to = "topicmodels", omit_empty = FALSE)
## <<DocumentTermMatrix (documents: 3, terms: 5)>>
## Non-/sparse entries: 5/10
## Sparsity : 67%
## Maximal term length: 5
## Weighting : term frequency (tf)
最后,如果您想对 dfm 进行子集化以删除空文档,只需使用dfm_subset()
. 第二个参数被强制转换为一个逻辑值,该值将采用TRUE
whenntoken(dfmat) > 0
和FALSE
when 0 的值。
# subset dfm to remove the empty documents
dfm_subset(dfmat, ntoken(dfmat))
## Document-feature matrix of: 2 documents, 5 features (50.0% sparse).
## 2 x 5 sparse Matrix of class "dfm"
## features
## docs one two three four five
## text1 1 1 1 0 0
## text3 0 0 0 1 1
推荐阅读
- php - Laravel 通过 JSON 对象数组建立关系
- unix - chmod 不会更改 Google Drive File Stream 中文件的权限
- docker - 如何使用第二个 docker 实例?
- sql-server - 按优先顺序查询
- kiwi-tcms - 报告字段重叠
- php - 如何在 Wordpress 中呈现自定义表格中的信息?
- php - php pecl_http 已加载,但未定义任何函数
- neo4j - Spring Data Neo4j 通过几个 id 数组查找节点
- java - 缺少流的 Spring Initializr
- apache - 设置器注入期间的 Symfony 5 @required 注释奇怪的缓存问题?