gpt4 book ai didi

python - 将单个时间序列与大量时间序列相关联

转载 作者:行者123 更新时间:2023-12-01 04:39:39 26 4
gpt4 key购买 nike

我有大量 (M) 时间序列,每个时间序列都有 N 个时间点,存储在 MxN 矩阵中。然后,我还有一个包含 N 个时间点的单独时间序列,我希望将其与矩阵中的所有时间序列相关联。

一个简单的解决方案是逐行遍历矩阵并运行numpy.corrcoef。但是,我想知道是否有更快或更简洁的方法来做到这一点?

最佳答案

让我们使用这个相关性公式:

enter image description here

您可以将 X 实现为 M x N 数组,将 Y 实现为 N 的另一个独立时间序列数组 元素与 X 相关。因此,假设 XY 分别为 AB,矢量化实现将如下所示 -

import numpy as np

# Rowwise mean of input arrays & subtract from input arrays themeselves
A_mA = A - A.mean(1)[:,None]
B_mB = B - B.mean()

# Sum of squares across rows
ssA = (A_mA**2).sum(1)
ssB = (B_mB**2).sum()

# Finally get corr coeff
out = np.dot(A_mA,B_mB.T).ravel()/np.sqrt(ssA*ssB)
# OR out = np.einsum('ij,j->i',A_mA,B_mB)/np.sqrt(ssA*ssB)

验证结果 -

In [115]: A
Out[115]:
array([[ 0.1001229 , 0.77201334, 0.19108671, 0.83574124],
[ 0.23873773, 0.14254842, 0.1878178 , 0.32542199],
[ 0.62674274, 0.42252403, 0.52145288, 0.75656695],
[ 0.24917321, 0.73416177, 0.40779406, 0.58225605],
[ 0.91376553, 0.37977182, 0.38417424, 0.16035635]])

In [116]: B
Out[116]: array([ 0.18675642, 0.3073746 , 0.32381341, 0.01424491])

In [117]: out
Out[117]: array([-0.39788555, -0.95916359, -0.93824771, 0.02198139, 0.23052277])

In [118]: np.corrcoef(A[0],B), np.corrcoef(A[1],B), np.corrcoef(A[2],B)
Out[118]:
(array([[ 1. , -0.39788555],
[-0.39788555, 1. ]]),
array([[ 1. , -0.95916359],
[-0.95916359, 1. ]]),
array([[ 1. , -0.93824771],
[-0.93824771, 1. ]]))

关于python - 将单个时间序列与大量时间序列相关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30995062/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com