计算两个multidimensional array之间的相关系数

NB当我说“相关系数”时，我的意思是Pearson乘积矩相关系数 。

• `numpy`函数`correlate`要求input数组是一维的。
• `numpy`函数`corrcoef`接受二维数组，但它们必须具有相同的形状。
• `scipy.stats`函数`pearsonr`要求input数组是一维的。

2 Solutions collect form web for “计算两个multidimensional array之间的相关系数”

` `out = np.dot(arr_one,arr_two.T)` `

` `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]))` `

` `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` `

` `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` `

` `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` `

` `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` `

@Divakar为计算未缩放的关联提供了一个很好的select，这正是我最初要求的。

` `import numpy as np def generate_correlation_map(x, y): """Correlate each n with each m. Parameters ---------- x : np.array Shape NX T. y : np.array Shape MX T. Returns ------- np.array NXM array in which each element is a correlation coefficient. """ mu_x = x.mean(1) mu_y = y.mean(1) n = x.shape[1] if n != y.shape[1]: raise ValueError('x and y must ' + 'have the same number of timepoints.') s_x = x.std(1, ddof=n - 1) s_y = y.std(1, ddof=n - 1) cov = np.dot(x, yT) - n * np.dot(mu_x[:, np.newaxis], mu_y[np.newaxis, :]) return cov / np.dot(s_x[:, np.newaxis], s_y[np.newaxis, :])` `

` `from scipy.stats import pearsonr def test_generate_correlation_map(): x = np.random.rand(10, 10) y = np.random.rand(20, 10) desired = np.empty((10, 20)) for n in range(x.shape[0]): for m in range(y.shape[0]): desired[n, m] = pearsonr(x[n, :], y[m, :])[0] actual = generate_correlation_map(x, y) np.testing.assert_array_almost_equal(actual, desired)` `
• 防止matplotlib中imshow的消除锯齿
• 如何在scipy / matplotlib中绘制和注释层次聚类树状图
• Python中的均方根误差
• 使用scipy计算matrix排名
• Scipy稀疏...数组？
• Python中的多重线性回归
• 浓缩距离matrix如何工作？ （pdist）
• 重新采样表示图像的numpy数组
• numpy.fft和scipy.fftpack有什么区别？
• 如何规范一个NumPy数组在一定的范围内？
• 将MATLAB代码转换为Python的工具