就sparse 到removeSparseTerms() 的参数而言,稀疏度是指一个词条相对文档频率的阈值,高于该词条删除。这里的相对文档频率是指一个比例。正如命令的帮助页面所述(虽然不是很清楚),稀疏度在接近 1.0 时更小。 (注意稀疏度不能取 0 或 1.0 的值,只能取两者之间的值。)
例如,如果您将sparse = 0.99 设置为removeSparseTerms() 的参数,那么这将仅删除比0.99 更稀疏的术语。
sparse = 0.99 的确切解释是对于术语 $j$,您将保留所有符合以下条件的术语
$df_j > N * (1 - 0.99)$,其中 $N$ 是文档的数量——在这种情况下,可能所有术语都将被保留(参见下面的示例)。
接近另一个极端,如果sparse = .01,那么只会保留(几乎)出现在每个文档中的术语。 (当然这取决于术语的数量和文档的数量,在自然语言中,像“the”这样的常用词很可能出现在每个文档中,因此永远不会“稀疏”。)
稀疏度阈值为 0.99 的示例,其中一个词最多出现在(第一个示例)少于 0.01 个文档和(第二个示例)仅超过 0.01 个文档中:
> # second term occurs in just 1 of 101 documents
> myTdm1 <- as.DocumentTermMatrix(slam::as.simple_triplet_matrix(matrix(c(rep(1, 101), rep(1,1), rep(0, 100)), ncol=2)),
+ weighting = weightTf)
> removeSparseTerms(myTdm1, .99)
<<DocumentTermMatrix (documents: 101, terms: 1)>>
Non-/sparse entries: 101/0
Sparsity : 0%
Maximal term length: 2
Weighting : term frequency (tf)
>
> # second term occurs in 2 of 101 documents
> myTdm2 <- as.DocumentTermMatrix(slam::as.simple_triplet_matrix(matrix(c(rep(1, 101), rep(1,2), rep(0, 99)), ncol=2)),
+ weighting = weightTf)
> removeSparseTerms(myTdm2, .99)
<<DocumentTermMatrix (documents: 101, terms: 2)>>
Non-/sparse entries: 103/99
Sparsity : 49%
Maximal term length: 2
Weighting : term frequency (tf)
以下是一些带有实际文本和术语的附加示例:
> myText <- c("the quick brown furry fox jumped over a second furry brown fox",
"the sparse brown furry matrix",
"the quick matrix")
> require(tm)
> myVCorpus <- VCorpus(VectorSource(myText))
> myTdm <- DocumentTermMatrix(myVCorpus)
> as.matrix(myTdm)
Terms
Docs brown fox furry jumped matrix over quick second sparse the
1 2 2 2 1 0 1 1 1 0 1
2 1 0 1 0 1 0 0 0 1 1
3 0 0 0 0 1 0 1 0 0 1
> as.matrix(removeSparseTerms(myTdm, .01))
Terms
Docs the
1 1
2 1
3 1
> as.matrix(removeSparseTerms(myTdm, .99))
Terms
Docs brown fox furry jumped matrix over quick second sparse the
1 2 2 2 1 0 1 1 1 0 1
2 1 0 1 0 1 0 0 0 1 1
3 0 0 0 0 1 0 1 0 0 1
> as.matrix(removeSparseTerms(myTdm, .5))
Terms
Docs brown furry matrix quick the
1 2 2 0 1 1
2 1 1 1 0 1
3 0 0 1 1 1
在sparse = 0.34 的最后一个示例中,仅保留了出现在三分之二文档中的术语。
根据文档频率从文档术语矩阵中修剪术语的另一种方法是文本分析包quanteda。此处的相同功能不是指稀疏度,而是直接指术语的文档频率(如tf-idf)。
> require(quanteda)
> myDfm <- dfm(myText, verbose = FALSE)
> docfreq(myDfm)
a brown fox furry jumped matrix over quick second sparse the
1 2 1 2 1 2 1 2 1 1 3
> dfm_trim(myDfm, minDoc = 2)
Features occurring in fewer than 2 documents: 6
Document-feature matrix of: 3 documents, 5 features.
3 x 5 sparse Matrix of class "dfmSparse"
features
docs brown furry the matrix quick
text1 2 2 1 0 1
text2 1 1 1 1 0
text3 0 0 1 1 1
这种用法对我来说似乎更简单。