Numpy - 相关系数和相关的统计函数没有给出相同的结果

时间:2014-04-05 20:24:38

标签: python numpy statistics probability correlation

对于数据X = [0,0,1,1,0]Y = [1,1,0,1,1]

>> np.corrcoef(X,Y) 

返回

array([[ 1.        , -0.61237244],
       [-0.61237244,  1.        ]])

但是,根据http://docs.scipy.org/doc/numpy/reference/generated/numpy.corrcoef.html中显示的公式,我无法使用np.varnp.cov重现此结果:

>> np.cov([0,0,1,1,0],[1,1,0,1,1])/sqrt(np.var([0,0,1,1,0])*np.var([1,1,0,1,1]))

array([[ 1.53093109, -0.76546554],
       [-0.76546554,  1.02062073]])

这里发生了什么?

2 个答案:

答案 0 :(得分:4)

根据您的链接(http://docs.scipy.org/doc/numpy/reference/generated/numpy.corrcoef.html),您需要注意索引......

c = np.cov([0,0,1,1,0],[1,1,0,1,1])
corrcoef = [[ c[0,0]/np.sqrt(c[0,0]*c[0,0]), c[0,1]/np.sqrt(c[0,0]*c[1,1]) ],
           [ c[1,0]/np.sqrt(c[1,1]*c[0,0]), c[1,1]/np.sqrt(c[1,1]*c[1,1]) ]]

print corrcoef
# [[1.0, -0.61237243569579447], [-0.61237243569579447, 1.0]]

没错!

答案 1 :(得分:4)

这是因为,np.var默认的delta自由度为0,而不是1

In [57]:

X = [0,0,1,1,0]
Y = [1,1,0,1,1]
np.corrcoef(X,Y) 
Out[57]:
array([[ 1.        , -0.61237244],
       [-0.61237244,  1.        ]])
In [58]:

V = np.sqrt(np.array([np.var(X, ddof=1), np.var(Y, ddof=1)])).reshape(1,-1)
np.matrix(np.cov(X,Y))
Out[58]:
matrix([[ 0.3 , -0.15],
        [-0.15,  0.2 ]])
In [59]:

np.matrix(np.cov(X,Y))/(V*V.T)
Out[59]:
matrix([[ 1.        , -0.61237244],
        [-0.61237244,  1.        ]])

或者看起来是另一回事:

In [70]:

V=np.diag(np.cov(X,Y)).reshape(1,-1) #the diagonal elements
In [71]:

np.matrix(np.cov(X,Y))/np.sqrt(V*V.T)
Out[71]:
matrix([[ 1.        , -0.61237244],
        [-0.61237244,  1.        ]])

真实情况np.cov(m, y=None, rowvar=1, bias=0, ddof=None),当biasddof都未提供时,默认规范化为N-1,N为观察次数。所以,这相当于1的delta自由度。不幸的是,np.var(a, axis=None, dtype=None, out=None, ddof=0, keepdims=False)的默认值的默认delta自由度为0

每当不确定时,最安全的方法是抓住协方差矩阵的对角元素,而不是单独计算var,以确保一致的行为。