Commit
•
91b0698
1
Parent(s):
7f6bcfb
Upload time-series-transformers-cn.md (#36)
Browse files- Upload time-series-transformers-cn.md (87915b1ce0c803dfdbf3e6f6cdca02d5ad53b907)
Co-authored-by: Yang Li <[email protected]>
- time-series-transformers-cn.md +852 -0
time-series-transformers-cn.md
ADDED
@@ -0,0 +1,852 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
标题:“使用 🤗 Transformers 进行概率时间序列预测”
|
3 |
+
缩略图:/blog/assets/118_time-series-transformers/thumbnail.png
|
4 |
+
作者:
|
5 |
+
- 用户:nielsr
|
6 |
+
- 用户:kashif
|
7 |
+
---
|
8 |
+
|
9 |
+
<h1>使用 🤗 Transformers 进行概率时间序列预测</h1>
|
10 |
+
|
11 |
+
<!-- {blog_metadata} -->
|
12 |
+
<!-- {authors} -->
|
13 |
+
|
14 |
+
<script async="None" defer="None" src="https://unpkg.com/medium-zoom-element@0/dist/medium-zoom-element.min.js"></script>
|
15 |
+
|
16 |
+
<a target="_blank" href="https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/time-series-transformers.ipynb">
|
17 |
+
<img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"></img>
|
18 |
+
</a>
|
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'],
|
93 |
+
num_rows: 366
|
94 |
+
})
|
95 |
+
test: Dataset({
|
96 |
+
features: ['start', 'target', 'feat_static_cat', 'feat_dynamic_real', 'item_id'],
|
97 |
+
num_rows: 366
|
98 |
+
})
|
99 |
+
validation: Dataset({
|
100 |
+
features: ['start', 'target', 'feat_static_cat', 'feat_dynamic_real', 'item_id'],
|
101 |
+
num_rows: 366
|
102 |
+
})
|
103 |
+
})
|
104 |
+
```
|
105 |
+
|
106 |
+
|
107 |
+
每个示例都包含一些键,其中“start”和“target”是最重要的键。让我们看一下数据集中的第一个时间序列:
|
108 |
+
|
109 |
+
|
110 |
+
```python
|
111 |
+
train_example = dataset['train'][0]
|
112 |
+
train_example.keys()
|
113 |
+
|
114 |
+
>>> dict_keys(['start', 'target', 'feat_static_cat', 'feat_dynamic_real', 'item_id'])
|
115 |
+
```
|
116 |
+
|
117 |
+
`start` 仅指示时间序列的开始(作为日期时间),而 `target` 包含时间序列的实际值。
|
118 |
+
|
119 |
+
`start` 将有助于将时间相关的特征添加到时间序列值中,作为模型的额外输入(例如“一年中的月份”)。因为我们知道数据的频率是“每月”,所以知道例如第二个值的时间戳为“1979-02-01”,等等。
|
120 |
+
|
121 |
+
|
122 |
+
```python
|
123 |
+
print(train_example['start'])
|
124 |
+
print(train_example['target'])
|
125 |
+
|
126 |
+
>>> 1979-01-01 00:00:00
|
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]
|
138 |
+
validation_example.keys()
|
139 |
+
|
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'])
|
150 |
+
print(validation_example['target'])
|
151 |
+
|
152 |
+
>>> 1979-01-01 00:00:00
|
153 |
+
[1149.8699951171875, 1053.8001708984375, ..., 5985.830078125]
|
154 |
+
```
|
155 |
+
|
156 |
+
但是,与训练示例相比,此示例具有“prediction_length=24”附加值。让我们验证一下。
|
157 |
+
|
158 |
+
|
159 |
+
```python
|
160 |
+
freq = "1M"
|
161 |
+
prediction_length = 24
|
162 |
+
|
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
|
171 |
+
|
172 |
+
figure, axes = plt.subplots()
|
173 |
+
axes.plot(train_example['target'], color="blue")
|
174 |
+
axes.plot(validation_example['target'], color="red", alpha=0.5)
|
175 |
+
|
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"]
|
187 |
+
test_dataset = dataset["test"]
|
188 |
+
```
|
189 |
+
|
190 |
+
## 将 `start` 更新为 `pd.Period`
|
191 |
+
|
192 |
+
我们要做的第一件事是使用数据的 `freq` 将每个时间序列的 `start` 特征转换为 pandas `Period` 索引:
|
193 |
+
|
194 |
+
|
195 |
+
```python
|
196 |
+
from functools import lru_cache
|
197 |
+
|
198 |
+
import pandas as pd
|
199 |
+
import numpy as np
|
200 |
+
|
201 |
+
@lru_cache(10_000)
|
202 |
+
def convert_to_pandas_period(date, freq):
|
203 |
+
return pd.Period(date, freq)
|
204 |
+
|
205 |
+
def transform_start_field(batch, freq):
|
206 |
+
batch["start"] = [convert_to_pandas_period(date, freq) for date in batch["start"]]
|
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
|
214 |
+
|
215 |
+
train_dataset.set_transform(partial(transform_start_field, freq=freq))
|
216 |
+
test_dataset.set_transform(partial(transform_start_field, freq=freq))
|
217 |
+
```
|
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”,因为我们将添加“MonthOfYear”和“Age”特征;
|
228 |
+
- 静态分类特征的数量:在我们的例子中,这将只是“1”,因为我们将添加一个“时间序列 ID”特征;
|
229 |
+
- 基数:每个静态分类特征的值的数量,作为一个列表,对于我们的案例来说将是“[366]”,因为我们有 366 个不同的时间序列
|
230 |
+
- 嵌入维度:每个静态分类特征的嵌入维度,作为列表,例如“[3]”意味着模型将为每个“366”时间序列(区域)学习大小为“3”的嵌入向量.
|
231 |
+
|
232 |
+
|
233 |
+
让我们使用 GluonTS 为给定频率(“每月”)提供的默认滞后:
|
234 |
+
|
235 |
+
|
236 |
+
```python
|
237 |
+
from gluonts.time_feature import get_lags_for_frequency
|
238 |
+
|
239 |
+
lags_sequence = get_lags_for_frequency(freq)
|
240 |
+
print(lags_sequence)
|
241 |
+
|
242 |
+
>>> [1, 2, 3, 4, 5, 6, 7, 11, 12, 13, 23, 24, 25, 35, 36, 37]
|
243 |
+
```
|
244 |
+
|
245 |
+
|
246 |
+
这意味着我们将回顾每个时间步长达 37 个月的时间,作为附加功能。
|
247 |
+
|
248 |
+
我们还检查 GluonTS 为我们提供的默认时间功能:
|
249 |
+
|
250 |
+
|
251 |
+
```python
|
252 |
+
from gluonts.time_feature import time_features_from_frequency_str
|
253 |
+
|
254 |
+
time_features = time_features_from_frequency_str(freq)
|
255 |
+
print(time_features)
|
256 |
+
|
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
|
268 |
+
|
269 |
+
config = TimeSeriesTransformerConfig(
|
270 |
+
prediction_length=prediction_length,
|
271 |
+
context_length=prediction_length*3, # context length
|
272 |
+
lags_sequence=lags_sequence,
|
273 |
+
num_time_features=len(time_features) + 1, # we'll add 2 time features ("month of year" and "age", see further)
|
274 |
+
num_static_categorical_features=1, # we have a single static categorical feature, namely time series ID
|
275 |
+
cardinality=[len(train_dataset)], # it has 366 possible values
|
276 |
+
embedding_dimension=[2], # the model will learn an embedding of size 2 for each of the 366 possible values
|
277 |
+
encoder_layers=4,
|
278 |
+
decoder_layers=4,
|
279 |
+
)
|
280 |
+
|
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
|
288 |
+
|
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
|
303 |
+
from gluonts.dataset.field_names import FieldName
|
304 |
+
from gluonts.transform import (
|
305 |
+
AddAgeFeature,
|
306 |
+
AddObservedValuesIndicator,
|
307 |
+
AddTimeFeatures,
|
308 |
+
AsNumpyArray,
|
309 |
+
Chain,
|
310 |
+
ExpectedNumInstanceSampler,
|
311 |
+
InstanceSplitter,
|
312 |
+
RemoveFields,
|
313 |
+
SelectFields,
|
314 |
+
SetField,
|
315 |
+
TestSplitSampler,
|
316 |
+
Transformation,
|
317 |
+
ValidationSplitSampler,
|
318 |
+
VstackFeatures,
|
319 |
+
RenameFields,
|
320 |
+
)
|
321 |
+
```
|
322 |
+
|
323 |
+
下面的转换带有注释,以解释它们的作用。在高层次上,我们将迭代数据集的各个时间序列并添加/删除字段或特征:
|
324 |
+
|
325 |
+
|
326 |
+
```python
|
327 |
+
from transformers import PretrainedConfig
|
328 |
+
|
329 |
+
def create_transformation(freq: str, config: PretrainedConfig) -> Transformation:
|
330 |
+
remove_field_names = []
|
331 |
+
if config.num_static_real_features == 0:
|
332 |
+
remove_field_names.append(FieldName.FEAT_STATIC_REAL)
|
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
|
344 |
+
else []
|
345 |
+
)
|
346 |
+
+ (
|
347 |
+
[SetField(output_field=FieldName.FEAT_STATIC_REAL, value=[0.0])]
|
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,
|
355 |
+
expected_ndim=1,
|
356 |
+
dtype=int,
|
357 |
+
),
|
358 |
+
AsNumpyArray(
|
359 |
+
field=FieldName.FEAT_STATIC_REAL,
|
360 |
+
expected_ndim=1,
|
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,
|
382 |
+
output_field=FieldName.FEAT_TIME,
|
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",
|
405 |
+
FieldName.FEAT_STATIC_REAL: "static_real_features",
|
406 |
+
FieldName.FEAT_TIME: "time_features",
|
407 |
+
FieldName.TARGET: "values",
|
408 |
+
FieldName.OBSERVED_VALUES: "observed_mask",
|
409 |
+
}
|
410 |
+
),
|
411 |
+
]
|
412 |
+
)
|
413 |
+
|
414 |
+
```
|
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
|
424 |
+
from gluonts.transform.sampler import InstanceSampler
|
425 |
+
from typing import Optional
|
426 |
+
|
427 |
+
def create_instance_splitter(config: PretrainedConfig, mode: str, train_sampler: Optional[InstanceSampler] = None,
|
428 |
+
validation_sampler: Optional[InstanceSampler] = None,) -> Transformation:
|
429 |
+
assert mode in ["train", "validation", "test"]
|
430 |
+
|
431 |
+
instance_sampler = {
|
432 |
+
"train": train_sampler or ExpectedNumInstanceSampler(
|
433 |
+
num_instances=1.0, min_future=config.prediction_length
|
434 |
+
),
|
435 |
+
"validation": validation_sampler or ValidationSplitSampler(
|
436 |
+
min_future=config.prediction_length
|
437 |
+
),
|
438 |
+
"test": TestSplitSampler(),
|
439 |
+
}[mode]
|
440 |
+
|
441 |
+
return InstanceSplitter(
|
442 |
+
target_field="values",
|
443 |
+
is_pad_field=FieldName.IS_PAD,
|
444 |
+
start_field=FieldName.START,
|
445 |
+
forecast_start_field=FieldName.FORECAST_START,
|
446 |
+
instance_sampler=instance_sampler,
|
447 |
+
past_length=config.context_length + max(config.lags_sequence),
|
448 |
+
future_length=config.prediction_length,
|
449 |
+
time_series_fields=[
|
450 |
+
"time_features",
|
451 |
+
"observed_mask",
|
452 |
+
],
|
453 |
+
)
|
454 |
+
```
|
455 |
+
|
456 |
+
## 创建 PyTorch 数据加载器
|
457 |
+
|
458 |
+
接下来,是时候创建 PyTorch DataLoaders,它允许我们拥有成批的(输入、输出)对 - 或者换句话说(`past_values`、`future_values`)。
|
459 |
+
|
460 |
+
|
461 |
+
```python
|
462 |
+
from gluonts.itertools import Cyclic, IterableSlice, PseudoShuffled
|
463 |
+
from gluonts.torch.util import IterableDataset
|
464 |
+
from torch.utils.data import DataLoader
|
465 |
+
|
466 |
+
from typing import Iterable
|
467 |
+
|
468 |
+
def create_train_dataloader(
|
469 |
+
config: PretrainedConfig,
|
470 |
+
freq,
|
471 |
+
data,
|
472 |
+
batch_size: int,
|
473 |
+
num_batches_per_epoch: int,
|
474 |
+
shuffle_buffer_length: Optional[int] = None,
|
475 |
+
**kwargs,
|
476 |
+
) -> Iterable:
|
477 |
+
PREDICTION_INPUT_NAMES = [
|
478 |
+
"static_categorical_features",
|
479 |
+
"static_real_features",
|
480 |
+
"past_time_features",
|
481 |
+
"past_values",
|
482 |
+
"past_observed_mask",
|
483 |
+
"future_time_features",
|
484 |
+
]
|
485 |
+
|
486 |
+
TRAINING_INPUT_NAMES = PREDICTION_INPUT_NAMES + [
|
487 |
+
"future_values",
|
488 |
+
"future_observed_mask",
|
489 |
+
]
|
490 |
+
|
491 |
+
transformation = create_transformation(freq, config)
|
492 |
+
transformed_data = transformation.apply(data, is_train=True)
|
493 |
+
|
494 |
+
# we initialize a Training instance
|
495 |
+
instance_splitter = create_instance_splitter(
|
496 |
+
config, "train"
|
497 |
+
) + SelectFields(TRAINING_INPUT_NAMES)
|
498 |
+
|
499 |
+
|
500 |
+
# the instance splitter will sample a window of
|
501 |
+
# context length + lags + prediction length (from the 366 possible transformed time series)
|
502 |
+
# randomly from within the target time series and return an iterator.
|
503 |
+
training_instances = instance_splitter.apply(
|
504 |
+
Cyclic(transformed_data)
|
505 |
+
if shuffle_buffer_length is None
|
506 |
+
else PseudoShuffled(
|
507 |
+
Cyclic(transformed_data),
|
508 |
+
shuffle_buffer_length=shuffle_buffer_length,
|
509 |
+
)
|
510 |
+
)
|
511 |
+
|
512 |
+
# from the training instances iterator we now return a Dataloader which will
|
513 |
+
# continue to sample random windows for as long as it is called
|
514 |
+
# to return batch_size of the appropriate tensors ready for training!
|
515 |
+
return IterableSlice(
|
516 |
+
iter(
|
517 |
+
DataLoader(
|
518 |
+
IterableDataset(training_instances),
|
519 |
+
batch_size=batch_size,
|
520 |
+
**kwargs,
|
521 |
+
)
|
522 |
+
),
|
523 |
+
num_batches_per_epoch,
|
524 |
+
)
|
525 |
+
```
|
526 |
+
|
527 |
+
|
528 |
+
```python
|
529 |
+
def create_test_dataloader(
|
530 |
+
config: PretrainedConfig,
|
531 |
+
freq,
|
532 |
+
data,
|
533 |
+
batch_size: int,
|
534 |
+
**kwargs,
|
535 |
+
):
|
536 |
+
PREDICTION_INPUT_NAMES = [
|
537 |
+
"static_categorical_features",
|
538 |
+
"static_real_features",
|
539 |
+
"past_time_features",
|
540 |
+
"past_values",
|
541 |
+
"past_observed_mask",
|
542 |
+
"future_time_features",
|
543 |
+
]
|
544 |
+
|
545 |
+
transformation = create_transformation(freq, config)
|
546 |
+
transformed_data = transformation.apply(data, is_train=False)
|
547 |
+
|
548 |
+
# we create a Test Instance splitter which will sample the very last
|
549 |
+
# context window seen during training only for the encoder.
|
550 |
+
instance_splitter = create_instance_splitter(
|
551 |
+
config, "test"
|
552 |
+
) + SelectFields(PREDICTION_INPUT_NAMES)
|
553 |
+
|
554 |
+
# we apply the transformations in test mode
|
555 |
+
testing_instances = instance_splitter.apply(transformed_data, is_train=False)
|
556 |
+
|
557 |
+
# This returns a Dataloader which will go over the dataset once.
|
558 |
+
return DataLoader(IterableDataset(testing_instances), batch_size=batch_size, **kwargs)
|
559 |
+
```
|
560 |
+
|
561 |
+
|
562 |
+
```python
|
563 |
+
train_dataloader = create_train_dataloader(
|
564 |
+
config=config,
|
565 |
+
freq=freq,
|
566 |
+
data=train_dataset,
|
567 |
+
batch_size=256,
|
568 |
+
num_batches_per_epoch=100,
|
569 |
+
)
|
570 |
+
|
571 |
+
test_dataloader = create_test_dataloader(
|
572 |
+
config=config,
|
573 |
+
freq=freq,
|
574 |
+
data=test_dataset,
|
575 |
+
batch_size=64,
|
576 |
+
)
|
577 |
+
```
|
578 |
+
|
579 |
+
让我们检查第一批:
|
580 |
+
|
581 |
+
|
582 |
+
```python
|
583 |
+
batch = next(iter(train_dataloader))
|
584 |
+
for k,v in batch.items():
|
585 |
+
print(k,v.shape, v.type())
|
586 |
+
|
587 |
+
>>> static_categorical_features torch.Size([256, 1]) torch.LongTensor
|
588 |
+
static_real_features torch.Size([256, 1]) torch.FloatTensor
|
589 |
+
past_time_features torch.Size([256, 181, 2]) torch.FloatTensor
|
590 |
+
past_values torch.Size([256, 181]) torch.FloatTensor
|
591 |
+
past_observed_mask torch.Size([256, 181]) torch.FloatTensor
|
592 |
+
future_time_features torch.Size([256, 24, 2]) torch.FloatTensor
|
593 |
+
future_values torch.Size([256, 24]) torch.FloatTensor
|
594 |
+
future_observed_mask torch.Size([256, 24]) torch.FloatTensor
|
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_values”、“future_observed_mask”和“future_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
|
611 |
+
outputs = model(
|
612 |
+
past_values=batch["past_values"],
|
613 |
+
past_time_features=batch["past_time_features"],
|
614 |
+
past_observed_mask=batch["past_observed_mask"],
|
615 |
+
static_categorical_features=batch["static_categorical_features"],
|
616 |
+
static_real_features=batch["static_real_features"],
|
617 |
+
future_values=batch["future_values"],
|
618 |
+
future_time_features=batch["future_time_features"],
|
619 |
+
future_observed_mask=batch["future_observed_mask"],
|
620 |
+
output_hidden_states=True
|
621 |
+
)
|
622 |
+
```
|
623 |
+
|
624 |
+
```python
|
625 |
+
print("Loss:", outputs.loss.item())
|
626 |
+
|
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
|
643 |
+
from torch.optim import Adam
|
644 |
+
|
645 |
+
accelerator = Accelerator()
|
646 |
+
device = accelerator.device
|
647 |
+
|
648 |
+
model.to(device)
|
649 |
+
optimizer = Adam(model.parameters(), lr=1e-3)
|
650 |
+
|
651 |
+
model, optimizer, train_dataloader = accelerator.prepare(
|
652 |
+
model, optimizer, train_dataloader,
|
653 |
+
)
|
654 |
+
|
655 |
+
for epoch in range(40):
|
656 |
+
model.train()
|
657 |
+
for batch in train_dataloader:
|
658 |
+
optimizer.zero_grad()
|
659 |
+
outputs = model(
|
660 |
+
static_categorical_features=batch["static_categorical_features"].to(device),
|
661 |
+
static_real_features=batch["static_real_features"].to(device),
|
662 |
+
past_time_features=batch["past_time_features"].to(device),
|
663 |
+
past_values=batch["past_values"].to(device),
|
664 |
+
future_time_features=batch["future_time_features"].to(device),
|
665 |
+
future_values=batch["future_values"].to(device),
|
666 |
+
past_observed_mask=batch["past_observed_mask"].to(device),
|
667 |
+
future_observed_mask=batch["future_observed_mask"].to(device),
|
668 |
+
)
|
669 |
+
loss = outputs.loss
|
670 |
+
|
671 |
+
# Backpropagation
|
672 |
+
accelerator.backward(loss)
|
673 |
+
optimizer.step()
|
674 |
+
|
675 |
+
print(loss.item())
|
676 |
+
```
|
677 |
+
|
678 |
+
|
679 |
+
## 推理
|
680 |
+
|
681 |
+
在推理时,建议使用 `generate()` 方法进行自回归生成,类似于 NLP 模型。
|
682 |
+
|
683 |
+
预测涉及从测试实例采样器获取数据,该采样器将从数据集中每个时间序列的最后一个“context_length”大小的值窗口中采样,并将其传递给模型。请注意,我们将提前已知的“future_time_features”传递给解码器。
|
684 |
+
|
685 |
+
该模型将从预测分布中自回归采样一定数量的值,并将它们传回解码器以返回预测输出:
|
686 |
+
|
687 |
+
```python
|
688 |
+
model.eval()
|
689 |
+
|
690 |
+
forecasts = []
|
691 |
+
|
692 |
+
for batch in test_dataloader:
|
693 |
+
outputs = model.generate(
|
694 |
+
static_categorical_features=batch["static_categorical_features"].to(device),
|
695 |
+
static_real_features=batch["static_real_features"].to(device),
|
696 |
+
past_time_features=batch["past_time_features"].to(device),
|
697 |
+
past_values=batch["past_values"].to(device),
|
698 |
+
future_time_features=batch["future_time_features"].to(device),
|
699 |
+
past_observed_mask=batch["past_observed_mask"].to(device),
|
700 |
+
)
|
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
|
710 |
+
forecasts[0].shape
|
711 |
+
|
712 |
+
>>> (64, 100, 24)
|
713 |
+
```
|
714 |
+
|
715 |
+
我们将垂直堆叠它们,以获得测试数据集中所有时间序列的预测:
|
716 |
+
|
717 |
+
```python
|
718 |
+
forecasts = np.vstack(forecasts)
|
719 |
+
print(forecasts.shape)
|
720 |
+
|
721 |
+
>>> (366, 100, 24)
|
722 |
+
```
|
723 |
+
|
724 |
+
我们可以根据测试集中存在的样本值,根据真实情况评估生成的预测。我们将使用我们为数据集中的每个时间序列:
|
725 |
+
|
726 |
+
```python
|
727 |
+
from evaluate import load
|
728 |
+
from gluonts.time_feature import get_seasonality
|
729 |
+
|
730 |
+
mase_metric = load("evaluate-metric/mase")
|
731 |
+
smape_metric = load("evaluate-metric/smape")
|
732 |
+
|
733 |
+
forecast_median = np.median(forecasts, 1)
|
734 |
+
|
735 |
+
mase_metrics = []
|
736 |
+
smape_metrics = []
|
737 |
+
for item_id, ts in enumerate(test_dataset):
|
738 |
+
training_data = ts["target"][:-prediction_length]
|
739 |
+
ground_truth = ts["target"][-prediction_length:]
|
740 |
+
mase = mase_metric.compute(
|
741 |
+
predictions=forecast_median[item_id],
|
742 |
+
references=np.array(ground_truth),
|
743 |
+
training=np.array(training_data),
|
744 |
+
periodicity=get_seasonality(freq))
|
745 |
+
mase_metrics.append(mase["mase"])
|
746 |
+
|
747 |
+
smape = smape_metric.compute(
|
748 |
+
predictions=forecast_median[item_id],
|
749 |
+
references=np.array(ground_truth),
|
750 |
+
)
|
751 |
+
smape_metrics.append(smape["smape"])
|
752 |
+
```
|
753 |
+
|
754 |
+
|
755 |
+
```python
|
756 |
+
print(f"MASE: {np.mean(mase_metrics)}")
|
757 |
+
|
758 |
+
>>> MASE: 1.361636922541396
|
759 |
+
|
760 |
+
print(f"sMAPE: {np.mean(smape_metrics)}")
|
761 |
+
|
762 |
+
>>> sMAPE: 0.17457818831512306
|
763 |
+
```
|
764 |
+
|
765 |
+
我们还可以绘制数据集中每个时间序列的单独指标,并观察到少数时间序列对最终测试指标的贡献很大:
|
766 |
+
|
767 |
+
```python
|
768 |
+
plt.scatter(mase_metrics, smape_metrics, alpha=0.3)
|
769 |
+
plt.xlabel("MASE")
|
770 |
+
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
|
780 |
+
|
781 |
+
def plot(ts_index):
|
782 |
+
fig, ax = plt.subplots()
|
783 |
+
|
784 |
+
index = pd.period_range(
|
785 |
+
start=test_dataset[ts_index][FieldName.START],
|
786 |
+
periods=len(test_dataset[ts_index][FieldName.TARGET]),
|
787 |
+
freq=freq,
|
788 |
+
).to_timestamp()
|
789 |
+
|
790 |
+
# Major ticks every half year, minor ticks every month,
|
791 |
+
ax.xaxis.set_major_locator(mdates.MonthLocator(bymonth=(1, 7)))
|
792 |
+
ax.xaxis.set_minor_locator(mdates.MonthLocator())
|
793 |
+
|
794 |
+
ax.plot(
|
795 |
+
index[-2*prediction_length:],
|
796 |
+
test_dataset[ts_index]["target"][-2*prediction_length:],
|
797 |
+
label="actual",
|
798 |
+
)
|
799 |
+
|
800 |
+
plt.plot(
|
801 |
+
index[-prediction_length:],
|
802 |
+
np.median(forecasts[ts_index], axis=0),
|
803 |
+
label="median",
|
804 |
+
)
|
805 |
+
|
806 |
+
plt.fill_between(
|
807 |
+
index[-prediction_length:],
|
808 |
+
forecasts[ts_index].mean(0) - forecasts[ts_index].std(axis=0),
|
809 |
+
forecasts[ts_index].mean(0) + forecasts[ts_index].std(axis=0),
|
810 |
+
alpha=0.3,
|
811 |
+
interpolate=True,
|
812 |
+
label="+/- 1-std",
|
813 |
+
)
|
814 |
+
plt.legend()
|
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 (李洋)
|