两个矩阵之间的Pearson相关

时间:2016-12-18 10:34:49

标签: python-2.7 numpy correlation

所以我想计算一个矩阵的每一行与另一个矩阵的每一列之间的相关性。这是我所提出的,它的工作原理,但我觉得它很慢(对于形状为500x30000和500x16的两个矩阵,大约需要60秒)。

def matrix_corr(array1,array2):

array1= array1.T #transposed in order to have same dimension in the middle of both matrices


corr_pear = np.empty((array1.shape[0],array2.shape[1]))


for n in range(array1.shape[0]): #30000 rowvectors
    array1_mean = np.mean(array1[n,:]) #n-th rowvector 
    array1_squared = np.sum(np.square(array1[n,:]-array1_mean))
    for m in range(array2.shape[1]): #256 columnvectors of hypothesis
        array2_mean = np.mean(array1[:,m])
        array2_squared = np.sum(np.square(array1[:,m]-array2_mean))
        corr_pear[n,m] = (np.inner((array1[n,:]-array1_mean),(array2[:,m]-array2_mean))/
        float(math.sqrt(array1_squared*array2_squared)))

return corr_pear

我认为有更多的pythonic方法来解决这个问题。

我希望有人能告诉我如何调整它。

谢谢!

0 个答案:

没有答案