![](/img/trans.png)
[英]R : error inherits(x, “matrix”) || inherits(x, “Matrix”) is not TRUE when trying to calculate cosine similarity with tf-idf
[英]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")
但我收到此错误:
sim2(x = lsa_t2, method = "cosine", norm = "l2") 中的错误:
继承(x,“矩阵”)|| 继承(x,“矩阵”)不是真的
为了提供更多上下文,这就是 las_t2 的样子
任何文档都包含文本(我已经检查过了)并且在我清除 dfm 之前我过滤了没有文本的文档。
知道发生了什么吗?
您收到的错误基本上意味着函数sim2
不适用于lsa
对象。 但是,我不确定我是否理解这个问题。 为什么首先要将dfm
转换为lsa
textmatrix 格式?
如果要计算文本之间的余弦相似度,可以直接在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
如果你想使用sim2
从text2vec
,你可以这样做,使用相同的对象,而无需首先将其转换:
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()
否则这些结果会因运行而set.seed()
。
或者,如果您想在quanteda
完成所有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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.