微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

查找矩阵数组的索引,该索引最接近 R

如何解决查找矩阵数组的索引,该索引最接近 R

我有一个数组 Q,它的大小为 nquantiles by nfeatures by nfeatures。在这里,基本上切片 Q[1,] 会给我我的数据的第一个分位数,跨越我的数据的所有 n 个特征。

我感兴趣的是使用另一个矩阵 M(大小为 nfeatures 乘 nfeatures)代表一些其他数据,并询问 M 中的每个元素在 Q 中的分位数。

最快的方法是什么?

我认为我可以对矩阵 M 的所有行和列执行 double for 循环,并提出与此类似的解决方案:Finding the closest index to a value in R

但是对所有 nfeatures x nfeatures 值执行此操作将非常低效。我希望可能存在一种解决这个问题的矢量化方法,但我不知道如何解决这个问题。

这是方法的可重现方法,我可以用 O(N^2) 复杂度解决问题。

#Generate some data
set.seed(235)
data             = rnorm(n = 100,mean = 0,sd = 1)
list_of_matrices = list(matrix(data = data[1:25],ncol = 5,nrow = 5),matrix(data = data[26:50],matrix(data = data[51:75],matrix(data = data[76:100],nrow = 5))
#Get the quantiles  (5 quantiles here)
Q <- apply(simplify2array(list_of_matrices),1:2,quantile,prob = c(seq(0,1,length = 5)))
#dim(Q)
#Q should have dims nquantiles by nfeatures by nfeatures

#Generate some other matrix M (true-data)
M             = matrix(data = rnorm(n = 25,sd = 1),nrow = 5,ncol = 5)

#Loop through rows and columns in M to find which index of the array matches up closest with element M[i,j]
results = matrix(data = NA,ncol = 5)
for (i in 1:nrow(M)) {
  for (j in 1:ncol(M)) {
    true_value = M[i,j]
    #Subset Q to the ith and jth element (vector of nqauntiles)
    quantiles  = Q[,i,j]
    results[i,j]    = (which.min(abs(quantiles-true_value)))
  }
}
'''

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。