您偶然发现了计算术语频率的差异。
标准定义:
TF:术语频率:TF(t) =(术语 t 出现在 a 中的次数
文档)/(文档中的术语总数)。
IDF:逆文档频率:IDF(t) = log(总数量
文档/其中包含术语 t 的文档数量)
TF-IDF 重量是这些量 TF * IDF 的乘积
看起来很简单,但事实并非如此。我们来计算 doc1 中单词“dog”的 tf_idf。
狗的第一个 TF:即 doc 中的 1 个术语 / 9 个术语 = 0.11111
1/9 = 0.1111111
现在狗的 IDF:(2 个文档/1 个术语)的日志。现在有多种可能性,即:log(或自然对数)、log2或log10!
log(2) = 0.6931472
log2(2) = 1
log10(2) = 0.30103
#tf_idf on log:
1/9 * log(2) = 0.07701635
#tf_idf on log2:
1/9 * log2(2) = 0.11111
#tf_idf on log10:
1/9 * log10(2) = 0.03344778
现在变得有趣了。Tidytext
根据日志为您提供正确的权重。tm
根据 log2 返回 tf_idf。我预计 Quanteda 的值为 0.03344778,因为它们的基数是 log10。
但是查看 quanteda,它正确返回结果,但使用计数作为默认值而不是比例计数。要获得应有的一切,请尝试以下代码:
df.count3 <- df %>% unnest_tokens(word, text) %>%
count(doc, word) %>%
cast_dfm(document = doc,term = word, value = n)
dfm_tfidf(df.count3, scheme_tf = "prop", scheme_df = "inverse")
Document-feature matrix of: 2 documents, 11 features (22.7% sparse).
2 x 11 sparse Matrix of class "dfm"
features
docs brown fox god jumps lazy over quick the dog foxy ox
doc1 0 0.03344778 0.03344778 0 0 0 0 0 0 0 0
doc2 0 0 0 0 0 0 0 0 0.030103 0.030103 0.030103
看起来更好,这是基于 log10 的。
如果你使用quanteda
通过调整参数,可以得到tidytext
or tm
通过改变结果base
范围。
# same as tidytext the natural log
dfm_tfidf(df.count3, scheme_tf = "prop", scheme_df = "inverse", base = exp(1))
# same as tm
dfm_tfidf(df.count3, scheme_tf = "prop", scheme_df = "inverse", base = 2)