Datasets:

Modalities:
Image
Size:
< 1K
Libraries:
Datasets
License:
xianbao zhongdongy commited on
Commit
20a07ea
·
1 Parent(s): 4b583b6

Review: version published on WeChat and Zhihu (#48)

Browse files

- Review: version published on WeChat and Zhihu (541e49ecc76e665cc3b1b8beac697a02866a1b89)


Co-authored-by: Zhongdong Yang <zhongdongy@users.noreply.huggingface.co>

Files changed (1) hide show
  1. time-series-transformers-cn.md +161 -127
time-series-transformers-cn.md CHANGED
@@ -19,74 +19,90 @@
19
 
20
  ## 介绍
21
 
22
- 时间序列预测是一个重要的科学和商业问题,因此最近通过使用[基于深度学习](https://dl.acm.org/doi/abs/10.1145/3533382) 而不是[经典方法](https://otexts.com/fpp3/)的模型也了很多创新。 ARIMA 等经典方法与新颖的深度学习方法之间的一个重要区别如下。
 
 
 
 
 
23
 
24
  ## 概率预测
25
 
26
- 通常,经典方法分别适用于数据集中的每个时间序列。这些通常被称为“单一”或“局部”方法。然而,当处理某些应用程序的大量时间序列时,在所有可用时间序列上训练一个“全局”模型是有益的,这使模型能够从许多不同的来源学习潜在的表示。
27
 
28
- 一些经典方法是点值的意思是,它们每个时间步只输出一个值,并且通过最小化关于地面数据的 L2 或 L1 类型的损失来训练模型。然而,由于预测经常用于实际决策流程中,即使有人在循环中,也提供预测的不确定性更加有益。这也称为“概率预测”,而不是“点预测”。这需要对概率分布进行建模,并从中进行采样
29
 
30
  所以简而言之,我们希望训练**全局概率**模型,而不是训练局部点预测模型。深度学习非常适合这一点,因为神经网络可以从几个相关的时间序列中学习表示,并对数据的不确定性进行建模。
31
 
32
- 在概率设中学习某些选定参数分布的未来参数很常见,例如高斯分布或 Student-T或者学习条件分位数函数或使用适应时间序列设置的 Conformal Prediction 框架。方法的选择不会影响建模方面,因此通常可以将其视为另一个超参数。通过采用经验均值或中值,人们总是可以将概率模型转变为点预测模型。
 
 
 
 
33
 
34
- ## 时间序列转换器
35
 
36
- 正如人们所想象的那样,在对本质上是连续的时间序列数据建模方面,研究人员提出了使用循环神经网络 (RNN)(如 LSTM 或 GRU)或卷积网络(CNN)以及最近基于 Transformer 的方法的模型这很自然地适合时间序列预测设置。
 
37
 
38
- 这篇博文中,我们将利用 vanilla Transformer [(Vaswani et al., 2017)](https://arxiv.org/abs/1706.03762) 进行**单变量**概率预测任务(即预测每个时间序列的维分布)。 Encoder-Decoder Transformer 是预测的自然选择,因为它很好地封装了几个归纳偏差
 
39
 
40
- 首先使用编码器-解码器架构在推理时很有帮助,通常对于一些记录的数据,我们希望预测未来的一些预测步骤。这以被认为类似于文本生成任务,在给定上情况下,我们下一个标记进行采样并将其传回解码器(也称为“自回归生成”)类似地,我们也可以在给定某种分布类型情况,从中抽样以提供预测,直到我们期望的预测范围。这被称为贪婪采/搜索[此处](https://huggingface.co/blog/how-to-generate) 有篇关NLP 设置精彩博文
41
 
42
- Transformer 帮助我们训练能包含数千个时间点的时间序列数据。由于注意力机制的时间和内存限制,一次*所有*时间序列的历史输入模型可能是不可行的。因此,在随机梯度下降 (SGD) 构建批次时,可以考虑一些适当文窗口并从训练数据中对该窗口和后续预测长度大小的窗口进行采样可以将上下文大小的窗口传递给编码器,将预测窗口传递给 *causal-masked* 解码器。意味着解码器在学习下一个值时只能查看之前的时间步长。这相当于人们如何训练用于机器翻译的 vanilla Transformer称为“教师强制”
43
 
44
- Transformers 相对其他架构的一个好处是,我们可以将失值(这在时间序列设置中很常见)作为编码器或解码器附加掩码并且仍然可以在不诉诸填充或插补情况下进行训练这相当Transformers 库中 BERT 和 GPT-2 等模型的“attention_mask”在注意力矩阵的计算中不包括填充标记
45
 
46
- 由于普通 Transformer 的二次计算和内存要求,Transformer 架构的一个缺点是上下文和预测窗口的大小受到限制,请参阅 [Tay 等人,2020](https://arxiv.org/abs /2009.06732)。此外,由于 Transformer 是一种强大架构,与其他 [方法](https://openreview.net/pdf?id=D7YBmfX_VQy) 相比,它可能会过度拟合或更容易学习虚假相关性。
 
 
 
47
 
48
- 🤗 Transformers 库带有一个普通的概率时间序列 Transformer 模型,简称为 [Time Series Transformer](https://huggingface.co/docs/transformers/model_doc/time_series_transformer)。在面的部分中,我们将展示如何在自定义数据集上训练此类模型。
 
 
 
49
 
50
 
51
  ## 设置环境
52
 
53
- 首先,让我们安装必要的库🤗 Transformers、🤗 Datasets、🤗 Evaluate、🤗 Accelerate 和 [GluonTS](https://github.com/awslabs/gluonts)。
54
 
55
- 正如我们将展示的那样,GluonTS 将用于转换数据以创建特征以及创建适当训练、验证和测试批次。
 
56
 
 
57
 
58
  ```python
59
  !pip install -q transformers
60
-
61
  !pip install -q datasets
62
-
63
  !pip install -q evaluate
64
-
65
  !pip install -q accelerate
66
-
67
  !pip install -q gluonts ujson
68
  ```
69
 
70
  ## 加载数据集
71
 
72
- 在这篇博文中,我们将使用 [Hugging Face Hub](https://huggingface.co/datasets/monash_tsf) 上提供的tourism_monthly数据集。该数据集包含澳大利亚 366 个地区的每月旅游量。
 
 
 
73
 
74
- 此数据集是 [Monash Time Series Forecasting](https://forecastingdata.org/) 存储库的一部分,该存储库是来自多个领域的时间序列数据集的集合。它可以看作是时间序列预测的 GLUE 基准。
75
 
 
 
76
 
77
  ```python
78
  from datasets import load_dataset
79
-
80
  dataset = load_dataset("monash_tsf", "tourism_monthly")
81
  ```
82
 
83
-
84
- 可以看出,数据集包含 3 个片段:训练、验证和测试。
85
-
86
 
87
  ```python
88
  dataset
89
-
90
  >>> DatasetDict({
91
  train: Dataset({
92
  features: ['start', 'target', 'feat_static_cat', 'feat_dynamic_real', 'item_id'],
@@ -104,8 +120,7 @@ dataset
104
  ```
105
 
106
 
107
- 每个示例都包含一些键,其中starttarget是最重要的键。让我们看一下数据集中的第一个时间序列
108
-
109
 
110
  ```python
111
  train_example = dataset['train'][0]
@@ -114,10 +129,9 @@ train_example.keys()
114
  >>> dict_keys(['start', 'target', 'feat_static_cat', 'feat_dynamic_real', 'item_id'])
115
  ```
116
 
117
- `start` 仅指示时间序列的开始(作日期时间),而 `ta​​rget` 包含时间序列的实际值。
118
-
119
- `start` 将有助于将时间相关的特征添加到时间序列值中,作为模型的额外输入(例如“一年中的月份”)。因为我们知道数据的频率是“每月”,所以知道例如第二个值的时间戳为“1979-02-01”,等等。
120
 
 
121
 
122
  ```python
123
  print(train_example['start'])
@@ -127,11 +141,9 @@ print(train_example['target'])
127
  [1149.8699951171875, 1053.8001708984375, ..., 5772.876953125]
128
  ```
129
 
 
130
 
131
- 验证集包含训练集相同的据,只是“prediction_length”的间更。这使我们能够根情况验证模型测。
132
-
133
- 与验证集相比,测试集还是一个“prediction_length”长数据(或者与用于在多个滚动窗口上进行测试的训练集相比,“prediction_length”长数据的若干倍)。
134
-
135
 
136
  ```python
137
  validation_example = dataset['validation'][0]
@@ -140,10 +152,7 @@ validation_example.keys()
140
  >>> dict_keys(['start', 'target', 'feat_static_cat', 'feat_dynamic_real', 'item_id'])
141
  ```
142
 
143
-
144
-
145
- 初始值与相应的训练示例完全相同:
146
-
147
 
148
  ```python
149
  print(validation_example['start'])
@@ -153,8 +162,7 @@ print(validation_example['target'])
153
  [1149.8699951171875, 1053.8001708984375, ..., 5985.830078125]
154
  ```
155
 
156
- 但是,与训练示例相比,此示例具有prediction_length=24”附加值。让我们验证一下。
157
-
158
 
159
  ```python
160
  freq = "1M"
@@ -163,8 +171,7 @@ prediction_length = 24
163
  assert len(train_example['target']) + prediction_length == len(validation_example['target'])
164
  ```
165
 
166
- 让我们可视化一下
167
-
168
 
169
  ```python
170
  import matplotlib.pyplot as plt
@@ -176,11 +183,9 @@ axes.plot(validation_example['target'], color="red", alpha=0.5)
176
  plt.show()
177
  ```
178
 
179
- ![png](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/time-series-transformers/output_21_0.png)
180
-
181
-
182
- 让我们拆分数据:
183
 
 
184
 
185
  ```python
186
  train_dataset = dataset["train"]
@@ -189,8 +194,7 @@ test_dataset = dataset["test"]
189
 
190
  ## 将 `start` 更新为 `pd.Period`
191
 
192
- 我们要做的第一件事是使用数据的 `freq` 将每个时间序列的 `start` 特征转换为 pandas `Period` 索引
193
-
194
 
195
  ```python
196
  from functools import lru_cache
@@ -207,7 +211,10 @@ def transform_start_field(batch, freq):
207
  return batch
208
  ```
209
 
210
- 我们现在使用 `datasets`' [`set_transform`](https://huggingface.co/docs/datasets/v2.7.0/en/package_reference/main_classes#datasets.Dataset.set_transform) 功能执行此操作:
 
 
 
211
 
212
  ```python
213
  from functools import partial
@@ -218,19 +225,19 @@ test_dataset.set_transform(partial(transform_start_field, freq=freq))
218
 
219
  ## 定义模型
220
 
221
- 接下来,让我们实例化一个模型。该模型将从头开始训练,因此我们不会在这里使用`from_pretrained`方法,而是从[`config`](https://huggingface.co/docs/transformers/model_doc/time_series_transformer #transformers.TimeSeriesTransformerConfig)中随机初始化模型。
222
 
223
- 我们为模型指定了几个附加参数
224
- - `prediction_length`在我们的例子中`24` 个月):这是 Transformer 的解码器将学习预测的范围
225
- - `context_length`如果未指定 `context_length`,模型会将 `context_length`编码器的输入设置为等于 `prediction_length`
226
- - 给定频率的滞后”:些指我们“回头看”的程度,作为附加功能添加。例如对于“每日”频率,我们可能会考虑回顾[1, 2, 7, 30, ...]或者换句话说,回顾 1, 2, ... 天,而对于“分钟”数据,我们可能会考虑 `[1, 30, 60, 60*24, ...]` 等
227
- - 时间特征的数量在我们的例子中,这将是“2,因为我们将添加MonthOfYearAge特征
228
- - 静态类特征的数量在我们的例子中,这将只是1,因为我们将添加一个“时间序列 ID”特征
229
- - 基数每个静态类特征的值的数量,作为一个列表,对于我们的案例来说将是[366],因为我们有 366 个不同的时间序列
230
- - 嵌入维度每个静态类特征的嵌入维度,作为列表例如[3]意味着模型将为每个366时间区域学习大小为3的嵌入向量.
231
 
232
 
233
- 让我们使用 GluonTS 为给定频率“每月”提供的默认滞后
234
 
235
 
236
  ```python
@@ -243,10 +250,9 @@ print(lags_sequence)
243
  ```
244
 
245
 
246
- 这意味着我们将回顾每个时间步长达 37 个月的时间,作为附加功能
247
-
248
- 我们还检查 GluonTS 为我们提供的默认时间功能:
249
 
 
250
 
251
  ```python
252
  from gluonts.time_feature import time_features_from_frequency_str
@@ -257,11 +263,9 @@ print(time_features)
257
  >>> [<function month_of_year at 0x7fa496d0ca70>]
258
  ```
259
 
 
260
 
261
- 在这种情况下,只有一个特征,即“一年中的月份”。这意味着对于每个时间步长,我们将添加月份作为标量值(例如,如果时间戳为“一月”,则为“1”;如果时间戳为“二月”,则为“2”,等等)。
262
-
263
- 我们现在拥有定义模型的一切:
264
-
265
 
266
  ```python
267
  from transformers import TimeSeriesTransformerConfig, TimeSeriesTransformerForPrediction
@@ -281,7 +285,10 @@ config = TimeSeriesTransformerConfig(
281
  model = TimeSeriesTransformerForPrediction(config)
282
  ```
283
 
284
- 请注意,与 🤗 Transformers 库中的其他模型类似,[`TimeSeriesTransformerModel`](https://huggingface.co/docs/transformers/model_doc/time_series_transformer#transformers.TimeSeriesTransformerModel) 对应于没有任何部的编码器-解码器 Transformer顶部并且 [`TimeSeriesTransformerForPrediction`](https://huggingface.co/docs/transformers/model_doc/time_series_transformer#transformers.TimeSeriesTransformerForPrediction) 对应于顶部有一个 **distribution head** 的 `TimeSeriesTransformerModel`。默认情况下,该模型使用 Student-t 分布(但这是可配置的):
 
 
 
285
 
286
  ```python
287
  model.config.distribution_output
@@ -289,14 +296,13 @@ model.config.distribution_output
289
  >>> student_t
290
  ```
291
 
292
- 这是与用于 NLP 的 Transformers 的一个重要区别,其中头部通常由一个固定的分类分布组成,实现为 `nn.Linear` 层。
293
 
294
  ## 定义转换
295
 
296
- 接下来,我们定义数据的转换,特别时间特征的创建(基于数据集或通用数据集
297
-
298
- 同样,我们将为此使用 GluonTS 库。我们定义了一个“转换链”(有点类似于图像的“torchvision.transforms.Compose”)。它允许我们将多个转换组合到一个流水线中。
299
 
 
300
 
301
  ```python
302
  from gluonts.time_feature import time_features_from_frequency_str, TimeFeature, get_lags_for_frequency
@@ -320,7 +326,7 @@ from gluonts.transform import (
320
  )
321
  ```
322
 
323
- 下面的转换带有注释,以解释它们的作在高层次上,我们将迭代数据集的各个时间序列并添加/删除字段或特征
324
 
325
 
326
  ```python
@@ -333,11 +339,11 @@ def create_transformation(freq: str, config: PretrainedConfig) -> Transformation
333
  if config.num_dynamic_real_features == 0:
334
  remove_field_names.append(FieldName.FEAT_DYNAMIC_REAL)
335
 
336
- # a bit like torchvision.transforms.Compose
337
  return Chain(
338
- # step 1: remove static/dynamic fields if not specified
339
  [RemoveFields(field_names=remove_field_names)]
340
- # step 2: use static features if available, if not add dummy values
341
  + (
342
  [SetField(output_field=FieldName.FEAT_STATIC_CAT, value=[0])]
343
  if not config.num_static_categorical_features > 0
@@ -348,7 +354,7 @@ def create_transformation(freq: str, config: PretrainedConfig) -> Transformation
348
  if not config.num_static_real_features > 0
349
  else []
350
  )
351
- # step 3: convert the data to NumPy (potentially not needed)
352
  + [
353
  AsNumpyArray(
354
  field=FieldName.FEAT_STATIC_CAT,
@@ -361,21 +367,21 @@ def create_transformation(freq: str, config: PretrainedConfig) -> Transformation
361
  ),
362
  AsNumpyArray(
363
  field=FieldName.TARGET,
364
- # in the following line, we add 1 for the time dimension
365
  expected_ndim=1 if config.input_size==1 else 2,
366
  ),
367
- # step 4: handle the NaN's by filling in the target with zero
368
- # and return the mask (which is in the observed values)
369
- # true for observed values, false for nan's
370
- # the decoder uses this mask (no loss is incurred for unobserved values)
371
- # see loss_weights inside the xxxForPrediction model
372
  AddObservedValuesIndicator(
373
  target_field=FieldName.TARGET,
374
  output_field=FieldName.OBSERVED_VALUES,
375
  ),
376
- # step 5: add temporal features based on freq of the dataset
377
- # month of year in this case
378
- # these serve as positional encodings
379
  AddTimeFeatures(
380
  start_field=FieldName.START,
381
  target_field=FieldName.TARGET,
@@ -383,22 +389,22 @@ def create_transformation(freq: str, config: PretrainedConfig) -> Transformation
383
  time_features=time_features_from_frequency_str(freq),
384
  pred_length=config.prediction_length,
385
  ),
386
- # step 6: add another temporal feature (just a single number)
387
- # tells the model where in the life the value of the time series is
388
- # sort of running counter
389
  AddAgeFeature(
390
  target_field=FieldName.TARGET,
391
  output_field=FieldName.FEAT_AGE,
392
  pred_length=config.prediction_length,
393
  log_scale=True,
394
  ),
395
- # step 7: vertically stack all the temporal features
396
  VstackFeatures(
397
  output_field=FieldName.FEAT_TIME,
398
  input_fields=[FieldName.FEAT_TIME, FieldName.FEAT_AGE]
399
  + ([FieldName.FEAT_DYNAMIC_REAL] if config.num_dynamic_real_features > 0 else []),
400
  ),
401
- # step 8: rename to match HuggingFace names
402
  RenameFields(
403
  mapping={
404
  FieldName.FEAT_STATIC_CAT: "static_categorical_features",
@@ -415,9 +421,9 @@ def create_transformation(freq: str, config: PretrainedConfig) -> Transformation
415
 
416
  ## 定义 `InstanceSplitter`
417
 
418
- 对于训练/验证/测试,我们接下来创建一个InstanceSplitter,用于从数据集中对窗口进行采样因为,请记住,由于时间和内存限制,我们无法将整个历史值传递给 Transformer
419
 
420
- 实例拆分器从数据中随机采样大小为context_length和后续大小为prediction_length的窗口,并将past_future_键附加到各个窗口的任何时键。这确保了 `values` 被拆分为 `past_values` 和后续的 `future_values` 键,它们将分别用作编码器和解码器的输入。 `time_series_fields` 参数中的任何都会发生同样的情况���
421
 
422
 
423
  ```python
@@ -455,8 +461,7 @@ def create_instance_splitter(config: PretrainedConfig, mode: str, train_sampler:
455
 
456
  ## 创建 PyTorch 数据加载器
457
 
458
- 接下来是时候创建 PyTorch DataLoaders它允许我们拥有成批的输入输出)对 - 或者换句话说(`past_values``future_values`
459
-
460
 
461
  ```python
462
  from gluonts.itertools import Cyclic, IterableSlice, PseudoShuffled
@@ -576,7 +581,7 @@ test_dataloader = create_test_dataloader(
576
  )
577
  ```
578
 
579
- 让我们检查第一批
580
 
581
 
582
  ```python
@@ -595,16 +600,15 @@ for k,v in batch.items():
595
  ```
596
 
597
 
598
- 可以看出,我们没有将 `input_ids` 和 `attention_mask` 提供给编码器NLP 模型是这种情况,而是提供 `past_values`,以及 `past_observed_mask`、`past_time_features`、`static_categorical_features`和`static_real_features`。
599
 
600
- 解码器输入包括future_valuesfuture_observed_maskfuture_time_features。 `future_values` 可以看作 NLP 中的 `decoder_input_ids` 的等价物
601
- 我们参考 [docs](https://huggingface.co/docs/transformers/model_doc/time_series_transformer#transformers.TimeSeriesTransformerForPrediction.forward.past_values) 以获得对它们中每一个的详细解释。
602
 
603
- ## 前传
604
 
605
- 让我们对刚刚创建的批次执行一次前向传递:
606
 
607
- Let's perform a single forward pass with the batch we just created:
608
 
609
  ```python
610
  # perform forward pass
@@ -627,16 +631,18 @@ print("Loss:", outputs.loss.item())
627
  >>> Loss: 9.141253471374512
628
  ```
629
 
630
- 请注意,该模型正在返回损失。这是可能的,因为解码器会自动将future_values向右移动一个位置以获得标签。这允许计算预测和标签之间的损失
631
 
632
- 另请注意,解码器使用因果掩码预测未来,因为它需要预测的值在future_values张量中。
633
 
634
  ## 训练模型
635
 
636
  是时候训练模型了!我们将使用标准的 PyTorch 训练循环。
637
 
638
- 我们将在这里使用 🤗 [Accelerate](https://huggingface.co/docs/accelerate/index) 库,它会自动将模型、优化器和数据加载器放置在适当的“设备”上。
639
 
 
 
640
 
641
  ```python
642
  from accelerate import Accelerator
@@ -680,9 +686,9 @@ for epoch in range(40):
680
 
681
  在推理时,建议使用 `generate()` 方法进行自回归生成,类似于 NLP 模型。
682
 
683
- 预测涉及从测试实例采样器获数据,该采样器将数据集每个时间序列的最后一个“context_length”大小值窗口中采样,并将其传递给模型。请注意,我们将提前已知的future_time_features传递给解码器。
684
 
685
- 该模型将从预测分布中自回归采样一定数量的值,并将它们传回解码器以返回预测输出
686
 
687
  ```python
688
  model.eval()
@@ -701,9 +707,9 @@ for batch in test_dataloader:
701
  forecasts.append(outputs.sequences.cpu().numpy())
702
  ```
703
 
704
- 该模型输出一个形状张量`batch_size``number of samples``prediction length`
705
 
706
- 在这种情况下,我们将接下来 24 个月内获得 100 个可能的值(对于大小为 64 的批次中的每个示例):
707
 
708
 
709
  ```python
@@ -712,7 +718,7 @@ forecasts[0].shape
712
  >>> (64, 100, 24)
713
  ```
714
 
715
- 我们将垂直堆叠它们,以获得测试数据集中所有时间序列的预测
716
 
717
  ```python
718
  forecasts = np.vstack(forecasts)
@@ -721,7 +727,12 @@ print(forecasts.shape)
721
  >>> (366, 100, 24)
722
  ```
723
 
724
- 我们可以根据测试集中存在的样本值,根据真实情况评估生成的预测。我们使用我们为数据集中的每个时间序列
 
 
 
 
 
725
 
726
  ```python
727
  from evaluate import load
@@ -751,7 +762,6 @@ for item_id, ts in enumerate(test_dataset):
751
  smape_metrics.append(smape["smape"])
752
  ```
753
 
754
-
755
  ```python
756
  print(f"MASE: {np.mean(mase_metrics)}")
757
 
@@ -762,7 +772,7 @@ print(f"sMAPE: {np.mean(smape_metrics)}")
762
  >>> sMAPE: 0.17457818831512306
763
  ```
764
 
765
- 我们还可以绘制数据集中每个时间序列的单独指标,并观察到少数时间序列对最终测试指标的贡献很大
766
 
767
  ```python
768
  plt.scatter(mase_metrics, smape_metrics, alpha=0.3)
@@ -771,9 +781,9 @@ plt.ylabel("sMAPE")
771
  plt.show()
772
  ```
773
 
774
- ![png](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/time-series-transformers/output_scatter.png)
775
 
776
- 为了根据地面测试数据绘制任何时间序列的预测,我们定义了以下
777
 
778
  ```python
779
  import matplotlib.dates as mdates
@@ -815,38 +825,62 @@ def plot(ts_index):
815
  plt.show()
816
  ```
817
 
818
- 例如
819
 
820
  ```python
821
  plot(334)
822
  ```
823
 
824
- ![png](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/time-series-transformers/output_65_1.png)
825
 
826
- 我们如何与其他模型进行比较? [Monash Time Series Repository](https://forecastingdata.org/#results) 有一个测试集 MASE 指标的比较表我们可以将添加到
 
827
  |Dataset | SES| Theta | TBATS| ETS | (DHR-)ARIMA| PR| CatBoost | FFNN | DeepAR | N-BEATS | WaveNet| **Transformer** (Our) |
828
  |:------------------:|:-----------------:|:--:|:--:|:--:|:--:|:--:|:--:|:---:|:---:|:--:|:--:|:--:|
829
  |Tourism Monthly | 3.306 | 1.649 | 1.751 | 1.526| 1.589| 1.678 |1.699| 1.582 | 1.409 | 1.574| 1.482 | **1.361**|
830
 
831
- 请注意,使用我们的模型,我们击败了报告的所有其他模型另请参见相应 [paper](https://openreview.net/pdf?id=wEc1mgAjU-) 中的表 2,并且我们没有做任何超参数调整。我们刚刚训练Transformer 40 个
832
 
833
- 当然,我们需要小心,因为似乎 [“XGBoost 通常是您所需要的”](https://www.sciencedirect.com/科学/章/pii/S0169207021001679)。我们只是很好奇,想看看神经网络能给我们带来多远,以及 Transformer 是否会在这个领域发挥作用。这个特定的数据集似乎表明它绝对值得探索。
 
 
 
 
 
 
834
 
835
  ## 下一步
836
 
837
- 我们鼓励读者试 [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/time-series-transformers.ipynb) 和其他时间序列数据集来自 [Hub](https://huggingface.co/datasets/monash_tsf) 并替换适当的频率和预测长度参数。对于您的数据集,需要将它们转换为 GluonTS 使用约定在他们的文档 [此处](https://ts.gluon.ai/stable/tutorials/forecasting/extended_tutorial.html#What-在数据集中吗?)。我们还准备了一个示例笔记本,向您展示如何将数据集转换为 🤗 数据集格式 [此处](https://github.com/huggingface/notebooks/blob/main/examples/time_series_datasets.ipynb)。
 
 
 
 
 
 
 
 
 
 
 
 
838
 
 
839
 
840
- 正如时间序列研究人员所知,人们对基于 Transformer 模型应用于时间序列问题很感兴趣。 vanilla Transformer 只是众多基于注意力的模型之一,因此需要向库中添加更多模型
841
 
842
- 没有什么能阻止我们对多变量时间序列进行建模,但是为此需要使用多变量分布头来实例化模型。目前支持对角独立分布后续会增加其他多元分布。请继续关注未来的博客文章,其将包含教程
843
 
844
- 路线图上的另一件事是时间序列分类。这需要将带有分类头的时间序列模型添加到库中,例如用于异常检测任务。
 
845
 
846
- 当前模型假设存在日期时间和时间序列值这可能不是每个时间序列都存在的情况。例如,参见 [WOODS](https://woods-benchmarks.github.io/) 中的神经科学数集。因此需要对当前模型进行泛化使某输入在整个流水线中可选。
847
 
848
- 最后,NLP/视觉领域从[大型预训练模型](https://arxiv.org/abs/1810.04805) 中获益匪浅,但据我们所知,时间序列领域并非如此。基于 Transformer 的模型似乎是追求这一研究途径的明显选择,我们迫不及待地想看看研究人员和从业者会想出什么!
 
849
 
850
- >英文原文:[Probabilistic Time Series Forecasting with 🤗 Transformers](https://huggingface.co/blog/time-series-transformers)
851
 
852
- >译者:innovation64 (李洋)
 
 
 
19
 
20
  ## 介绍
21
 
22
+ 时间序列预测是一个重要的科学和商业问题,因此最近通过使用[基于深度学习](https://dl.acm.org/doi/abs/10.1145/3533382) 而不是[经典方法](https://otexts.com/fpp3/)的模型也出诸多创新。ARIMA 等经典方法与新颖的深度学习方法之间的一个重要区别如下。
23
+
24
+ - 关于基于深度学习进行时间序列预测的论文:
25
+ <url>https://dl.acm.org/doi/abs/10.1145/3533382</url>
26
+ - 《预测: 方法与实践》在线课本的中文版:
27
+ <url>https://otexts.com/fppcn/</url>
28
 
29
  ## 概率预测
30
 
31
+ 通常,经典方法针对数据集中的每个时间序列单独拟合。这些通常被称为“单一”或“局部”方法。然而,当处理某些应用程序的大量时间序列时,在所有可用时间序列上训练一个“全局”模型是有益的,这使模型能够从许多不同的来源学习潜在的表示。
32
 
33
+ 一些经典方法是点值的 (point-valued)(意思是每个时间步只输出一个值),并且通过最小化关于基本事实数据的 L2 或 L1 类型的损失来训练模型。然而,由于预测经常用于实际决策流程中,甚至在循环中有人的干预让模型同时也提供预测的不确定性更加有益。这也称为“概率预测”,而不是“点预测”。这需要对可以采样的概率分布进行建模。
34
 
35
  所以简而言之,我们希望训练**全局概率**模型,而不是训练局部点预测模型。深度学习非常适合这一点,因为神经网络可以从几个相关的时间序列中学习表示,并对数据的不确定性进行建模。
36
 
37
+ 在概率设中学习某些选定参数分布的未来参数很常见,例如高斯分布 (Gaussian) 或 Student-T或者学习条件分位数函数 (conditional quantile function),或使用适应时间序列设置的共型预测 (Conformal Prediction) 框架。方法的选择不会影响建模,因此通常可以将其视为另一个超参数。通过采用经验均值或中值,人们总是可以将概率模型转变为点预测模型。
38
+
39
+ ## 时间序列 Transformer
40
+
41
+ 正如人们所想象的那样,在对本来就连续的时间序列数据建模方面,研究人员提出了使用循环神经网络 (RNN) (如 LSTM 或 GRU) 或卷积网络 (CNN) 的模型,或利用最近兴起的基于 Transformer 的训练方法,都很自然地适合时间序列预测场景。
42
 
43
+ 在这篇博文中,我们将利用传统 vanilla Transformer [(参考 Vaswani 等 2017 年发表的论文)](https://arxiv.org/abs/1706.03762) 进行**单变量**概率预测 (univariate probabilistic forecasting) 任务 (即预测每个时间序列的一维分布) 。 由于 Encoder-Decoder Transformer 很好地封装了几个归纳偏差,所以它成为了我们预测的自然选择。
44
 
45
+ - 传统 vanilla Transformer 论文链接:
46
+ <url>https://arxiv.org/abs/1706.03762</url>
47
 
48
+ 首先,使用 Encoder-Decoder 架构推理时很有���助。通常对于一些记录的数据,我们希望提前预知未来的一些预测步骤。可以认为这个过程类似于文本生成任务,即给定上下文,采样下一个词元 (token) 并将其传回解码器 (也称为“自回归生成”) 。类似地,我们也可以在给定某种分布类型的情况下,从中抽样以提供预测,直到我们期望的预测范围。这被称为贪婪采样 (Greedy Sampling)/搜索,[此处](https://huggingface.co/blog/how-to-generate) 篇关于 NLP 场景预测的精彩博文
49
+ <url>https://hf.co/blog/how-to-generate</url>
50
 
51
+ 其次Transformer 帮助我们训练可能包含成千上万个时间点时间序列数据。由于注意力机制时间和内存限制,次性将 **所有** 时间序列的完整历史输入模型或许不太行。因此,在为随机梯度降 (SGD) 构建批次时,可以考虑适当文窗口大小并从训练数据中该窗口和后续预测长度大小的窗口进行采样。可以将调整过大小文窗口传递给编码器、预测窗口传递给 **causal-masked** 解码器。这样一来解码器在学习下个值时只能查看之前的时间步。这相当人们训练用于机器翻译的 vanilla Transformer 过程,称为“教师强制 (Teacher Forcing)”
52
 
53
+ Transformers 相对于他架构的另一个好处是,我们可缺失值 (这在时间序列场景中很常见) 作编码器或解码器的额外掩蔽值 (mask),并且仍然可以在不诉诸于填充或插补情况下进行训练。这相当于 Transformers 库中 BERT 和 GPT-2 等模型的 `attention_mask`在注意力矩阵 (attention matrix) 的计算中不包括填充词元
54
 
55
+ 传统 vanilla Transformer 的平方运算和内存要求,Transformer 架构的一个缺点是上下文和预测窗口大小受到限制。关于这一点,可以参阅 [Tay 等人 2020 年发表调研报告](https://arxiv.org/abs/2009.06732) 此外,由Transformer 是一种强大的架构,与 [其他方法](https://openreview.net/pdf?id=D7YBmfX_VQy) 相比它可能会过拟合或更容易学习虚假相关性
56
 
57
+ - Tay 等 2020 年发表调研报告地址:
58
+ <url>https://arxiv.org/abs/2009.06732</url>
59
+ - 上述关于其他预测时间线方法的论文地址:
60
+ <url>https://openreview.net/pdf?id=D7YBmfX_VQy</url>
61
 
62
+ 🤗 Transformers 库带有一个普通的概率时间序列 Transformer 模型,简称为 [Time Series Transformer](https://huggingface.co/docs/transformers/model_doc/time_series_transformer)。在这篇文章后面的内容中,我们将展示如何在自定义数据集上训练此类模型。
63
+
64
+ Time Series Transformer 模型文档:
65
+ <url>https://hf.co/docs/transformers/model_doc/time_series_transformer</url>
66
 
67
 
68
  ## 设置环境
69
 
70
+ 首先,让我们安装必要的库: 🤗 Transformers、🤗 Datasets、🤗 Evaluate、🤗 Accelerate 和 [GluonTS](https://github.com/awslabs/gluonts)。
71
 
72
+ GluonTS 的 GitHub 仓库:
73
+ <url>https://github.com/awslabs/gluonts</url>
74
 
75
+ 正如我们将展示的那样,GluonTS 将用于转换数据以创建特征以及创建适当的训练、验证和测试批次。
76
 
77
  ```python
78
  !pip install -q transformers
 
79
  !pip install -q datasets
 
80
  !pip install -q evaluate
 
81
  !pip install -q accelerate
 
82
  !pip install -q gluonts ujson
83
  ```
84
 
85
  ## 加载数据集
86
 
87
+ 在这篇博文中,我们将使用 [Hugging Face Hub](https://huggingface.co/datasets/monash_tsf) 上提供的 `tourism_monthly` 数据集。该数据集包含澳大利亚 366 个地区的每月旅游量。
88
+
89
+ `tourism_monthly` 数据集地址:
90
+ <url>https://hf.co/datasets/monash_tsf</url>
91
 
92
+ 此数据集是 [Monash Time Series Forecasting](https://forecastingdata.org/) 存储库的一部分,该存储库收纳了是来自多个领域的时间序列数据集。它可以看作是时间序列预测的 GLUE 基准。
93
 
94
+ Monash Time Series Forecasting 存储库链接:
95
+ <url>https://forecastingdata.org/</url>
96
 
97
  ```python
98
  from datasets import load_dataset
 
99
  dataset = load_dataset("monash_tsf", "tourism_monthly")
100
  ```
101
 
102
+ 可以看出,数据集包含 3 个片段: 训练、验证和测试。
 
 
103
 
104
  ```python
105
  dataset
 
106
  >>> DatasetDict({
107
  train: Dataset({
108
  features: ['start', 'target', 'feat_static_cat', 'feat_dynamic_real', 'item_id'],
 
120
  ```
121
 
122
 
123
+ 每个示例都包含一些键,其中 `start` `target` 是最重要的键。让我们看一下数据集中的第一个时间序列:
 
124
 
125
  ```python
126
  train_example = dataset['train'][0]
 
129
  >>> dict_keys(['start', 'target', 'feat_static_cat', 'feat_dynamic_real', 'item_id'])
130
  ```
131
 
132
+ `start` 仅指示时间序列的开始 (类型 `datetime`) ,而 `target` 包含时间序列的实际值。
 
 
133
 
134
+ `start` 将有助于将时间相关的特征添加到时间序列值中,作为模型的额外输入 (例如“一年中的月份”) 。因为我们已经知道数据的频率是 `每月`,所以也能推算第二个值的时间戳为 `1979-02-01`,等等。
135
 
136
  ```python
137
  print(train_example['start'])
 
141
  [1149.8699951171875, 1053.8001708984375, ..., 5772.876953125]
142
  ```
143
 
144
+ 验证集包含与训练集相同的数据,只是数据时间范围延长了 `prediction_length` 那么多。这使我们能够根据真实情况验证模型的预测。
145
 
146
+ 验证集相比,测试集还是比验证集多包含 `prediction_length` 时间的数据 (或者使用比训练集多出个 `prediction_length` 时长的测试集,现在多重滚动窗口上的测试任务)
 
 
 
147
 
148
  ```python
149
  validation_example = dataset['validation'][0]
 
152
  >>> dict_keys(['start', 'target', 'feat_static_cat', 'feat_dynamic_real', 'item_id'])
153
  ```
154
 
155
+ 验证的初始值与相应的训练示例完全相同:
 
 
 
156
 
157
  ```python
158
  print(validation_example['start'])
 
162
  [1149.8699951171875, 1053.8001708984375, ..., 5985.830078125]
163
  ```
164
 
165
+ 但是,与训练示例相比,此示例具有 `prediction_length=24` 个额外的数据。让我们验证一下。
 
166
 
167
  ```python
168
  freq = "1M"
 
171
  assert len(train_example['target']) + prediction_length == len(validation_example['target'])
172
  ```
173
 
174
+ 让我们可视化一下:
 
175
 
176
  ```python
177
  import matplotlib.pyplot as plt
 
183
  plt.show()
184
  ```
185
 
186
+ ![](https://man-archives.oss-cn-hangzhou.aliyuncs.com/goofan/output_21_0.png)
 
 
 
187
 
188
+ 下面拆分数据:
189
 
190
  ```python
191
  train_dataset = dataset["train"]
 
194
 
195
  ## 将 `start` 更新为 `pd.Period`
196
 
197
+ 我们要做的第一件事是根据数据的 `freq` 将每个时间序列的 `start` 特征转换为 pandas `Period` 索引:
 
198
 
199
  ```python
200
  from functools import lru_cache
 
211
  return batch
212
  ```
213
 
214
+ 这里我们使用 `datasets` [`set_transform`](https://huggingface.co/docs/datasets/v2.7.0/en/package_reference/main_classes#datasets.Dataset.set_transform) 来实现:
215
+
216
+ `set_transform` 文档地址:
217
+ <url>https://hf.co/docs/datasets/v2.7.0/en/package_reference/main_classes</url>
218
 
219
  ```python
220
  from functools import partial
 
225
 
226
  ## 定义模型
227
 
228
+ 接下来,让我们实例化一个模型。该模型将从头开始训练,因此我们不使用 `from_pretrained` 方法,而是从 [`config`](https://huggingface.co/docs/transformers/model_doc/time_series_transformer#transformers.TimeSeriesTransformerConfig) 中随机初始化模型。
229
 
230
+ 我们为模型指定了几个附加参数:
231
+ - `prediction_length` (在我们的例子中`24` 个月) : 这是 Transformer 的解码器将学习预测的范围;
232
+ - `context_length`: 如果未指定 `context_length`,模型会将 `context_length` (编码器的输入) 设置为等于 `prediction_length`;
233
+ - 给定频率的 `lags`(滞后): 将决模型“回头看”的程度,也会作为附加特征。例如对于 `Daily` 频率,我们可能会考虑回顾 `[1, 2, 7, 30, ...]`也就是回顾 12……的数据,而对于 Minute` 数据,我们可能会考虑 `[1, 30, 60, 60*24, ...]` 等;
234
+ - 时间特征的数量: 在我们的例子中设置为 `2`,因为我们将添加 `MonthOfYear` `Age` 特征;
235
+ - 静态类别型特征的数量: 在我们的例子中,这将只是 `1`,因为我们将添加一个“时间序列 ID”特征;
236
+ - 基数: 将每个静态类别型特征的值的数量构成一个列表,对于例来说将是 `[366]`,因为我们有 366 个不同的时间序列;
237
+ - 嵌入维度: 每个静态类别型特征的嵌入维度,也是构成列表例如 `[3]` 意味着模型将为每个 ``366` 时间��� (区域) 学习大小为 `3` 的嵌入向量
238
 
239
 
240
+ 让我们使用 GluonTS 为给定频率 (“每月”) 提供的默认滞后值:
241
 
242
 
243
  ```python
 
250
  ```
251
 
252
 
253
+ 这意味着我们每个时间步将回顾长达 37 个月的数据,作为附加特征
 
 
254
 
255
+ 我们还检查 GluonTS 为我们提供的默认时间特征:
256
 
257
  ```python
258
  from gluonts.time_feature import time_features_from_frequency_str
 
263
  >>> [<function month_of_year at 0x7fa496d0ca70>]
264
  ```
265
 
266
+ 在这种情况下,只有一个特征,即“一年中的月份”。这意味着对于每个时间步长,我们将添加月份作为标量值 (例如,如果时间戳为 "january",则为 `1`;如果时间戳为 "february",则为 `2`,等等) 。
267
 
268
+ 我们现在准备好定义模型需要的所有内容了:
 
 
 
269
 
270
  ```python
271
  from transformers import TimeSeriesTransformerConfig, TimeSeriesTransformerForPrediction
 
285
  model = TimeSeriesTransformerForPrediction(config)
286
  ```
287
 
288
+ 请注意,与 🤗 Transformers 库中的其他模型类似,[`TimeSeriesTransformerModel`](https://huggingface.co/docs/transformers/model_doc/time_series_transformer#transformers.TimeSeriesTransformerModel) 对应于没有任何前置头的编码器-解码器 Transformer, [`TimeSeriesTransformerForPrediction`](https://huggingface.co/docs/transformers/model_doc/time_series_transformer#transformers.TimeSeriesTransformerForPrediction) 对应于顶部有一个分布前置头 (**distribution head**) 的 `TimeSeriesTransformerModel`。默认情况下,该模型使用 Student-t 分布 (也以自行配置):
289
+
290
+ 上述两个模型的文档链接:
291
+ <url>https://hf.co/docs/transformers/model_doc/time_series_transformer</url>
292
 
293
  ```python
294
  model.config.distribution_output
 
296
  >>> student_t
297
  ```
298
 
299
+ 这是具体实现层面与用于 NLP 的 Transformers 的一个重要区别,其中头部通常由一个固定的分类分布组成,实现为 `nn.Linear` 层。
300
 
301
  ## 定义转换
302
 
303
+ 接下来,我们定义数据的转换,尤其需要基于样本数据集或通用数据集来创建其中的时间特征
 
 
304
 
305
+ 同样,我们用到了 GluonTS 库。这里定义了一个 `Chain` (有点类似于图像训练的 `torchvision.transforms.Compose`) 。它允许我们将多个转换组合到一个流水线中。
306
 
307
  ```python
308
  from gluonts.time_feature import time_features_from_frequency_str, TimeFeature, get_lags_for_frequency
 
326
  )
327
  ```
328
 
329
+ 下面的转换代码带有注释供大家查看具体步骤从全局来说,我们将迭代数据集的各个时间序列并添加删除某些字段或特征:
330
 
331
 
332
  ```python
 
339
  if config.num_dynamic_real_features == 0:
340
  remove_field_names.append(FieldName.FEAT_DYNAMIC_REAL)
341
 
342
+ # 类似 torchvision.transforms.Compose
343
  return Chain(
344
+ # 步骤 1: 如果静态或动态字段没有特殊声明���则将它们移除
345
  [RemoveFields(field_names=remove_field_names)]
346
+ # 步骤 2: 如果静态特征存在,就直接使用,否则添加一些虚拟值
347
  + (
348
  [SetField(output_field=FieldName.FEAT_STATIC_CAT, value=[0])]
349
  if not config.num_static_categorical_features > 0
 
354
  if not config.num_static_real_features > 0
355
  else []
356
  )
357
+ # 步骤 3: 将数据转换为 NumPy 格式 (应该用不上)
358
  + [
359
  AsNumpyArray(
360
  field=FieldName.FEAT_STATIC_CAT,
 
367
  ),
368
  AsNumpyArray(
369
  field=FieldName.TARGET,
370
+ # 接下来一行我们为时间维度的数据加上 1
371
  expected_ndim=1 if config.input_size==1 else 2,
372
  ),
373
+ # 步骤 4: 目标值遇到 NaN 时,用 0 填充
374
+ # 然后返回观察值的掩蔽值
375
+ # 存在观察值时为 true,NaN 时为 false
376
+ # 解码器会使用这些掩蔽值 (遇到非观察值时不会产生损失值)
377
+ # 具体可以查看 xxxForPrediction 模型的 loss_weights 说明
378
  AddObservedValuesIndicator(
379
  target_field=FieldName.TARGET,
380
  output_field=FieldName.OBSERVED_VALUES,
381
  ),
382
+ # 步骤 5: 根据数据集的 freq 字段添加暂存值
383
+ # 也就是这里的“一年中的月份”
384
+ # 这些暂存值将作为定位编码使用
385
  AddTimeFeatures(
386
  start_field=FieldName.START,
387
  target_field=FieldName.TARGET,
 
389
  time_features=time_features_from_frequency_str(freq),
390
  pred_length=config.prediction_length,
391
  ),
392
+ # 步骤 6: 添加另一个暂存值 (一个单一数字)
393
+ # 用于让模型知道当前值在时间序列中的位置
394
+ # 类似于一个步进计数器
395
  AddAgeFeature(
396
  target_field=FieldName.TARGET,
397
  output_field=FieldName.FEAT_AGE,
398
  pred_length=config.prediction_length,
399
  log_scale=True,
400
  ),
401
+ # 步骤 7: 将所有暂存特征值纵向堆叠
402
  VstackFeatures(
403
  output_field=FieldName.FEAT_TIME,
404
  input_fields=[FieldName.FEAT_TIME, FieldName.FEAT_AGE]
405
  + ([FieldName.FEAT_DYNAMIC_REAL] if config.num_dynamic_real_features > 0 else []),
406
  ),
407
+ # 步骤 8: 建立字段名和 Hugging Face 惯用字段名之间的映射
408
  RenameFields(
409
  mapping={
410
  FieldName.FEAT_STATIC_CAT: "static_categorical_features",
 
421
 
422
  ## 定义 `InstanceSplitter`
423
 
424
+ 对于训练验证测试步骤,接下来我们创建一个 `InstanceSplitter`,用于从数据集中对窗口进行采样 (因为由于时间和内存限制,我们无法将整个历史值传递给 Transformer)
425
 
426
+ 实例拆分器从数据中随机采样大小为 `context_length` 和后续大小为 `prediction_length` 的窗口,并将 `past_` `future_` 键附加到各个窗口的任何时键。这确保了 `values` 被拆分为 `past_values` 和后续的 `future_values` 键,它们将分别用作编码器和解码器的输入。同样我们还需要修改 `time_series_fields` 参数中的所有:
427
 
428
 
429
  ```python
 
461
 
462
  ## 创建 PyTorch 数据加载器
463
 
464
+ 有了数据下一步需要创建 PyTorch DataLoaders它允许我们批量处理成对 (输入, 输出) 数据,即 (`past_values` , `future_values`)
 
465
 
466
  ```python
467
  from gluonts.itertools import Cyclic, IterableSlice, PseudoShuffled
 
581
  )
582
  ```
583
 
584
+ 让我们检查第一批:
585
 
586
 
587
  ```python
 
600
  ```
601
 
602
 
603
+ 可以看出,我们没有将 `input_ids` 和 `attention_mask` 提供给编码器 (训练 NLP 模型时也是这种情况),而是提供 `past_values`,以及 `past_observed_mask`、`past_time_features`、`static_categorical_features` `static_real_features` 几项数据
604
 
605
+ 解码器输入包括 `future_values``future_observed_mask` `future_time_features`。 `future_values` 可以看作等同于 NLP 训练中的 `decoder_input_ids`。
 
606
 
607
+ 我们可以参考 [Time Series Transformer 文档](https://huggingface.co/docs/transformers/model_doc/time_series_transformer#transformers.TimeSeriesTransformerForPrediction.forward.past_values) 以获得对它们中每一个的详细解释。
608
 
609
+ ## 前向传
610
 
611
+ 让我们对刚刚创建的批次执行一次前向传播:
612
 
613
  ```python
614
  # perform forward pass
 
631
  >>> Loss: 9.141253471374512
632
  ```
633
 
634
+ 目前,该模型返回损失。这是由于解码器会自动将 `future_values` 向右移动一个位置以获得标签。这允许计算预测结果和标签之间的误差
635
 
636
+ 另请注意,解码器使用 Causal Mask 避免预测未来,因为它需要预测的值在 `future_values` 张量中。
637
 
638
  ## 训练模型
639
 
640
  是时候训练模型了!我们将使用标准的 PyTorch 训练循环。
641
 
642
+ 这里我们到了 🤗 [Accelerate](https://huggingface.co/docs/accelerate/index) 库,它会自动将模型、优化器和数据加载器放置在适当的 `device` 上。
643
 
644
+ 🤗 Accelerate 文档地址:
645
+ <url>https://hf.co/docs/accelerate/index</url>
646
 
647
  ```python
648
  from accelerate import Accelerator
 
686
 
687
  在推理时,建议使用 `generate()` 方法进行自回归生成,类似于 NLP 模型。
688
 
689
+ 预测的过程会从测试实例采样器数据采样器将数据集每个时间序列的最后 `context_length` 那么长时间数据采样出来然后输入模型。请注意,这里需要把提前已知的 `future_time_features` 传递给解码器。
690
 
691
+ 该模型将从预测分布中自回归采样一定数量的值,并将它们传回解码器最终得到预测输出:
692
 
693
  ```python
694
  model.eval()
 
707
  forecasts.append(outputs.sequences.cpu().numpy())
708
  ```
709
 
710
+ 该模型输出一个表示结构的张量 (`batch_size`, `number of samples`, `prediction length`)
711
 
712
+ 面的输出说明: 对于大小为 64 的批次中的每个示例,我们将获得接下来 24 个月内 100 个可能的值:
713
 
714
 
715
  ```python
 
718
  >>> (64, 100, 24)
719
  ```
720
 
721
+ 我们将垂直堆叠它们,以获得测试数据集中所有时间序列的预测:
722
 
723
  ```python
724
  forecasts = np.vstack(forecasts)
 
727
  >>> (366, 100, 24)
728
  ```
729
 
730
+ 我们可以根据测试集中存在的样本值,根据真实情况评估生成的预测。这里我们使用数据集中的每个时间序列的 [MASE](https://huggingface.co/spaces/evaluate-metric/mase) 和 [sMAPE](https://hf.co/spaces/evaluate-metric/smape) 指标 (metrics) 来评估:
731
+
732
+ - MASE 文档地址:
733
+ <url>https://hf.co/spaces/evaluate-metric/mase</url>
734
+ - sMAPE 文档地址:
735
+ <url>https://hf.co/spaces/evaluate-metric/smape</url>
736
 
737
  ```python
738
  from evaluate import load
 
762
  smape_metrics.append(smape["smape"])
763
  ```
764
 
 
765
  ```python
766
  print(f"MASE: {np.mean(mase_metrics)}")
767
 
 
772
  >>> sMAPE: 0.17457818831512306
773
  ```
774
 
775
+ 我们还可以单独绘制数据集中每个时间序列的结果指标,并观察到其中少数时间序列对最终测试指标的影响很大:
776
 
777
  ```python
778
  plt.scatter(mase_metrics, smape_metrics, alpha=0.3)
 
781
  plt.show()
782
  ```
783
 
784
+ ![](https://man-archives.oss-cn-hangzhou.aliyuncs.com/goofan/output_scatter.png)
785
 
786
+ 为了根据基本事实测试数据绘制任何时间序列的预测,我们定义了以下辅助绘图函数:
787
 
788
  ```python
789
  import matplotlib.dates as mdates
 
825
  plt.show()
826
  ```
827
 
828
+ 例如:
829
 
830
  ```python
831
  plot(334)
832
  ```
833
 
834
+ ![](https://man-archives.oss-cn-hangzhou.aliyuncs.com/goofan/output_65_1.png)
835
 
836
+ 我们如何与其他模型进行比较? [Monash Time Series Repository](https://forecastingdata.org/#results) 有一个测试集 MASE 指标的比较表我们可以将自己的结果添加到其中作比较:
837
+
838
  |Dataset | SES| Theta | TBATS| ETS | (DHR-)ARIMA| PR| CatBoost | FFNN | DeepAR | N-BEATS | WaveNet| **Transformer** (Our) |
839
  |:------------------:|:-----------------:|:--:|:--:|:--:|:--:|:--:|:--:|:---:|:---:|:--:|:--:|:--:|
840
  |Tourism Monthly | 3.306 | 1.649 | 1.751 | 1.526| 1.589| 1.678 |1.699| 1.582 | 1.409 | 1.574| 1.482 | **1.361**|
841
 
842
+ 请注意,我们的模型击败了所有已知的其他模型 (另请参见相应 [论文](https://openreview.net/pdf?id=wEc1mgAjU-) 中的表 2) ,并且我们没有做任何超参数优化。我们仅仅花了 40 个完整训练调参周来训练 Transformer。
843
 
844
+ 对于此数据集的预测方法论文:
845
+ <url>https://openreview.net/pdf?id=wEc1mgAjU-</url>
846
+
847
+ 当然,我们应该谦虚。从历史发展的角度来看,现在认为神经网络解决时间序列预测问题是正途,就好比当年的论文得出了 [“你需要的就是 XGBoost”](https://www.sciencedirect.com/science/article/pii/S0169207021001679) 的���论。我们只是很好奇,想看看神经网络能带我们走多远,以及 Transformer 是否会在这个领域发挥作用。这个特定的数据集似乎表明它绝对值得探索。
848
+
849
+ 得出“你需要的就是 XGBoost”结论的论文地址:
850
+ <url>https://www.sciencedirect.com/science/article/pii/S0169207021001679</url>
851
 
852
  ## 下一步
853
 
854
+ 我们鼓励读者我们的 [Jupyter Notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/time-series-transformers.ipynb) 和来自 [Hugging Face Hub](https://huggingface.co/datasets/monash_tsf) 的其他时间序列数据集,并替换适当的频率和预测长度参数。对于您的数据集,需要将它们转换为 GluonTS 的惯用格式,在他们的 [文档](https://ts.gluon.ai/stable/tutorials/forecasting/extended_tutorial.html#What-is-in-a-dataset?) 里有非常清晰的说明。我们还准备了一个示例 [Notebook](https://github.com/huggingface/notebooks/blob/main/examples/time_series_datasets.ipynb),向您展示如何将数据集转换为 🤗 Hugging Face 数据集格式
855
+
856
+ - Time Series Transformers Notebook:
857
+ <url>https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/time-series-transformers.ipynb</url>
858
+ - Hub 中的 Monash Time Series 数据集:
859
+ <url>https://hf.co/datasets/monash_tsf</url>
860
+ - GluonTS 阐述数据集格式的文档:
861
+ <url>https://ts.gluon.ai/stable/tutorials/forecasting/extended_tutorial.html</url>
862
+ - 演示数据集格式转换的 Notebook:
863
+ <url>https://github.com/huggingface/notebooks/blob/main/examples/time_series_datasets.ipynb</url>
864
+
865
+
866
+ 正如时间序列研究人员所知,人们对“将基于 Transformer 的模型应用于时间序列”问题很感兴趣。传统 vanilla Transformer 只是众多基于注意力 (Attention) 的模型之一,因此需要向库中补充更多模型。
867
 
868
+ 目前没有什么能妨碍我们继续探索对多变量时间序列 (multivariate time series) 进行建模,但是为此需要使用多变量分布头 (multivariate distribution head) 来实例化模型。目前已经支持了对角独立分布 (diagonal independent distributions),后续会增加其他多元分布支持。请继续关注未来的博客文章以及其中的教程。
869
 
870
+ 路线图上的另一件事是时间序列分类。这需要带有分类头的时间序列模型添加到库中,例如用于异常检测这类任务
871
 
872
+ 的模型会假设日期时间和时间序列值都存在,但在现实中这可能不能完全满足。例如 [WOODS](https://woods-benchmarks.github.io/) 给出的神经科学数据集。因,我们还需要对当前模型进行泛化使某些输入在整个流水线可选
873
 
874
+ WOODS 主页:
875
+ <url>https://woods-benchmarks.github.io/</url>
876
 
877
+ 最后NLP/CV 领域从[大型预训练模型](https://arxiv.org/abs/1810.04805) 中获益匪浅,但我们所知时间序列领域并非如此。基于 Transformer 的模型似乎是这一研究方向的必然之选我们迫不及待地想看看研究人员和从业者会发现哪突破!
878
 
879
+ 大型预训练模型论文��址:
880
+ <url>https://arxiv.org/abs/1810.04805</url>
881
 
882
+ ---
883
 
884
+ >>>> 英文原文: [Probabilistic Time Series Forecasting with 🤗 Transformers](https://huggingface.co/blog/time-series-transformers)
885
+ >>>>
886
+ >>>> 译者、排版: zhongdongy (阿东)