自相关以numpy估计周期性

Tit*_*llo 5 python numpy time-series correlation

我有大量的时间序列(> 500),我只想选择周期性的时间序列。我做了一些文献研究,发现应该寻找自相关。使用numpy我计算自相关为:

def autocorr(x):
    norm = x - np.mean(x)
    result = np.correlate(norm, norm, mode='full')
    acorr = result[result.size/2:]
    acorr /= ( x.var() * np.arange(x.size, 0, -1) )
    return acorr
Run Code Online (Sandbox Code Playgroud)

这将返回一组系数(r?),在绘制时应告诉我时间序列是否为周期性。

我生成了两个玩具示例:

#random signal
s1 = np.random.randint(5, size=80)
#periodic signal
s2 = np.array([5,2,3,1] * 20)
Run Code Online (Sandbox Code Playgroud)

s1 s2

生成自相关图时,我得到:

自动校正1 Autocorr2

第二个自相关向量清楚地表明了一些周期性:

Autocorr1 =  [1, 0.28, -0.06,  0.19, -0.22, -0.13,  0.07 ..]
Autocorr2 =  [1, -0.50, -0.49,  1, -0.50, -0.49,  1 ..]
Run Code Online (Sandbox Code Playgroud)

我的问题是,如何从自相关矢量自动确定时间序列是否为周期性?有没有一种方法可以将这些值汇总为单个系数,例如,如果= 1完美周期性,如果= 0则完全没有周期性。我试图计算平均值,但没有意义。我应该看看数字1吗?

小智 5

我将使用mode ='same'而不是mode ='full',因为使用mode ='full'时,我们得到了极端移位的协方差,其中只有1个数组元素与self重叠,其余为零。这些不会变得有趣。使用mode ='same'时,至少有一半的移位数组与原始数组重叠。

另外,要获得真实的相关系数(r),您需要除以重叠部分的大小,而不是除以原始x的大小。(在我的代码中是np.arange(n-1, n//2, -1))。然后,每个输出将在-1和1之间。

瞥一眼类似于2(1-r)的Durbin–Watson统计,表明人们认为其值小于1是自相关的重要指示,它对应于r> 0.5。这就是我在下面使用的。要对自相关的重要性进行统计上合理的处理,请参阅统计文献。一个起点就是为您的时间序列建立模型。

def autocorr(x):
    n = x.size
    norm = (x - np.mean(x))
    result = np.correlate(norm, norm, mode='same')
    acorr = result[n//2 + 1:] / (x.var() * np.arange(n-1, n//2, -1))
    lag = np.abs(acorr).argmax() + 1
    r = acorr[lag-1]        
    if np.abs(r) > 0.5:
      print('Appears to be autocorrelated with r = {}, lag = {}'. format(r, lag))
    else: 
      print('Appears to be not autocorrelated')
    return r, lag
Run Code Online (Sandbox Code Playgroud)

您的两个玩具示例的输出:

似乎不是自相关的
似乎是自相关的,r = 1.0,滞后= 4