两个2D数组之间的相关性(默认“有效”情况):
您可以像这样简单地使用矩阵乘法np.dot –
out = np.dot(arr_one,arr_two.T)
与两个输入数组的每个成对行组合(row1,row2)之间的默认“有效”情况的相关性将对应于每个(row1,row2)位置处的乘法结果.
两个2D阵列的行方向相关系数计算:
def corr2_coeff(A,B):
# Rowwise mean of input arrays & subtract from input arrays themeselves
A_mA = A - A.mean(1)[:,None]
B_mB = B - B.mean(1)[:,None]
# Sum of squares across rows
ssA = (A_mA**2).sum(1);
ssB = (B_mB**2).sum(1);
# Finally get corr coeff
return np.dot(A_mA,B_mB.T)/np.sqrt(np.dot(ssA[:,None],ssB[None]))
这是基于How to apply corr2 functions in Multidimentional arrays in MATLAB的解决方案
标杆
本节将运行时性能与针对generate_correlation_map& ;;的提议方法进行比较.基于循环pearsonr的方法在other answer.中列出(取自函数test_generate_correlation_map(),在其末尾没有值正确性验证码).请注意,建议方法的时间还包括在开始时检查两个输入数组中是否有相同数量的列,这也是在另一个答案中完成的.下面列出了运行时.
情况1:
In [106]: A = np.random.rand(1000,100)
In [107]: B = np.random.rand(1000,100)
In [108]: %timeit corr2_coeff(A,B)
100 loops, best of 3: 15 ms per loop
In [109]: %timeit generate_correlation_map(A, B)
100 loops, best of 3: 19.6 ms per loop
案例#2:
In [110]: A = np.random.rand(5000,100)
In [111]: B = np.random.rand(5000,100)
In [112]: %timeit corr2_coeff(A,B)
1 loops, best of 3: 368 ms per loop
In [113]: %timeit generate_correlation_map(A, B)
1 loops, best of 3: 493 ms per loop
案例#3:
In [114]: A = np.random.rand(10000,10)
In [115]: B = np.random.rand(10000,10)
In [116]: %timeit corr2_coeff(A,B)
1 loops, best of 3: 1.29 s per loop
In [117]: %timeit generate_correlation_map(A, B)
1 loops, best of 3: 1.83 s per loop
另一种基于循环pearsonr的方法似乎太慢,但这里是一个小数据的运行时 –
In [118]: A = np.random.rand(1000,100)
In [119]: B = np.random.rand(1000,100)
In [120]: %timeit corr2_coeff(A,B)
100 loops, best of 3: 15.3 ms per loop
In [121]: %timeit generate_correlation_map(A, B)
100 loops, best of 3: 19.7 ms per loop
In [122]: %timeit pearsonr_based(A,B)
1 loops, best of 3: 33 s per loop