BLOGLLM Logo
Go Pro
Guest
Not signed in
所有博客课程练习面试准备系列标签书签价格
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboard游戏
Articles
练习 / Time series7 of 17 in topic

184. 使用自相关性寻找每周模式

MediumTime series

滞后 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 意味着没有关联。就像注意到每个周一看起来都和上一个周一很像。标准估计量使用整个序列的均值和方差,而不是每个切片的均值和方差。

Worked example

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 图常用于识别交通或销售中的每周周期。
主题
Time series
相似题目
  • 为预测构建滞后 (lag) 和差分 (difference) 特征Medium
  • 使用 Holt's linear smoothing 预测趋势序列Medium
  • 计算平均绝对比例误差Medium
  • 将序列分解为趋势、季节性和残差Medium
所有 Time series 道题目
反馈
184 / 903
Python 3solution.pyPython 空闲
1
2
3
4
5
6
import numpy as np
​
def autocorr(x, k):
# your code here
pass
​
autocorr(_x, 7)

此用例使用生成数据,因此按原样运行。按 + 添加你自己的用例。

Run 会在浏览器中检查这些用例,无需登录。 Submit 会检查所有 4 个测试。

Ctrl/按 + 回车 运行
© BlogLLM, Bengaluru, India关于条款隐私退款DMCA联系我们RSS