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

183. 为预测构建滞后 (lag) 和差分 (difference) 特征

MediumTime series

要使用普通模型预测明天的数值,你需要将序列转换为过去数值的行。缺少历史数据的行将被丢弃。

编写 make_features(series, lags) 函数,返回 (X, y)。对于每个具有所有滞后项可用性的时间 t (t >= max(lags)):
- 该行内容为 [series[t - L] for L in lags] + [series[t - 1] - series[t - 2]]
- 目标值 (target) 为 series[t]
假设 max(lags) >= 2。将 X 作为 2D float 数组返回,将 y 作为 1D float 数组返回。

函数def make_features(series, lags)

示例 1

输入: make_features([1.0, 2.0, 4.0, 7.0, 11.0], [1, 2])

输出: ([[2.0, 1.0, 1.0], [4.0, 2.0, 2.0], [7.0, 4.0, 3.0]], [4.0, 7.0, 11.0])

示例 2

输入: make_features([5.0, 7.0, 6.0, 9.0, 12.0, 11.0, 15.0], [1, 3])[0]

输出: [[6.0, 5.0, -1.0], [9.0, 7.0, 3.0], [12.0, 6.0, 3.0], [11.0, 9.0, -1.0]]

示例 3

输入: make_features([5.0, 7.0, 6.0, 9.0, 12.0, 11.0, 15.0], [1, 3])[1]

输出: [9.0, 12.0, 11.0, 15.0]

约束条件

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

让 t 从 max(lags) 开始。

提示 2

差分特征使用了 t - 1 和 t - 2,由于 max(lags) >= 2,这两者都是可用的。

常见错误
  • 在特征行中使用 series[t](如错误版本所示)会将答案泄露到输入中。
理解思路

像线性回归这样的普通模型无法理解时间,因此为了进行预测,你需要将序列转换为一张表:每一行包含过去的值,而目标值是当前的值。每个特征必须严格来自过去,否则模型会看到答案。就像仅使用昨天及更早的记录来预测今天的销售额一样。没有足够历史数据的行会被丢弃。

Worked example

series [1, 2, 4, 7, 11], lags [1, 2]。从 t = 2 开始。Row t = 2: [series[1], series[0]] = [2, 1], 加上 diff series[1] - series[0] = 1, target 4。Row t = 3: [4, 2] 加上 diff 2, target 7。Row t = 4: [7, 4] 加上 diff 3, target 11。因此 X = [[2, 1, 1], [4, 2, 2], [7, 4, 3]] 且 y = [4, 7, 11]。

对于 t >= max(lags), row = [series[t - L] for L in lags] + [series[t - 1] - series[t - 2]], target = series[t]。使用梯度提升树进行需求预测时通常会使用此类特征。
主题
Time series
相似题目
  • 使用自相关性寻找每周模式Medium
  • 使用 Holt's linear smoothing 预测趋势序列Medium
  • 计算平均绝对比例误差Medium
  • 将序列分解为趋势、季节性和残差Medium
所有 Time series 道题目
反馈
183 / 903
Python 3solution.pyPython 空闲
1
2
3
4
5
6
import numpy as np
​
def make_features(series, lags):
# your code here
pass
​
make_features([5.0, 7.0, 6.0, 9.0, 12.0, 11.0, 15.0], [1, 3])[0]

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

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

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