我正在测试一些
autocorrelation
Joe Kington
和
unubtu
前者使用
max
价值,而后者是价值
variance
.对于一些随机均匀数据,结果截然不同,如下所示。
import numpy as np
from statsmodels.tsa.stattools import acf
import matplotlib.pyplot as plt
def acorr_unutbu(x):
x = x - x.mean()
autocorr = np.correlate(x, x, mode='full')[-x.size:]
# Normalization
autocorr /= (x.var() * (np.arange(x.size, 0, -1)))
return autocorr
def acorr_joe(x):
x = x - x.mean()
# The original answer uses [x.size:], I changed it to [-x.size:] to match
# the size of the other function
autocorr = np.correlate(x, x, mode='full')[-x.size:]
# Normalization
autocorr /= autocorr.max()
return autocorr
N = 1000
data = np.random.rand(N)
ac_joe = acorr_joe(data)
ac_unubtu = acorr_unutbu(data)
fig, axes = plt.subplots(nrows=2)
axes[0].plot(ac_joe, label="joe")
axes[0].legend()
axes[1].plot(ac_unubtu, c='r', label="unutbu")
axes[1].legend()
plt.show()
statsmodels autocorrelation function
acf
,这表明Joe的答案(在上面的代码中有一个小的修改)可能使用了正确的规范化。
# Compare with statsmodels lags
lags = acf(data, nlags=N)
fig, axes = plt.subplots(nrows=2)
axes[0].plot(ac_joe - lags, label="joe - SM")
axes[0].set_ylim(-.5, .5)
axes[0].legend()
axes[1].plot(ac_unubtu - lags, c='r', label="unutbu - SM")
axes[1].set_ylim(-.5, .5)
axes[1].legend()
plt.show()