-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
ltsf.py
501 lines (439 loc) · 16.1 KB
/
ltsf.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
"""Deep Learning Forecasters using LTSF-Linear Models."""
from sktime.forecasting.base.adapters._pytorch import BaseDeepNetworkPyTorch
class LTSFLinearForecaster(BaseDeepNetworkPyTorch):
"""LTSF-Linear Forecaster.
Implementation of the Long-Term Short-Term Feature (LTSF) linear forecaster,
aka LTSF-Linear, by Zeng et al [1]_.
Core logic is directly copied from the cure-lab LTSF-Linear implementation [2]_,
which is unfortunately not available as a package.
Parameters
----------
seq_len : int
length of input sequence
pred_len : int
length of prediction (forecast horizon)
num_epochs : int, default=16
number of epochs to train
batch_size : int, default=8
number of training examples per batch
in_channels : int, default=1
number of input channels passed to network
individual : bool, default=False
boolean flag that controls whether the network treats each channel individually"
"or applies a single linear layer across all channels. If individual=True, the"
"a separate linear layer is created for each input channel. If"
"individual=False, a single shared linear layer is used for all channels."
criterion : torch.nn Loss Function, default=torch.nn.MSELoss
loss function to be used for training
criterion_kwargs : dict, default=None
keyword arguments to pass to criterion
optimizer : torch.optim.Optimizer, default=torch.optim.Adam
optimizer to be used for training
optimizer_kwargs : dict, default=None
keyword arguments to pass to optimizer
lr : float, default=0.003
learning rate to train model with
References
----------
.. [1] Zeng A, Chen M, Zhang L, Xu Q. 2023.
Are transformers effective for time series forecasting?
Proceedings of the AAAI conference on artificial intelligence 2023
(Vol. 37, No. 9, pp. 11121-11128).
.. [2] https://github.com/cure-lab/LTSF-Linear
Examples
--------
>>> from sktime.forecasting.ltsf import LTSFLinearForecaster # doctest: +SKIP
>>> from sktime.datasets import load_airline
>>> model = LTSFLinearForecaster(10, 3) # doctest: +SKIP
>>> y = load_airline()
>>> model.fit(y, fh=[1,2,3]) # doctest: +SKIP
LTSFLinearForecaster(pred_len=3, seq_len=10)
>>> y_pred = model.predict() # doctest: +SKIP
>>> y_pred # doctest: +SKIP
1961-01 515.456726
1961-02 576.704712
1961-03 559.859680
Freq: M, Name: Number of airline passengers, dtype: float32
"""
_tags = {
# packaging info
# --------------
"authors": ["luca-miniati"],
"maintainers": ["luca-miniati"],
# "python_dependencies": "pytorch" - inherited from BaseDeepNetworkPyTorch
# estimator type vars inherited from BaseDeepNetworkPyTorch
}
def __init__(
self,
seq_len,
pred_len,
*,
num_epochs=16,
batch_size=8,
in_channels=1,
individual=False,
criterion=None,
criterion_kwargs=None,
optimizer=None,
optimizer_kwargs=None,
lr=0.001,
custom_dataset_train=None,
custom_dataset_pred=None,
):
self.seq_len = seq_len
self.pred_len = pred_len
self.individual = individual
self.in_channels = in_channels
self.criterion = criterion
self.optimizer = optimizer
self.criterion_kwargs = criterion_kwargs
self.optimizer_kwargs = optimizer_kwargs
self.lr = lr
self.num_epochs = num_epochs
self.custom_dataset_train = custom_dataset_train
self.custom_dataset_pred = custom_dataset_pred
self.batch_size = batch_size
super().__init__(
num_epochs=num_epochs,
batch_size=batch_size,
in_channels=in_channels,
individual=individual,
criterion_kwargs=criterion_kwargs,
optimizer=optimizer,
optimizer_kwargs=optimizer_kwargs,
lr=lr,
)
from sktime.utils.validation._dependencies import _check_soft_dependencies
if _check_soft_dependencies("torch"):
import torch
self.criterions = {
"MSE": torch.nn.MSELoss,
"L1": torch.nn.L1Loss,
"SmoothL1": torch.nn.SmoothL1Loss,
"Huber": torch.nn.HuberLoss,
}
self.optimizers = {
"Adadelta": torch.optim.Adadelta,
"Adagrad": torch.optim.Adagrad,
"Adam": torch.optim.Adam,
"AdamW": torch.optim.AdamW,
"SGD": torch.optim.SGD,
}
def _build_network(self, fh):
from sktime.networks.ltsf._ltsf import LTSFLinearNetwork
return LTSFLinearNetwork(
self.seq_len,
fh,
self.in_channels,
self.individual,
)._build()
@classmethod
def get_test_params(cls, parameter_set="default"):
"""Return testing parameter settings for the estimator.
Parameters
----------
parameter_set : str, default="default"
Name of the set of test parameters to return, for use in tests. If no
special parameters are defined for a value, will return ``"default"`` set.
Returns
-------
params : dict or list of dict
"""
params = [
{
"seq_len": 2,
"pred_len": 1,
"lr": 0.005,
"optimizer": "Adam",
"batch_size": 1,
"num_epochs": 1,
"individual": True,
}
]
return params
class LTSFDLinearForecaster(BaseDeepNetworkPyTorch):
"""LTSF-DLinear Forecaster.
Implementation of the Long-Term Short-Term Feature (LTSF) decomposition linear
forecaster, aka LTSF-DLinear, by Zeng et al [1]_.
Core logic is directly copied from the cure-lab LTSF-Linear implementation [2]_,
which is unfortunately not available as a package.
Parameters
----------
seq_len : int
length of input sequence
pred_len : int
length of prediction (forecast horizon)
num_epochs : int, default=16
number of epochs to train
batch_size : int, default=8
number of training examples per batch
in_channels : int, default=1
number of input channels passed to network
individual : bool, default=False
boolean flag that controls whether the network treats each channel individually"
"or applies a single linear layer across all channels. If individual=True, the"
"a separate linear layer is created for each input channel. If"
"individual=False, a single shared linear layer is used for all channels."
criterion : torch.nn Loss Function, default=torch.nn.MSELoss
loss function to be used for training
criterion_kwargs : dict, default=None
keyword arguments to pass to criterion
optimizer : torch.optim.Optimizer, default=torch.optim.Adam
optimizer to be used for training
optimizer_kwargs : dict, default=None
keyword arguments to pass to optimizer
lr : float, default=0.003
learning rate to train model with
References
----------
.. [1] Zeng A, Chen M, Zhang L, Xu Q. 2023.
Are transformers effective for time series forecasting?
Proceedings of the AAAI conference on artificial intelligence 2023
(Vol. 37, No. 9, pp. 11121-11128).
.. [2] https://github.com/cure-lab/LTSF-Linear
Examples
--------
>>> from sktime.forecasting.ltsf import LTSFDLinearForecaster # doctest: +SKIP
>>> from sktime.datasets import load_airline
>>> model = LTSFDLinearForecaster(10, 3) # doctest: +SKIP
>>> y = load_airline()
>>> model.fit(y, fh=[1,2,3]) # doctest: +SKIP
LTSFDLinearForecaster(pred_len=3, seq_len=10)
>>> y_pred = model.predict() # doctest: +SKIP
>>> y_pred # doctest: +SKIP
1961-01 436.494476
1961-02 433.659851
1961-03 479.309631
Freq: M, Name: Number of airline passengers, dtype: float32
"""
def __init__(
self,
seq_len,
pred_len,
*,
num_epochs=16,
batch_size=8,
in_channels=1,
individual=False,
criterion=None,
criterion_kwargs=None,
optimizer=None,
optimizer_kwargs=None,
lr=0.001,
custom_dataset_train=None,
custom_dataset_pred=None,
):
self.seq_len = seq_len
self.pred_len = pred_len
self.individual = individual
self.in_channels = in_channels
self.criterion = criterion
self.optimizer = optimizer
self.criterion_kwargs = criterion_kwargs
self.optimizer_kwargs = optimizer_kwargs
self.lr = lr
self.num_epochs = num_epochs
self.custom_dataset_train = custom_dataset_train
self.custom_dataset_pred = custom_dataset_pred
self.batch_size = batch_size
super().__init__(
num_epochs=num_epochs,
batch_size=batch_size,
in_channels=in_channels,
individual=individual,
criterion_kwargs=criterion_kwargs,
optimizer=optimizer,
optimizer_kwargs=optimizer_kwargs,
lr=lr,
)
from sktime.utils.validation._dependencies import _check_soft_dependencies
if _check_soft_dependencies("torch"):
import torch
self.criterions = {
"MSE": torch.nn.MSELoss,
"L1": torch.nn.L1Loss,
"SmoothL1": torch.nn.SmoothL1Loss,
"Huber": torch.nn.HuberLoss,
}
self.optimizers = {
"Adadelta": torch.optim.Adadelta,
"Adagrad": torch.optim.Adagrad,
"Adam": torch.optim.Adam,
"AdamW": torch.optim.AdamW,
"SGD": torch.optim.SGD,
}
def _build_network(self, fh):
from sktime.networks.ltsf._ltsf import LTSFDLinearNetwork
return LTSFDLinearNetwork(
self.seq_len,
fh,
self.in_channels,
self.individual,
)._build()
@classmethod
def get_test_params(cls, parameter_set="default"):
"""Return testing parameter settings for the estimator.
Parameters
----------
parameter_set : str, default="default"
Name of the set of test parameters to return, for use in tests. If no
special parameters are defined for a value, will return ``"default"`` set.
Returns
-------
params : dict or list of dict
"""
params = [
{
"seq_len": 2,
"pred_len": 1,
"lr": 0.005,
"optimizer": "Adam",
"batch_size": 1,
"num_epochs": 1,
"individual": True,
}
]
return params
class LTSFNLinearForecaster(BaseDeepNetworkPyTorch):
"""LTSF-NLinear Forecaster.
Implementation of the Long-Term Short-Term Feature (LTSF) normalization linear
forecaster, aka LTSF-NLinear, by Zeng et al [1]_.
Core logic is directly copied from the cure-lab LTSF-Linear implementation [2]_,
which is unfortunately not available as a package.
Parameters
----------
seq_len : int
length of input sequence
pred_len : int
length of prediction (forecast horizon)
num_epochs : int, default=16
number of epochs to train
batch_size : int, default=8
number of training examples per batch
in_channels : int, default=1
number of input channels passed to network
individual : bool, default=False
boolean flag that controls whether the network treats each channel individually"
"or applies a single linear layer across all channels. If individual=True, the"
"a separate linear layer is created for each input channel. If"
"individual=False, a single shared linear layer is used for all channels."
criterion : torch.nn Loss Function, default=torch.nn.MSELoss
loss function to be used for training
criterion_kwargs : dict, default=None
keyword arguments to pass to criterion
optimizer : torch.optim.Optimizer, default=torch.optim.Adam
optimizer to be used for training
optimizer_kwargs : dict, default=None
keyword arguments to pass to optimizer
lr : float, default=0.003
learning rate to train model with
References
----------
.. [1] Zeng A, Chen M, Zhang L, Xu Q. 2023.
Are transformers effective for time series forecasting?
Proceedings of the AAAI conference on artificial intelligence 2023
(Vol. 37, No. 9, pp. 11121-11128).
.. [2] https://github.com/cure-lab/LTSF-Linear
Examples
--------
>>> from sktime.forecasting.ltsf import LTSFNLinearForecaster # doctest: +SKIP
>>> from sktime.datasets import load_airline
>>> model = LTSFNLinearForecaster(10, 3) # doctest: +SKIP
>>> y = load_airline()
>>> model.fit(y, fh=[1,2,3]) # doctest: +SKIP
LTSFNLinearForecaster(pred_len=3, seq_len=10)
>>> y_pred = model.predict() # doctest: +SKIP
>>> y_pred # doctest: +SKIP
1961-01 455.628082
1961-02 433.349640
1961-03 437.045502
Freq: M, Name: Number of airline passengers, dtype: float32
"""
def __init__(
self,
seq_len,
pred_len,
*,
num_epochs=16,
batch_size=8,
in_channels=1,
individual=False,
criterion=None,
criterion_kwargs=None,
optimizer=None,
optimizer_kwargs=None,
lr=0.001,
custom_dataset_train=None,
custom_dataset_pred=None,
):
self.seq_len = seq_len
self.pred_len = pred_len
self.individual = individual
self.in_channels = in_channels
self.criterion = criterion
self.optimizer = optimizer
self.criterion_kwargs = criterion_kwargs
self.optimizer_kwargs = optimizer_kwargs
self.lr = lr
self.num_epochs = num_epochs
self.custom_dataset_train = custom_dataset_train
self.custom_dataset_pred = custom_dataset_pred
self.batch_size = batch_size
super().__init__(
num_epochs=num_epochs,
batch_size=batch_size,
in_channels=in_channels,
individual=individual,
criterion_kwargs=criterion_kwargs,
optimizer=optimizer,
optimizer_kwargs=optimizer_kwargs,
lr=lr,
)
from sktime.utils.validation._dependencies import _check_soft_dependencies
if _check_soft_dependencies("torch"):
import torch
self.criterions = {
"MSE": torch.nn.MSELoss,
"L1": torch.nn.L1Loss,
"SmoothL1": torch.nn.SmoothL1Loss,
"Huber": torch.nn.HuberLoss,
}
self.optimizers = {
"Adadelta": torch.optim.Adadelta,
"Adagrad": torch.optim.Adagrad,
"Adam": torch.optim.Adam,
"AdamW": torch.optim.AdamW,
"SGD": torch.optim.SGD,
}
def _build_network(self, fh):
from sktime.networks.ltsf._ltsf import LTSFNLinearNetwork
return LTSFNLinearNetwork(
self.seq_len,
fh,
self.in_channels,
self.individual,
)._build()
@classmethod
def get_test_params(cls, parameter_set="default"):
"""Return testing parameter settings for the estimator.
Parameters
----------
parameter_set : str, default="default"
Name of the set of test parameters to return, for use in tests. If no
special parameters are defined for a value, will return ``"default"`` set.
Returns
-------
params : dict or list of dict
"""
params = [
{
"seq_len": 2,
"pred_len": 1,
"lr": 0.005,
"optimizer": "Adam",
"batch_size": 1,
"num_epochs": 1,
"individual": True,
}
]
return params