簡體   English   中英

如何找到矩陣中最相似的列?

[英]how to find the most similar columns in a matrix?

我有一個矩陣,希望在其中找到非常相似的列( 我不希望找到相同的列

# to generate a matrix
Mat<- matrix(rexp(200, rate=.1), ncol=1000, nrow=400)

我個人認為“ cor”或“ all.equal”,我做了如下操作,但沒有用。

indexmax <- apply(Mat, MARGIN = 2, function(x) which(cor(x) >= 0.5, arr.ind = TRUE))

我需要的輸出是顯示哪些列高度相似以及它們的相似程度(可以是相關系數)

相似意味着它們的值在某個閾值內相似(例如,超過75%的值殘差(例如column1-column2)小於abs(0.5)

我也很想看看這與關聯有何不同。 它們會產生相同的結果嗎?

您可以嘗試使用相關性(使用更簡單的矩陣進行演示)

set.seed(123)
Mat <- matrix(rnorm(300), ncol = 10)
library(matrixcalc)

corr <- cor(Mat)
res <-which(lower.triangle(corr)>.3, arr.ind = TRUE)

data.frame(res[res[,1] != res[,2],], correlation = corr[res[res[,1] != res[,2],]])
  row col correlation
1   8   1   0.3387738
2   6   2   0.3350891

rowcol實際上都引用原始矩陣中的列。 因此,例如,第8列與第1列之間的相關性為0.3387738

我將采用線性回歸方法:

Mat<- matrix(rexp(200, rate=.1), ncol=100, nrow=400)
combinations <- combn(1:ncol(Mat), m = 2)
sigma <- NULL
for(i in 1:ncol(combinations)){
  sigma <- c(sigma, summary(lm(Mat[,combinations[1,1]] ~ Mat[,combinations[2,1]]))$sigma)
}
sigma <- data.frame(sigma = sigma, comb_nr = 1:ncol(combinations))

和殘留標准誤差作為可選標准。 您可以按sigma進一步排序數據幀,並獲得最佳/最差組合。

如果您想要一種(不太優雅的)簡單方法,對於您這樣大小的矩陣可能很慢,則可以執行以下操作:

set.seed(1)

Mat <- matrix(runif(40000), ncol=100, nrow=400)

col.combs <- t(combn(1:ncol(Mat), 2))

similar <- data.frame(Col1=NULL, Col2=NULL, Corr=NULL, Pct.Diff=NULL)

# Compare each pair of columns
for (k in 1:nrow(col.combs)) {
    i <- col.combs[k, 1]
    j <- col.combs[k, 2]

    # Difference within threshold?
    diff.thresh <- (abs(Mat[, i] - Mat[, j]) < 0.5)

    pair.corr <- cor(Mat[, 1], Mat[, 2])

    if (mean(diff.thresh) > 0.75)
        similar <- rbind(similar, c(i, j, pair.corr, 100*mean(diff.thresh)))
}

在此示例中,有2590個不同的列對,其值的75%以上在彼此之內(即在0.5個元素內)。 您可以通過查看結果數據幀來檢查實際差異和相關系數。

> head(similar)
   Col1  Col2         Corr Pct.Diff
1     1     2 -0.003187894    76.75
2     1     3  0.074061019    76.75
3     1     4  0.082668387    78.00
4     1     5  0.001713751    75.50
5     1     8  0.052228907    75.75
6     1    12 -0.017921978    78.00

也許這不是最好的解決方案,但可以完成工作。

另外,如果您不確定為什么要使用mean(diff.thresh) ,那是因為邏輯向量的總和是TRUE元素的數量。 平均值是總和除以長度,這意味着在這種情況下,它是閾值內的值的分數。

暫無
暫無

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

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