为了节省内存空间,在处理一个非常大的语料库样本时,我希望只取前10克,并将其中的10克与所有的2到5克结合起来,形成我的单个quanteda::dfmSparse对象,它将用于自然语言处理nlp预测。随身携带所有的1克将是没有意义的,因为只有前十或二十将永远不会与我使用的简单的后退模式。
我没能找到一个quanteda::dfm(corpusText,。。。)参数,指示它只返回顶部的##特性。因此,基于package @KenB在其他线程中的评论,我使用dfm_select/remove函数提取前十克,并根据"quanteda联接“搜索结果点击"concatenate dfm matrices in 'quanteda' package”,我使用的是rbind.dfmSparse?函数来加入这些结果。
据我所知,到目前为止,一切看起来都是正确的。我想我应该把这个游戏计划从SO社区中拿出来,看看我是否忽略了一个更有效的途径来达到这个结果,或者我已经找到的解决方案中的一些缺陷。
corpusObject <- quanteda::corpus(paste("some corpus text of no consequence that in practice is going to be very large\n",
"and so one might expect a very large number of ngrams but for nlp purposes only care about top ten\n",
"adding some corpus text word repeats to ensure 1gram top ten selection approaches are working\n"))
corpusObject$documents
dfm1gramsSorted <- dfm_sort(dfm(corpusObject, tolower = T, stem = F, ngrams = 1))
dfm2to5grams <- quanteda::dfm(corpusObject, tolower = T, stem = F, ngrams = 2:5)
dfm1gramsSorted; dfm2to5grams
#featnames(dfm1gramsSorted); featnames(dfm2to5grams)
#colSums(dfm1gramsSorted); colSums(dfm2to5grams)
dfm1gramsSortedLen <- length(featnames(dfm1gramsSorted))
# option1 - select top 10 features from dfm1gramsSorted
dfmTopTen1grams <- dfm_select(dfm1gramsSorted, pattern = featnames(dfm1gramsSorted)[1:10])
dfmTopTen1grams; featnames(dfmTopTen1grams)
# option2 - drop all but top 10 features from dfm1gramsSorted
dfmTopTen1grams <- dfm_remove(dfm1gramsSorted, pattern = featnames(dfm1gramsSorted)[11:dfm1gramsSortedLen])
dfmTopTen1grams; featnames(dfmTopTen1grams)
dfmTopTen1gramsAndAll2to5grams <- rbind(dfmTopTen1grams, dfm2to5grams)
dfmTopTen1gramsAndAll2to5grams;
#featnames(dfmTopTen1gramsAndAll2to5grams); colSums(dfmTopTen1gramsAndAll2to5grams)
data.table(ngram = featnames(dfmTopTen1gramsAndAll2to5grams)[1:50], frequency = colSums(dfmTopTen1gramsAndAll2to5grams)[1:50],
keep.rownames = F, stringsAsFactors = F)/eoq
发布于 2017-08-13 09:14:20
对于提取前10位单位图,这个策略会很好地工作:
cbind() (而不是rbind())的2到5克dfm )。这应该可以做到:
dfmCombined <- cbind(dfm1gramsSorted[, 1:10], dfm2to5grams)
head(dfmCombined, nfeat = 15)
# Document-feature matrix of: 1 document, 195 features (0% sparse).
# (showing first document and first 15 features)
# features
# docs some corpus text of to very large top ten no some_corpus corpus_text text_of of_no no_consequence
# text1 2 2 2 2 2 2 2 2 2 1 2 2 1 1 1您的示例代码包含了data.table的一些用法,尽管这在问题中没有出现。在v0.99中,我们添加了一个新函数textstat_frequency(),它在data.frame中生成“长”/“整齐”的频率格式,这可能会有帮助:
head(textstat_frequency(dfmCombined), 10)
# feature frequency rank docfreq
# 1 some 2 1 1
# 2 corpus 2 2 1
# 3 text 2 3 1
# 4 of 2 4 1
# 5 to 2 5 1
# 6 very 2 6 1
# 7 large 2 7 1
# 8 top 2 8 1
# 9 ten 2 9 1
# 10 some_corpus 2 10 1https://stackoverflow.com/questions/45656490
复制相似问题