用numpy估计周期性的自相关方法

2024-10-05 20:06:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一套大的时间序列(>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

这将返回一组系数(r?)when plot应该告诉我时间序列是不是周期性的。在

我生成了两个玩具示例:

^{pr2}$

s1s2

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

Autocorr1Autocorr2

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

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 ..]

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


Tags: numpynormsizeifdefnp时间序列
1条回答
网友
1楼 · 发布于 2024-10-05 20:06:04

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

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

瞥一眼Durbin–Watson statistic,它与2(1-r)相似,表明人们认为它低于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

两个玩具示例的输出:

Appears to be not autocorrelated
Appears to be autocorrelated with r = 1.0, lag = 4

相关问题 更多 >