![](/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.