有没有一种方法可以向量化计算斯皮尔曼相关性及其 p 值的嵌套循环?

Is there a way to vectorize a nested loop that calculates the spearman correlation and it's p-values?

我有一个有 8300 列和 18 行的矩阵 m。每列代表一个基因;每行一个样本。我想计算邻接矩阵(使用 spearman 相关性)和相应的 p 值矩阵。

我目前得到的代码是:

W = np.zeros((n_genes, n_genes))
P = np.zeros((n_genes, n_genes))

for i in range(0, n_genes):
    for j in range(0, n_genes):
        W[i,j], P[i,j] = st.spearmanr(m[:,i], m[:,j])

效率低得惊人(使用 GPU 在 colab-google 中 运行 大约需要 11 个小时)。有没有办法对其进行矢量化?

非常感谢!

https://docs.scipy.org/doc/scipy-0.16.1/reference/generated/scipy.stats.spearmanr.html

看起来使用此函数您可以为两个参数传入整个 m 矩阵,它会在所有列之间进行相关和 p-values,它会将其解释为变量(行是样本变量)。然后它以矩阵形式输出 p-values 和相关性。因此,您可以摆脱 for 循环并一次性生成相关矩阵和 p-value 矩阵。即使不在一次通过中执行此操作,看起来您也在两次遍历所有数据以形成一个对称矩阵;我会完成第二个循环 "for j in range(i, n_genes):" 然后在循环主体中填写两个条目 [i,j] 和 [j,i]。