R - 将 DFM 转换为 LSA,然后计算余弦相似度:错误继承(x,"Matrix")不是 TRUE

R - convert DFM to LSA then compute cosine similarity: Error inherits(x, "Matrix") is not TRUE

我有一个文档特征矩阵 (DFM): 我想把它转换成一个 LSA 对象,最后计算每个文档之间的余弦相似度。

这是我跟随的段落

lsa_t2 <- convert(DFM_tfidf, to = "lsa" , omit_empty = TRUE)
t2_lsa_tfidf_cos_sim = sim2(x = lsa_t2, method = "cosine", norm = "l2")

但是我得到这个错误:

Error in sim2(x = lsa_t2, method = "cosine", norm = "l2") :
inherits(x, "matrix") || inherits(x, "Matrix") is not TRUE

为了提供更多背景信息,这就是 las_t2 的样子

任何文档都包含文本(我已经检查过了),在清除 dfm 之前,我过滤掉了没有文本的文档。

知道发生了什么事吗?

您收到的错误基本上意味着函数 sim2 不适用于 lsa 对象。但是,我不确定我是否理解这个问题。为什么首先要将 dfm 转换为 lsa 文本矩阵格式?

如果要计算文本之间的余弦相似度,可以直接在quenteda

中进行
library(quanteda)

texts <- c(d1 = "Shipment of gold damaged in a fire",
           d2 = "Delivery of silver arrived in a silver truck",
           d3 = "Shipment of gold arrived in a truck" )

texts_dfm <- dfm(texts)

textstat_simil(texts_dfm, 
               margin = "documents",
               method = "cosine")
#> textstat_simil object; method = "cosine"
#>       d1    d2    d3
#> d1 1.000 0.359 0.714
#> d2 0.359 1.000 0.598
#> d3 0.714 0.598 1.000

如果您想使用 text2vec 中的 sim2,您可以使用相同的对象,而无需先转换它:

library(text2vec)
sim2(x = texts_dfm, method = "cosine", norm = "l2")
#> 3 x 3 sparse Matrix of class "dsCMatrix"
#>           d1        d2        d3
#> d1 1.0000000 0.3585686 0.7142857
#> d2 0.3585686 1.0000000 0.5976143
#> d3 0.7142857 0.5976143 1.0000000

如你所见,结果是一样的。

更新

根据评论,我现在了解到您想通过潜在语义分析对数据进行转换。您可以按照下面链接的教程并插入 dfm 而不是教程中使用的 dtm:

texts_dfm_tfidf <- dfm_tfidf(texts_dfm)


library(text2vec)
lsa = LSA$new(n_topics = 2)
dtm_tfidf_lsa = fit_transform(texts_dfm_tfidf, lsa) # I get a warning here, probably due to the size of the toy dfm
d1_d2_tfidf_cos_sim = sim2(x = dtm_tfidf_lsa, method = "cosine", norm = "l2")
d1_d2_tfidf_cos_sim
#>              d1           d2        d3           d4
#> d1  1.000000000 -0.002533794 0.5452992  0.999996189
#> d2 -0.002533794  1.000000000 0.8368571 -0.005294431
#> d3  0.545299245  0.836857086 1.0000000  0.542983071
#> d4  0.999996189 -0.005294431 0.5429831  1.000000000

请注意,这些结果不同于 运行 运行,除非您使用 set.seed()

或者如果您想在 quanteda 中执行所有操作:

texts_lsa <- textmodel_lsa(texts_dfm_tfidf, 2)

textstat_simil(as.dfm(texts_lsa$docs), 
               margin = "documents",
               method = "cosine")
#> textstat_simil object; method = "cosine"
#>          d1       d2    d3       d4
#> d1  1.00000 -0.00684 0.648  1.00000
#> d2 -0.00684  1.00000 0.757 -0.00894
#> d3  0.64799  0.75720 1.000  0.64638
#> d4  1.00000 -0.00894 0.646  1.00000