【问题标题】:Retrieve top n rows based on cosine similarity of vectors in R根据R中向量的余弦相似度检索前n行
【发布时间】:2016-08-09 14:16:46
【问题描述】:

我正在编写一个函数,使用余弦相似度从单词列表及其值中检索前 n 个结果。我已将我的数据包含如下,这是大约 400k 的前几个条目,但它让您对结构有所了解。

the 0.41800  0.249680 -0.41242  0.121700 0.345270 -0.044457 -0.49688 -0.178620 -0.00066023 -0.656600 0.278430 -0.14767 -0.55677  0.14658 -0.0095095
.   0.15164  0.301770 -0.16763  0.176840 0.317190  0.339730 -0.43478 -0.310860 -0.44999000 -0.294860 0.166080  0.11963 -0.41328 -0.42353  0.5986800
of  0.70853  0.570880 -0.47160  0.180480 0.544490  0.726030  0.18157 -0.523930  0.10381000 -0.175660 0.078852 -0.36216 -0.11829 -0.83336  0.1191700
to  0.68047 -0.039263  0.30186 -0.177920 0.429620  0.032246 -0.41376  0.132280 -0.29847000 -0.085253 0.171180  0.22419 -0.10046 -0.43653  0.3341800
and 0.26818  0.143460 -0.27877  0.016257 0.113840  0.699230 -0.51332 -0.473680 -0.33075000 -0.138340 0.270200  0.30938 -0.45012 -0.41270 -0.0993200
in  0.33042  0.249950 -0.60874  0.109230 0.036372  0.151000 -0.55083 -0.074239 -0.09230700 -0.328210 0.095980 -0.82269 -0.36717 -0.67009  0.4290900

这是余弦相似度的代码

cosineSim <- function(v1,v2){
 a <- sum(v1*v2)
 b <- sqrt(sum(v1*v1))* sqrt(sum(v2*v2))
return (a/b)
}

我需要获取用户向量并将其与包含数据集的表 x 中的所有其他向量进行比较。例如,x['cat',] 返回包含单词“cat”所有值的 50 维向量。

这是我的 cosineSim 函数返回的示例:

cosineSim(x['cat',],x['dog',])

打印以下内容:

[1] 0.9218005

这表示这些词的余弦相似度。

这些值是小数,这是我使用 R 进行的第一个项目,所以我无法将代码 here 转换为我的需要。

任何帮助将不胜感激。

【问题讨论】:

  • 这只是一个例子,我可以选择 x['the',] 并且它会给你与数据结构中的第一行相同的结果,我将更新显示cosineSim 的结果。

标签: r vector cosine-similarity


【解决方案1】:

你正在寻找这样的东西吗?计算成对 cosineSim,然后显示前 10 个。您需要 cosineSim 值周围的 abs 吗?

library(data.table)
library(stringi)

#generate sample data
set.seed(1)
numRows <- 400
numCols <- 50
rnames <- head(unique(stri_rand_strings(numRows*2, sample(5:11, 5, replace=TRUE), '[a-zA-Z0-9]')),numRows)
dt <- data.table(matrix(rnorm(numRows*numCols), ncol=numCols, dimnames=list(rnames,NULL)), 
    keep.rownames=T)         
userVec <- rnorm(numCols)

#userVec norm and cosineSim calculation function
userVecNorm <- sqrt(sum(userVec^2))
cosSim <- function(x) sum(userVec*x) / userVecNorm / sqrt(sum(x^2))

#calculate pairwise cosineSim with userVec
dt[, cosineSim:=apply(.SD, 1, cosSim), .SDcols=V1:V50]

#order by cosineSim and show top 10
dt[order(cosineSim),][1:10,]

【讨论】:

    猜你喜欢
    • 2021-06-30
    • 2013-09-27
    • 2011-03-21
    • 2015-12-23
    • 2011-05-01
    • 2017-09-27
    • 2011-03-08
    • 2019-05-31
    • 1970-01-01
    相关资源
    最近更新 更多