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

对于数据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.var和np.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]])

这里发生了什么?

解决方法:

这是因为,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 =无,rowvar = 1,偏差= 0,ddof =无),当没有提供偏差和ddof时,默认归一化为N-1,N为数字观察所以,这相当于delta的*度为1.不幸的是,np.var的默认值(a,axis = None,dtype = None,out = None,ddof = 0,keepdims = False)具有默认的delta度*0.

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

上一篇:python – Pandas DataFrame列与自定义函数的成对关联


下一篇:mysql