利用python库计算person相关系数

使用numpy库,可以实现person相关系数的计算,例如对于矩阵a。

a
Out[235]: 
array([[1, 1, 2, 2, 3],
       [2, 2, 3, 3, 5],
       [1, 4, 2, 2, 3]])

使用np.corrcoef(a)可计算行与行之间的相关系数,np.corrcoef(a,rowvar=0)用于计算各列之间的相关系数,输出为相关系数矩阵。

np.corrcoef(a)
Out[236]: 
array([[ 1.   ,  0.976,  0.105],
       [ 0.976,  1.   ,  0.179],
       [ 0.105,  0.179,  1.   ]])

np.corrcoef(a,rowvar=0)
Out[237]: 
array([[ 1.   , -0.189,  1.   ,  1.   ,  1.   ],
       [-0.189,  1.   , -0.189, -0.189, -0.189],
       [ 1.   , -0.189,  1.   ,  1.   ,  1.   ],
       [ 1.   , -0.189,  1.   ,  1.   ,  1.   ],
       [ 1.   , -0.189,  1.   ,  1.   ,  1.   ]])

应用公式0.5*value+0.5可以将相关系数矩阵的值域由[-1,1]映射为[0,1]。

np.corrcoef(a)*0.5+0.5
Out[238]: 
array([[ 1.   ,  0.988,  0.552],
       [ 0.988,  1.   ,  0.59 ],
       [ 0.552,  0.59 ,  1.   ]])


你可能感兴趣的:(python,库,相关系数,numpy)