python中的相关矩阵

use*_*587 22 python

如何在python中计算相关矩阵?我有一个n维向量,其中每个元素有5维.例如,我的矢量看起来像

[
 [0.1, .32, .2,  0.4, 0.8], 
 [.23, .18, .56, .61, .12], 
 [.9,   .3,  .6,  .5,  .3], 
 [.34, .75, .91, .19, .21]
] 

在这种情况下,向量的维数为4,并且该向量的每个元素具有5维.如何以最简单的方式构建矩阵?

谢谢

unu*_*tbu 30

使用numpy,你可以使用np.corrcoef:

In [88]: import numpy as np

In [89]: np.corrcoef([[0.1, .32, .2, 0.4, 0.8], [.23, .18, .56, .61, .12], [.9, .3, .6, .5, .3], [.34, .75, .91, .19, .21]])
Out[89]: 
array([[ 1.        , -0.35153114, -0.74736506, -0.48917666],
       [-0.35153114,  1.        ,  0.23810227,  0.15958285],
       [-0.74736506,  0.23810227,  1.        , -0.03960706],
       [-0.48917666,  0.15958285, -0.03960706,  1.        ]])
Run Code Online (Sandbox Code Playgroud)


小智 10

如果您不想再次编写矩阵,也可以使用np.array.

import numpy as np
a = np.array([ [0.1, .32, .2,  0.4, 0.8], [.23, .18, .56, .61, .12], [.9,   .3,  .6,  .5,  .3],  [.34, .75, .91, .19, .21]]) 
b = np.corrcoef(a)
print b
Run Code Online (Sandbox Code Playgroud)

  • 如果想要列之间而不是行之间的相关性,则使用np.corrcoef(aT)。 (2认同)