<p>Pandas和Statsmodels版本之间的区别在于均值减和归一化/方差除:</p>
<ul>
<li><code>autocorr</code>只将原始序列的子序列传递给<code>np.corrcoef</code>。在该方法中,利用这些子序列的样本均值和样本方差来确定相关系数</li>
<li><code>acf</code>相反,使用总体序列样本均值和样本方差来确定相关系数。</li>
</ul>
<p>长时间序列的差异可能会变小,但短时间序列的差异会很大。</p>
<p>与Matlab相比,Pandas <code>autocorr</code>函数可能对应于对(滞后)序列本身进行Matlab s <code>xcorr</code>(交叉校正),而不是Matlab的<code>autocorr</code>,后者计算样本自相关(从文档中猜测;我无法验证这一点,因为我没有访问Matlab的权限)。</p>
<p>请参阅本MWE以获得澄清:</p>
<pre><code>import numpy as np
import pandas as pd
from statsmodels.tsa.stattools import acf
import matplotlib.pyplot as plt
plt.style.use("seaborn-colorblind")
def autocorr_by_hand(x, lag):
# Slice the relevant subseries based on the lag
y1 = x[:(len(x)-lag)]
y2 = x[lag:]
# Subtract the subseries means
sum_product = np.sum((y1-np.mean(y1))*(y2-np.mean(y2)))
# Normalize with the subseries stds
return sum_product / ((len(x) - lag) * np.std(y1) * np.std(y2))
def acf_by_hand(x, lag):
# Slice the relevant subseries based on the lag
y1 = x[:(len(x)-lag)]
y2 = x[lag:]
# Subtract the mean of the whole series x to calculate Cov
sum_product = np.sum((y1-np.mean(x))*(y2-np.mean(x)))
# Normalize with var of whole series
return sum_product / ((len(x) - lag) * np.var(x))
x = np.linspace(0,100,101)
results = {}
nlags=10
results["acf_by_hand"] = [acf_by_hand(x, lag) for lag in range(nlags)]
results["autocorr_by_hand"] = [autocorr_by_hand(x, lag) for lag in range(nlags)]
results["autocorr"] = [pd.Series(x).autocorr(lag) for lag in range(nlags)]
results["acf"] = acf(x, unbiased=True, nlags=nlags-1)
pd.DataFrame(results).plot(kind="bar", figsize=(10,5), grid=True)
plt.xlabel("lag")
plt.ylim([-1.2, 1.2])
plt.ylabel("value")
plt.show()
</code></pre>
<p><a href="https://i.stack.imgur.com/O3SNo.png" rel="noreferrer"><img src="https://i.stack.imgur.com/O3SNo.png" alt="enter image description here"/></a></p>
<p>Statsmodels使用<code>np.correlate</code>来优化它,但这基本上就是它的工作原理。</p>