簡體   English   中英

R:創建相似度矩陣的有效方法

[英]R: efficient way to create a similarity matrix

因此,我有一個龐大的數據矩陣,並想創建一個相似度矩陣。 我知道可以使用不同的功能(相關,余弦,互信息等),但是我的問題是有效的實現。 例如,可能正在利用data.frame的優勢,

所以這是到目前為止的示例代碼,我只計算矩陣一半的相似度,

#rm(list = ls())

load(iris)# the real data is 15K*300
tt = iris[c(1:5),1:4]

similarity_matrix_cor = matrix(data = 0, nrow = nrow(tt), ncol = nrow(tt))

for (cnt.1 in 1:nrow(tt))
{   
    print(cnt.1)
    for (cnt.2 in cnt.1:nrow(tt))
    {
        similarity_matrix_cor[cnt.1, cnt.2] = cor(as.numeric(tt[cnt.1,]), as.numeric(tt[cnt.2,]))
    }

}

complete_mat = function(tt) # eventually I add the other half of the matrix
{
    return(t(tt) + tt - diag(diag(tt),nrow=nrow(tt),ncol=ncol(tt)))
}

matrix_cor = complete_mat(similarity_matrix_cor)

你可以嘗試這樣的事情

#helper function to access row pairs
matab<-Vectorize(
    function(a,b,fun,data) {
        fun(data[a,],data[b,])
    }, vectorize.args=list("a","b")
)

然后使用outer()創建所有巴黎

outer(1:nrow(x),1:nrow(x),matab,fun=cor,data=as.matrix(x))

只需將fun=cor替換fun=cor您喜歡的功能即可。 它將接收成對的數據行作為輸入。 此解決方案不假定您的函數是對稱的,因此fun(a,b)可能不同於fun(b,a)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM