假设我有一组向量(来自传感器1的读数,来自传感器2的读数,来自传感器3的读数 – 首先通过时间戳,然后通过传感器ID索引),我想将其与一组单独的向量相关联(温度) ,湿度等 – 也都是首先按时间戳索引,其次是按类型索引).
numpy最干净的方法是什么?看起来它应该是一个相当简单的功能……
换句话说,我想看到:
> a.shape
(365,20)
> b.shape
(365, 5)
> correlations = magic_correlation_function(a,b)
> correlations.shape
(20, 5)
干杯,
/ YGA
附:我被要求添加一个例子.
这是我想看到的:
$In [27]: x
$Out[27]:
array([[ 0, 0, 0],
[-1, 0, -1],
[-2, 0, -2],
[-3, 0, -3],
[-4, 0.1, -4]])
$In [28]: y
$Out[28]:
array([[0, 0],
[1, 0],
[2, 0],
[3, 0],
[4, 0.1]])
$In [28]: magical_correlation_function(x, y)
$Out[28]:
array([[-1. , 0.70710678, 1. ]
[-0.70710678, 1. , 0.70710678]])
Ps2:哎呀,错误地转录了我的例子.对不起.现在修复了.
最佳答案 我能找到的最简单的事情是使用scipy.stats包
In [8]: x
Out[8]:
array([[ 0. , 0. , 0. ],
[-1. , 0. , -1. ],
[-2. , 0. , -2. ],
[-3. , 0. , -3. ],
[-4. , 0.1, -4. ]])
In [9]: y
Out[9]:
array([[0. , 0. ],
[1. , 0. ],
[2. , 0. ],
[3. , 0. ],
[4. , 0.1]])
In [10]: import scipy.stats
In [27]: (scipy.stats.cov(y,x)
/(numpy.sqrt(scipy.stats.var(y,axis=0)[:,numpy.newaxis]))
/(numpy.sqrt(scipy.stats.var(x,axis=0))))
Out[27]:
array([[-1. , 0.70710678, -1. ],
[-0.70710678, 1. , -0.70710678]])
这些不是你得到的数字,但你已经混淆了你的行. (元素[0,0]应为1.)
一个更复杂,但纯粹是numpy的解决方案
In [40]: numpy.corrcoef(x.T,y.T)[numpy.arange(x.shape[1])[numpy.newaxis,:]
,numpy.arange(y.shape[1])[:,numpy.newaxis]]
Out[40]:
array([[-1. , 0.70710678, -1. ],
[-0.70710678, 1. , -0.70710678]])
这将更慢,因为它计算x中每个元素与x中的其他元素的相关性,这是您不想要的.此外,用于获取所需阵列子集的高级索引技术可能会让您头疼.
如果你要强烈使用numpy,请熟悉broadcasting和indexing的规则.它们将帮助你尽可能多地推进到C级.