2014-11-03 56 views
0

我有两个变量作为numpy数组,我想计算皮尔逊之间的相关性。在我的情况下,相关性已经过去了,每个数组都是一个时间步。Numpy Arrays Correlation

例如:

皮尔逊的X之间的相关性[0,0,0]和y [0,0,0],X [1,0,0]和Y [1,0,0]。 ..

对于每个元素。

最后我会得到一个相关结果的数组。

我的数组:

>>> print x 
[[[ 0 1] 
    [ 2 3] 
    [ 4 5] 
    [ 6 7]] 

[[ 8 9] 
    [10 11] 
    [12 13] 
    [14 15]] 

[[16 17] 
    [18 19] 
    [20 21] 
    [22 23]]] 

>>> print y 
[[[10 11] 
    [12 13] 
    [14 15] 
    [16 17]] 

[[18 19] 
    [20 21] 
    [22 23] 
    [24 25]] 

[[26 27] 
    [28 29] 
    [30 31] 
    [32 33]]] 
+1

http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.pearsonr.html – atomh33ls 2014-11-03 13:12:02

+0

我试试这个,但它是一个维数组。 – marcelorodrigues 2014-11-03 13:28:14

+1

你能举一个例子说明你想用可复制的代码显示你所尝试过的东西吗? – atomh33ls 2014-11-03 13:48:54

回答

0

对不起é先生,如果我是不清楚

我的阵列尺寸是:

print (x.shape) 
x = (20, 21, 22) 

print (y.shape) 
y = (20, 21, 22) 

所以,我解决了我的问题写下面的代码。

如果有人有更好的主意,让我知道!

import numpy as np 

def corr_pearson(x, y): 

    """ 
    Compute Pearson correlation. 
    """ 

    x_mean = np.mean(x, axis=0) 
    x_stddev = np.std(x, axis=0) 

    y_mean = np.mean(y, axis=0) 
    y_stddev = np.std(y, axis=0) 

    x1 = (x - x_mean)/x_stddev 
    y1 = (y - y_mean)/y_stddev 

    x1y1mult = x1 * y1 

    x1y1sum = np.sum(x1y1mult, axis=0) 

    corr = x1y1sum/20. 

    return corr