184. 使用自相关性寻找每周模式
滞后 k 的自相关性衡量了一个序列与其平移 k 步后的序列之间的相似程度。具有每周周期的交通流量序列在滞后 7 处会出现峰值。
使用标准估计量编写 autocorr(x, k):设 m = mean(x),r_k = sum over t from 0 to n - k - 1 of (x_t - m)(x_{t+k} - m) divided by sum over all t of (x_t - m) ** 2。
如果 k = 0,返回 1.0。如果序列是常数,返回 0.0。
def autocorr(x, k)示例 1
输入: x = [1.0, 2.0, 3.0, 4.0], k = 1
输出: 0.25
约束条件
- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 4 tests to be accepted.
提示 1
Centre the series once with the global mean, then compare it with a shifted copy of itself.
提示 2
Subtract the mean, compute the denominator as the sum of squared centred values, and the numerator as the sum of products of the overlapping parts.
提示 3
The overlapping parts are xc[:n - k] and xc[k:]; check for a zero denominator (constant series, return 0.0) before handling k == 0, and avoid xc[:-k], which breaks at k = 0.
常见错误
- 使用两个切片各自的均值进行相关性计算(错误的实现方式)是一个不同的量,并且会夸大短序列的自相关性。
理解思路
滞后 k 的自相关性衡量一个序列与其平移 k 步后的序列有多相似。数值接近 1 意味着模式在 k 步后重复,接近 -1 意味着模式反转,接近 0 意味着没有关联。就像注意到每个周一看起来都和上一个周一很像。标准估计量使用整个序列的均值和方差,而不是每个切片的均值和方差。
x = [1, 2, 1, 2], mean 1.5, deviations [-0.5, 0.5, -0.5, 0.5]. Denominator = 4 x 0.25 = 1. Lag 1: products (-0.5)(0.5) + (0.5)(-0.5) + (-0.5)(0.5) = -0.75, so r_1 = -0.75. Lag 2: (-0.5)(-0.5) + (0.5)(0.5) = 0.5, so r_2 = 0.5.
r_k = sum over t = 0..n-k-1 of (x_t - m)(x_{t+k} - m) divided by sum over all t of (x_t - m)^2. 对于 k = 0 返回 1.0,对于常数序列返回 0.0。ACF 图常用于识别交通或销售中的每周周期。