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

187. 将序列分解为趋势、季节性和残差

MediumTime series

重要性 LLM API 的每日流量具有很强的周周期性,容量规划人员会首先将其剔除。

加法分解认为 x = trend + seasonal + residual。

编写 decompose(x, p),其中 p 为奇数周期。Trend 是宽度为 p 的中心移动平均(前 p // 2 个点和最后 p // 2 个点为 NaN)。去趋势后的 d = x - trend。相位 k 的 seasonal 值是所有满足 t % p == k 的索引 t 处 d 的均值(忽略 NaN),然后进行中心化处理使这 p 个值的总和为 0。Seasonal 是在整个序列中重复该模式。Residual = x - trend - seasonal。返回 (trend, seasonal, residual)。

函数def decompose(x, p)

示例 1

输入: x = [1, 2, 3, 1, 2, 3, 1, 2, 3], p = 3

输出: trend 2 inside, seasonal [-1, 0, 1] repeated, residual 0 inside

约束条件

  • Python 3 with NumPy. Code runs in your browser.
  • Your code must pass all 3 tests to be accepted.
提示 1

np.convolve(x, np.ones(p) / p, mode='valid') 可以得到中间部分的移动平均。

提示 2

中心移动平均会在两端留下 p // 2 个 NaN。

提示 3

对每个相位 k,使用 d[k::p] 并配合 nanmean。

提示 4

在平铺(tiling)模式之前先进行中心化。

常见错误
  • 没有对 seasonal 模式进行中心化。
  • 使用了滞后窗口(trailing window),这会导致趋势发生偏移。
理解思路

加法分解将序列分为三个部分:缓慢变化的趋势、重复的季节性模式以及剩余的部分。一个周期内的中心移动平均可以抵消季节性波动。

Worked example

x = [0, 2, 4, 3, 5, 7], p = 3。t = 1 处的 trend 为 (0 + 2 + 4) / 3 = 2,随后 t = 2, 3, 4 处的 trend 分别为 3, 4, 5;首尾点为 NaN。t = 1 到 4 的去趋势值 d 为 [0, 1, -1, 0]。按 t % 3 分组:相位 0 仅有 t = 3,结果为 -1;相位 1 有 t = 1 和 4,结果为 0;相位 2 有 t = 2,结果为 1。模式 [-1, 0, 1] 的总和已经为 0。将其重复应用;内部的 residual 为 0。

trend = 宽度为 p 的中心均值(两端各 p // 2 个点为 NaN);d = x - trend;seasonal 相位 k = 所有满足 t % p == k 的非 NaN d 的均值;减去这 p 个值的均值使其总和为 0;residual = x - trend - seasonal。应用于:预测流水线。
Shape 与数据流
x (n,) -> trend (n,) with p//2 NaN at each end
d = x - trend -> phase means pat (p,) -> seasonal = tile(pat) (n,)
主题
Time series
相似题目
  • 为预测构建滞后 (lag) 和差分 (difference) 特征Medium
  • 使用自相关性寻找每周模式Medium
  • 使用 Holt's linear smoothing 预测趋势序列Medium
  • 计算平均绝对比例误差Medium
所有 Time series 道题目
反馈
187 / 903
Python 3solution.pyPython 空闲
1
2
3
4
5
6
import numpy as np
​
def decompose(x, p):
# your code here
pass
​

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

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