问题描述
我有一个数组 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 (将#修改为@)