R 中的文本挖掘 |内存管理
Text Mining in R | memory management
我正在使用一个 160 MB 的文本文件并进行数据挖掘,但似乎一旦我将其转换为矩阵以了解词频然后它需要太多内存,有人可以帮助我吗
> dtm <- DocumentTermMatrix(clean)
> dtm
<<DocumentTermMatrix (documents: 472029, terms: 171548)>>
Non-/sparse entries: 3346670/80972284222
Sparsity : 100%
Maximal term length: 126
Weighting : term frequency (tf)
> as.matrix(dtm)
Error: cannot allocate vector of size 603.3 Gb
@Vineet 这里的数学说明了为什么 R 试图分配 603Gb 来将文档术语矩阵转换为非稀疏矩阵。 R 中矩阵中的每个数字单元占用 8 个字节。根据问题中文档术语矩阵的大小,数学公式如下:
> #
> # calculate memory consumed by matrix
> #
>
> rows <- 472029 #
> cols <- 171548
> # memory in gigabytes
> rows * cols * 8 / (1024 * 1024 * 1024)
[1] 603.3155
如果要计算词频,最好生成 1-gram,然后将它们汇总成频率分布。
使用 quanteda
包,代码如下所示。
words <- tokenize(...)
ngram1 <- unlist(tokens_ngrams(words,n=1))
ngram1freq <- data.frame(table(ngram1))
问候,
莱恩
2017-11-24 更新: 这是 quanteda 包中的一个完整示例,它使用 textstat_frequency()
函数从文档特征矩阵生成频率分布,以及前 20 个特征的 barplot()
。
此方法不需要将 n-gram 生成和聚合到频率分布中。
library(quanteda)
myCorpus <- corpus(data_char_ukimmig2010)
system.time(theDFM <- dfm(myCorpus,tolower=TRUE,
remove=c(stopwords(),",",".","-","\"","'","(",")",";",":")))
system.time(textFreq <- textstat_frequency(theDFM))
hist(textFreq$frequency,
main="Frequency Distribution of Words: UK 2010 Election Manifestos")
top20 <- textFreq[1:20,]
barplot(height=top20$frequency,
names.arg=top20$feature,
horiz=FALSE,
las=2,
main="Top 20 Words: UK 2010 Election Manifestos")
...以及由此产生的条形图:
我正在使用一个 160 MB 的文本文件并进行数据挖掘,但似乎一旦我将其转换为矩阵以了解词频然后它需要太多内存,有人可以帮助我吗
> dtm <- DocumentTermMatrix(clean)
> dtm
<<DocumentTermMatrix (documents: 472029, terms: 171548)>>
Non-/sparse entries: 3346670/80972284222
Sparsity : 100%
Maximal term length: 126
Weighting : term frequency (tf)
> as.matrix(dtm)
Error: cannot allocate vector of size 603.3 Gb
@Vineet 这里的数学说明了为什么 R 试图分配 603Gb 来将文档术语矩阵转换为非稀疏矩阵。 R 中矩阵中的每个数字单元占用 8 个字节。根据问题中文档术语矩阵的大小,数学公式如下:
> #
> # calculate memory consumed by matrix
> #
>
> rows <- 472029 #
> cols <- 171548
> # memory in gigabytes
> rows * cols * 8 / (1024 * 1024 * 1024)
[1] 603.3155
如果要计算词频,最好生成 1-gram,然后将它们汇总成频率分布。
使用 quanteda
包,代码如下所示。
words <- tokenize(...)
ngram1 <- unlist(tokens_ngrams(words,n=1))
ngram1freq <- data.frame(table(ngram1))
问候,
莱恩
2017-11-24 更新: 这是 quanteda 包中的一个完整示例,它使用 textstat_frequency()
函数从文档特征矩阵生成频率分布,以及前 20 个特征的 barplot()
。
此方法不需要将 n-gram 生成和聚合到频率分布中。
library(quanteda)
myCorpus <- corpus(data_char_ukimmig2010)
system.time(theDFM <- dfm(myCorpus,tolower=TRUE,
remove=c(stopwords(),",",".","-","\"","'","(",")",";",":")))
system.time(textFreq <- textstat_frequency(theDFM))
hist(textFreq$frequency,
main="Frequency Distribution of Words: UK 2010 Election Manifestos")
top20 <- textFreq[1:20,]
barplot(height=top20$frequency,
names.arg=top20$feature,
horiz=FALSE,
las=2,
main="Top 20 Words: UK 2010 Election Manifestos")
...以及由此产生的条形图: