/
preprocessing.py
1805 lines (1579 loc) · 80 KB
/
preprocessing.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
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# AUTOGENERATED! DO NOT EDIT! File to edit: ../../nbs/009_data.preprocessing.ipynb.
# %% ../../nbs/009_data.preprocessing.ipynb 3
from __future__ import annotations
from ..imports import *
import re
from joblib import dump, load
import sklearn
from sklearn.base import BaseEstimator, TransformerMixin
from pandas._libs.tslibs.timestamps import Timestamp
from fastcore.transform import Transform, ItemTransform, Pipeline
from fastai.data.transforms import Categorize
from fastai.data.load import DataLoader
from fastai.tabular.core import df_shrink_dtypes, make_date
from ..utils import *
from .core import *
from .preparation import *
# %% auto 0
__all__ = ['Nan2Value', 'TSRandomStandardize', 'default_date_attr', 'PD_TIME_UNITS', 'StandardScaler', 'RobustScaler',
'Normalizer', 'BoxCox', 'YeoJohnshon', 'Quantile', 'ToNumpyCategory', 'OneHot', 'TSNan2Value',
'TSStandardize', 'TSNormalize', 'TSStandardizeTuple', 'TSCatEncode', 'TSDropFeatByKey', 'TSClipOutliers',
'TSClip', 'TSSelfMissingness', 'TSRobustScale', 'get_stats_with_uncertainty', 'get_random_stats',
'TSGaussianStandardize', 'TSDiff', 'TSLog', 'TSCyclicalPosition', 'TSLinearPosition', 'TSMissingness',
'TSPositionGaps', 'TSRollingMean', 'TSLogReturn', 'TSAdd', 'TSClipByVar', 'TSDropVars', 'TSOneHotEncode',
'TSPosition', 'PatchEncoder', 'TSPatchEncoder', 'TSTuplePatchEncoder', 'TSShrinkDataFrame', 'object2date',
'TSOneHotEncoder', 'TSCategoricalEncoder', 'TSTargetEncoder', 'TSDateTimeEncoder', 'TSDropIfTrueCols',
'TSApplyFunction', 'TSMissingnessEncoder', 'TSSortByColumns', 'TSSelectColumns', 'TSStepsSinceStart',
'TSStandardScaler', 'TSRobustScaler', 'TSAddMissingTimestamps', 'TSDropDuplicates', 'TSFillMissing',
'Preprocessor', 'ReLabeler']
# %% ../../nbs/009_data.preprocessing.ipynb 6
class ToNumpyCategory(Transform):
"Categorize a numpy batch"
order = 90
def __init__(self, **kwargs):
super().__init__(**kwargs)
def encodes(self, o: np.ndarray):
self.type = type(o)
self.cat = Categorize()
self.cat.setup(o)
self.vocab = self.cat.vocab
return np.asarray(stack([self.cat(oi) for oi in o]))
def decodes(self, o: np.ndarray):
return stack([self.cat.decode(oi) for oi in o])
def decodes(self, o: torch.Tensor):
return stack([self.cat.decode(oi) for oi in o])
# %% ../../nbs/009_data.preprocessing.ipynb 9
class OneHot(Transform):
"One-hot encode/ decode a batch"
order = 90
def __init__(self, n_classes=None, **kwargs):
self.n_classes = n_classes
super().__init__(**kwargs)
def encodes(self, o: torch.Tensor):
if not self.n_classes: self.n_classes = len(np.unique(o))
return torch.eye(self.n_classes)[o]
def encodes(self, o: np.ndarray):
o = ToNumpyCategory()(o)
if not self.n_classes: self.n_classes = len(np.unique(o))
return np.eye(self.n_classes)[o]
def decodes(self, o: torch.Tensor): return torch.argmax(o, dim=-1)
def decodes(self, o: np.ndarray): return np.argmax(o, axis=-1)
# %% ../../nbs/009_data.preprocessing.ipynb 13
class TSNan2Value(Transform):
"Replaces any nan values by a predefined value or median"
order = 90
def __init__(self, value=0, median=False, by_sample_and_var=True, sel_vars=None):
store_attr()
if not ismin_torch("1.8"):
raise ValueError('This function only works with Pytorch>=1.8.')
def encodes(self, o:TSTensor):
if self.sel_vars is not None:
mask = torch.isnan(o[:, self.sel_vars])
if mask.any() and self.median:
if self.by_sample_and_var:
median = torch.nanmedian(o[:, self.sel_vars], dim=2, keepdim=True)[0].repeat(1, 1, o.shape[-1])
o[:, self.sel_vars][mask] = median[mask]
else:
o[:, self.sel_vars] = torch.nan_to_num(o[:, self.sel_vars], torch.nanmedian(o[:, self.sel_vars]))
o[:, self.sel_vars] = torch.nan_to_num(o[:, self.sel_vars], self.value)
else:
mask = torch.isnan(o)
if mask.any() and self.median:
if self.by_sample_and_var:
median = torch.nanmedian(o, dim=2, keepdim=True)[0].repeat(1, 1, o.shape[-1])
o[mask] = median[mask]
else:
o = torch.nan_to_num(o, torch.nanmedian(o))
o = torch.nan_to_num(o, self.value)
return o
Nan2Value = TSNan2Value
# %% ../../nbs/009_data.preprocessing.ipynb 16
class TSStandardize(Transform):
"""Standardizes batch of type `TSTensor`
Args:
- mean: you can pass a precalculated mean value as a torch tensor which is the one that will be used, or leave as None, in which case
it will be estimated using a batch.
- std: you can pass a precalculated std value as a torch tensor which is the one that will be used, or leave as None, in which case
it will be estimated using a batch. If both mean and std values are passed when instantiating TSStandardize, the rest of arguments won't be used.
- by_sample: if True, it will calculate mean and std for each individual sample. Otherwise based on the entire batch.
- by_var:
* False: mean and std will be the same for all variables.
* True: a mean and std will be be different for each variable.
* a list of ints: (like [0,1,3]) a different mean and std will be set for each variable on the list. Variables not included in the list
won't be standardized.
* a list that contains a list/lists: (like[0, [1,3]]) a different mean and std will be set for each element of the list. If multiple elements are
included in a list, the same mean and std will be set for those variable in the sublist/s. (in the example a mean and std is determined for
variable 0, and another one for variables 1 & 3 - the same one). Variables not included in the list won't be standardized.
- by_step: if False, it will standardize values for each time step.
- exc_vars: list of variables that won't be standardized.
- eps: it avoids dividing by 0
- use_single_batch: if True a single training batch will be used to calculate mean & std. Else the entire training set will be used.
"""
parameters, order = L('mean', 'std'), 90
_setup = True # indicates it requires set up
def __init__(self, mean=None, std=None, by_sample=False, by_var=False, by_step=False, exc_vars=None, eps=1e-8, use_single_batch=True, verbose=False, **kwargs):
super().__init__(**kwargs)
self.mean = tensor(mean) if mean is not None else None
self.std = tensor(std) if std is not None else None
self._setup = (mean is None or std is None) and not by_sample
self.eps = eps
self.by_sample, self.by_var, self.by_step = by_sample, by_var, by_step
drop_axes = []
if by_sample: drop_axes.append(0)
if by_var: drop_axes.append(1)
if by_step: drop_axes.append(2)
self.exc_vars = exc_vars
self.axes = tuple([ax for ax in (0, 1, 2) if ax not in drop_axes])
if by_var and is_listy(by_var):
self.list_axes = tuple([ax for ax in (0, 1, 2) if ax not in drop_axes]) + (1,)
self.use_single_batch = use_single_batch
self.verbose = verbose
if self.mean is not None or self.std is not None:
pv(f'{self.__class__.__name__} mean={self.mean}, std={self.std}, by_sample={self.by_sample}, by_var={self.by_var}, by_step={self.by_step}\n',
self.verbose)
@classmethod
def from_stats(cls, mean, std): return cls(mean, std)
def setups(self, dl: DataLoader):
if self._setup:
if not self.use_single_batch:
o = dl.dataset.__getitem__([slice(None)])[0]
else:
o, *_ = dl.one_batch()
if self.by_var and is_listy(self.by_var):
shape = torch.mean(o, dim=self.axes, keepdim=self.axes!=()).shape
mean = torch.zeros(*shape, device=o.device)
std = torch.ones(*shape, device=o.device)
for v in self.by_var:
if not is_listy(v): v = [v]
mean[:, v] = torch_nanmean(o[:, v], dim=self.axes if len(v) == 1 else self.list_axes, keepdim=True)
std[:, v] = torch.clamp_min(torch_nanstd(o[:, v], dim=self.axes if len(v) == 1 else self.list_axes, keepdim=True), self.eps)
else:
mean = torch_nanmean(o, dim=self.axes, keepdim=self.axes!=())
std = torch.clamp_min(torch_nanstd(o, dim=self.axes, keepdim=self.axes!=()), self.eps)
if self.exc_vars is not None:
mean[:, self.exc_vars] = 0.
std[:, self.exc_vars] = 1.
self.mean, self.std = mean, std
if len(self.mean.shape) == 0:
pv(f'{self.__class__.__name__} mean={self.mean}, std={self.std}, by_sample={self.by_sample}, by_var={self.by_var}, by_step={self.by_step}\n',
self.verbose)
else:
pv(f'{self.__class__.__name__} mean shape={self.mean.shape}, std shape={self.std.shape}, by_sample={self.by_sample}, by_var={self.by_var}, by_step={self.by_step}\n',
self.verbose)
self._setup = False
elif self.by_sample: self.mean, self.std = torch.zeros(1), torch.ones(1)
def encodes(self, o:TSTensor):
if self.by_sample:
if self.by_var and is_listy(self.by_var):
shape = torch.mean(o, dim=self.axes, keepdim=self.axes!=()).shape
mean = torch.zeros(*shape, device=o.device)
std = torch.ones(*shape, device=o.device)
for v in self.by_var:
if not is_listy(v): v = [v]
mean[:, v] = torch_nanmean(o[:, v], dim=self.axes if len(v) == 1 else self.list_axes, keepdim=True)
std[:, v] = torch.clamp_min(torch_nanstd(o[:, v], dim=self.axes if len(v) == 1 else self.list_axes, keepdim=True), self.eps)
else:
mean = torch_nanmean(o, dim=self.axes, keepdim=self.axes!=())
std = torch.clamp_min(torch_nanstd(o, dim=self.axes, keepdim=self.axes!=()), self.eps)
if self.exc_vars is not None:
mean[:, self.exc_vars] = 0.
std[:, self.exc_vars] = 1.
self.mean, self.std = mean, std
return (o - self.mean) / self.std
def decodes(self, o:TSTensor):
if self.mean is None or self.std is None: return o
return o * self.std + self.mean
def __repr__(self): return f'{self.__class__.__name__}(by_sample={self.by_sample}, by_var={self.by_var}, by_step={self.by_step})'
# %% ../../nbs/009_data.preprocessing.ipynb 24
@patch
def mul_min(x:torch.Tensor|TSTensor|NumpyTensor, axes=(), keepdim=False):
if axes == (): return retain_type(x.min(), x)
axes = reversed(sorted(axes if is_listy(axes) else [axes]))
min_x = x
for ax in axes: min_x, _ = min_x.min(ax, keepdim)
return retain_type(min_x, x)
@patch
def mul_max(x:torch.Tensor|TSTensor|NumpyTensor, axes=(), keepdim=False):
if axes == (): return retain_type(x.max(), x)
axes = reversed(sorted(axes if is_listy(axes) else [axes]))
max_x = x
for ax in axes: max_x, _ = max_x.max(ax, keepdim)
return retain_type(max_x, x)
class TSNormalize(Transform):
"Normalizes batch of type `TSTensor`"
parameters, order = L('min', 'max'), 90
_setup = True # indicates it requires set up
def __init__(self, min=None, max=None, range=(-1, 1), by_sample=False, by_var=False, by_step=False, clip_values=True,
use_single_batch=True, verbose=False, **kwargs):
super().__init__(**kwargs)
self.min = tensor(min) if min is not None else None
self.max = tensor(max) if max is not None else None
self._setup = (self.min is None and self.max is None) and not by_sample
self.range_min, self.range_max = range
self.by_sample, self.by_var, self.by_step = by_sample, by_var, by_step
drop_axes = []
if by_sample: drop_axes.append(0)
if by_var: drop_axes.append(1)
if by_step: drop_axes.append(2)
self.axes = tuple([ax for ax in (0, 1, 2) if ax not in drop_axes])
if by_var and is_listy(by_var):
self.list_axes = tuple([ax for ax in (0, 1, 2) if ax not in drop_axes]) + (1,)
self.clip_values = clip_values
self.use_single_batch = use_single_batch
self.verbose = verbose
if self.min is not None or self.max is not None:
pv(f'{self.__class__.__name__} min={self.min}, max={self.max}, by_sample={self.by_sample}, by_var={self.by_var}, by_step={self.by_step}\n', self.verbose)
@classmethod
def from_stats(cls, min, max, range_min=0, range_max=1): return cls(min, max, range_min, range_max)
def setups(self, dl: DataLoader):
if self._setup:
if not self.use_single_batch:
o = dl.dataset.__getitem__([slice(None)])[0]
else:
o, *_ = dl.one_batch()
if self.by_var and is_listy(self.by_var):
shape = torch.mean(o, dim=self.axes, keepdim=self.axes!=()).shape
_min = torch.zeros(*shape, device=o.device) + self.range_min
_max = torch.zeros(*shape, device=o.device) + self.range_max
for v in self.by_var:
if not is_listy(v): v = [v]
_min[:, v] = o[:, v].mul_min(self.axes if len(v) == 1 else self.list_axes, keepdim=self.axes!=())
_max[:, v] = o[:, v].mul_max(self.axes if len(v) == 1 else self.list_axes, keepdim=self.axes!=())
else:
_min, _max = o.mul_min(self.axes, keepdim=self.axes!=()), o.mul_max(self.axes, keepdim=self.axes!=())
self.min, self.max = _min, _max
if len(self.min.shape) == 0:
pv(f'{self.__class__.__name__} min={self.min}, max={self.max}, by_sample={self.by_sample}, by_var={self.by_var}, by_step={self.by_step}\n',
self.verbose)
else:
pv(f'{self.__class__.__name__} min shape={self.min.shape}, max shape={self.max.shape}, by_sample={self.by_sample}, by_var={self.by_var}, by_step={self.by_step}\n',
self.verbose)
self._setup = False
elif self.by_sample: self.min, self.max = -torch.ones(1), torch.ones(1)
def encodes(self, o:TSTensor):
if self.by_sample:
if self.by_var and is_listy(self.by_var):
shape = torch.mean(o, dim=self.axes, keepdim=self.axes!=()).shape
_min = torch.zeros(*shape, device=o.device) + self.range_min
_max = torch.ones(*shape, device=o.device) + self.range_max
for v in self.by_var:
if not is_listy(v): v = [v]
_min[:, v] = o[:, v].mul_min(self.axes, keepdim=self.axes!=())
_max[:, v] = o[:, v].mul_max(self.axes, keepdim=self.axes!=())
else:
_min, _max = o.mul_min(self.axes, keepdim=self.axes!=()), o.mul_max(self.axes, keepdim=self.axes!=())
self.min, self.max = _min, _max
output = ((o - self.min) / (self.max - self.min)) * (self.range_max - self.range_min) + self.range_min
if self.clip_values:
if self.by_var and is_listy(self.by_var):
for v in self.by_var:
if not is_listy(v): v = [v]
output[:, v] = torch.clamp(output[:, v], self.range_min, self.range_max)
else:
output = torch.clamp(output, self.range_min, self.range_max)
return output
def __repr__(self): return f'{self.__class__.__name__}(by_sample={self.by_sample}, by_var={self.by_var}, by_step={self.by_step})'
# %% ../../nbs/009_data.preprocessing.ipynb 28
class TSStandardizeTuple(ItemTransform):
"Standardizes X (and y if provided)"
parameters, order = L('x_mean', 'x_std', 'y_mean', 'y_std'), 90
def __init__(self, x_mean, x_std, y_mean=None, y_std=None, eps=1e-5):
self.x_mean, self.x_std = torch.as_tensor(x_mean).float(), torch.as_tensor(x_std + eps).float()
self.y_mean = self.x_mean if y_mean is None else torch.as_tensor(y_mean).float()
self.y_std = self.x_std if y_std is None else torch.as_tensor(y_std + eps).float()
def encodes(self, xy):
if len(xy) == 2:
x, y = xy
x = (x - self.x_mean) / self.x_std
y = (y - self.y_mean) / self.y_std
return (x, y)
elif len(xy) == 1:
x = xy[0]
x = (x - self.x_mean) / self.x_std
return (x, )
def decodes(self, xy):
if len(xy) == 2:
x, y = xy
x = x * self.x_std + self.x_mean
y = y * self.y_std + self.y_mean
return (x, y)
elif len(xy) == 1:
x = xy[0]
x = x * self.x_std + self.x_mean
return (x, )
# %% ../../nbs/009_data.preprocessing.ipynb 30
class TSCatEncode(Transform):
"Encodes a variable based on a categorical array"
def __init__(self, a, sel_var):
a_key = np.unique(a)
a_val = np.arange(1, len(a_key) + 1)
self.o2i = dict(zip(a_key, a_val))
self.a_key = torch.from_numpy(a_key)
self.sel_var = sel_var
def encodes(self, o:TSTensor):
o_ = o[:, self.sel_var]
o_val = torch.zeros_like(o_)
o_in_a = torch.isin(o_, self.a_key.to(o.device))
o_val[o_in_a] = o_[o_in_a].cpu().apply_(self.o2i.get).to(o.device) # apply is not available for cuda!!
o[:, self.sel_var] = o_val
return o
# %% ../../nbs/009_data.preprocessing.ipynb 33
class TSDropFeatByKey(Transform):
"""Randomly drops selected features at selected steps based
with a given probability per feature, step and a key variable"""
parameters, order = 'p', 90
def __init__(self,
key_var, # int representing the variable that contains the key information
p, # array of shape (n_keys, n_features, n_steps) representing the probabilities of dropping a feature at a given step for a given key
sel_vars, # int or slice or list of ints or array of ints representing the variables to drop
sel_steps=None, # int or slice or list of ints or array of ints representing the steps to drop
**kwargs,
):
super().__init__(**kwargs)
if isinstance(p, np.ndarray):
p = torch.from_numpy(p)
if not isinstance(sel_vars, slice):
if isinstance(sel_vars, Integral): sel_vars = [sel_vars]
sel_vars = np.asarray(sel_vars)
if not isinstance(sel_steps, slice) and sel_steps is not None:
sel_vars = sel_vars.reshape(-1, 1)
if sel_steps is None:
sel_steps = slice(None)
elif not isinstance(sel_steps, slice):
if isinstance(sel_steps, Integral): sel_steps = [sel_steps]
sel_steps = np.asarray(sel_steps)
if not isinstance(sel_vars, slice):
sel_steps = sel_steps.reshape(1, -1)
self.key_var, self.p = key_var, p
self.sel_vars, self.sel_steps = sel_vars, sel_steps
if p.shape[-1] == 1:
if isinstance(self.sel_vars, slice) or isinstance(self.sel_steps, slice):
self._idxs = [slice(None), slice(None), slice(None), 0]
else:
self._idxs = [slice(None), 0, slice(None), slice(None), 0]
else:
if isinstance(self.sel_vars, slice) or isinstance(self.sel_steps, slice):
self._idxs = self._idxs = [slice(None), np.arange(p.shape[-1]), slice(None), np.arange(p.shape[-1])]
else:
self._idxs = [slice(None), 0, np.arange(p.shape[-1]), slice(None), np.arange(p.shape[-1])]
def encodes(self, o:TSTensor):
o_slice = o[:, self.sel_vars, self.sel_steps]
o_values = o[:, self.key_var, self.sel_steps]
o_values = torch.nan_to_num(o_values)
o_values = torch.round(o_values).long()
if self.p.shape[-1] == 1:
p = self.p[o_values][self._idxs].permute(0, 2, 1)
else:
p = self.p[o_values][self._idxs].permute(1, 2, 0)
mask = torch.rand_like(o_slice) < p
o_slice[mask] = np.nan
o[:, self.sel_vars, self.sel_steps] = o_slice
return o
# %% ../../nbs/009_data.preprocessing.ipynb 35
class TSClipOutliers(Transform):
"Clip outliers batch of type `TSTensor` based on the IQR"
parameters, order = L('min', 'max'), 90
_setup = True # indicates it requires set up
def __init__(self, min=None, max=None, by_sample=False, by_var=False, use_single_batch=False, verbose=False, **kwargs):
super().__init__(**kwargs)
self.min = tensor(min) if min is not None else tensor(-np.inf)
self.max = tensor(max) if max is not None else tensor(np.inf)
self.by_sample, self.by_var = by_sample, by_var
self._setup = (min is None or max is None) and not by_sample
if by_sample and by_var: self.axis = (2)
elif by_sample: self.axis = (1, 2)
elif by_var: self.axis = (0, 2)
else: self.axis = None
self.use_single_batch = use_single_batch
self.verbose = verbose
if min is not None or max is not None:
pv(f'{self.__class__.__name__} min={min}, max={max}\n', self.verbose)
def setups(self, dl: DataLoader):
if self._setup:
if not self.use_single_batch:
o = dl.dataset.__getitem__([slice(None)])[0]
else:
o, *_ = dl.one_batch()
min, max = get_outliers_IQR(o, self.axis)
self.min, self.max = tensor(min), tensor(max)
if self.axis is None: pv(f'{self.__class__.__name__} min={self.min}, max={self.max}, by_sample={self.by_sample}, by_var={self.by_var}\n',
self.verbose)
else: pv(f'{self.__class__.__name__} min={self.min.shape}, max={self.max.shape}, by_sample={self.by_sample}, by_var={self.by_var}\n',
self.verbose)
self._setup = False
def encodes(self, o:TSTensor):
if self.axis is None: return torch.clamp(o, self.min, self.max)
elif self.by_sample:
min, max = get_outliers_IQR(o, axis=self.axis)
self.min, self.max = o.new(min), o.new(max)
return torch_clamp(o, self.min, self.max)
def __repr__(self): return f'{self.__class__.__name__}(by_sample={self.by_sample}, by_var={self.by_var})'
# %% ../../nbs/009_data.preprocessing.ipynb 37
class TSClip(Transform):
"Clip batch of type `TSTensor`"
parameters, order = L('min', 'max'), 90
def __init__(self, min=-6, max=6, **kwargs):
super().__init__(**kwargs)
self.min = torch.tensor(min)
self.max = torch.tensor(max)
def encodes(self, o:TSTensor):
return torch.clamp(o, self.min, self.max)
def __repr__(self): return f'{self.__class__.__name__}(min={self.min}, max={self.max})'
# %% ../../nbs/009_data.preprocessing.ipynb 39
class TSSelfMissingness(Transform):
"Applies missingness from samples in a batch to random samples in the batch for selected variables"
order = 90
def __init__(self, sel_vars=None, **kwargs):
self.sel_vars = sel_vars
super().__init__(**kwargs)
def encodes(self, o:TSTensor):
if self.sel_vars is not None:
mask = rotate_axis0(torch.isnan(o[:, self.sel_vars]))
o[:, self.sel_vars] = o[:, self.sel_vars].masked_fill(mask, np.nan)
else:
mask = rotate_axis0(torch.isnan(o))
o.masked_fill_(mask, np.nan)
return o
# %% ../../nbs/009_data.preprocessing.ipynb 41
class TSRobustScale(Transform):
r"""This Scaler removes the median and scales the data according to the quantile range (defaults to IQR: Interquartile Range)"""
parameters, order = L('median', 'iqr'), 90
_setup = True # indicates it requires set up
def __init__(self, median=None, iqr=None, quantile_range=(25.0, 75.0), use_single_batch=True, exc_vars=None, eps=1e-8, verbose=False, **kwargs):
super().__init__(**kwargs)
self.median = tensor(median) if median is not None else None
self.iqr = tensor(iqr) if iqr is not None else None
self._setup = median is None or iqr is None
self.use_single_batch = use_single_batch
self.exc_vars = exc_vars
self.eps = eps
self.verbose = verbose
self.quantile_range = quantile_range
def setups(self, dl: DataLoader):
if self._setup:
if not self.use_single_batch:
o = dl.dataset.__getitem__([slice(None)])[0]
else:
o, *_ = dl.one_batch()
new_o = o.permute(1,0,2).flatten(1)
median = get_percentile(new_o, 50, axis=1)
iqrmin, iqrmax = get_outliers_IQR(new_o, axis=1, quantile_range=self.quantile_range)
self.median = median.unsqueeze(0)
self.iqr = torch.clamp_min((iqrmax - iqrmin).unsqueeze(0), self.eps)
if self.exc_vars is not None:
self.median[:, self.exc_vars] = 0
self.iqr[:, self.exc_vars] = 1
pv(f'{self.__class__.__name__} median={self.median.shape} iqr={self.iqr.shape}', self.verbose)
self._setup = False
else:
if self.median is None: self.median = torch.zeros(1, device=dl.device)
if self.iqr is None: self.iqr = torch.ones(1, device=dl.device)
def encodes(self, o:TSTensor):
return (o - self.median) / self.iqr
def __repr__(self): return f'{self.__class__.__name__}(quantile_range={self.quantile_range}, use_single_batch={self.use_single_batch})'
# %% ../../nbs/009_data.preprocessing.ipynb 44
def get_stats_with_uncertainty(o, sel_vars=None, sel_vars_zero_mean_unit_var=False, bs=64, n_trials=None, axis=(0,2)):
o_dtype = o.dtype
if n_trials is None: n_trials = len(o) // bs
random_idxs = random_choice(len(o), n_trials * bs, n_trials * bs > len(o))
oi_mean = []
oi_std = []
start = 0
for i in progress_bar(range(n_trials)):
idxs = random_idxs[start:start + bs]
start += bs
if hasattr(o, 'oindex'):
oi = o.index[idxs]
if hasattr(o, 'compute'):
oi = o[idxs].compute()
else:
oi = o[idxs]
oi_mean.append(np.nanmean(oi.astype('float32'), axis=axis, keepdims=True))
oi_std.append(np.nanstd(oi.astype('float32'), axis=axis, keepdims=True))
oi_mean = np.concatenate(oi_mean)
oi_std = np.concatenate(oi_std)
E_mean = np.nanmean(oi_mean, axis=0, keepdims=True).astype(o_dtype)
S_mean = np.nanstd(oi_mean, axis=0, keepdims=True).astype(o_dtype)
E_std = np.nanmean(oi_std, axis=0, keepdims=True).astype(o_dtype)
S_std = np.nanstd(oi_std, axis=0, keepdims=True).astype(o_dtype)
if sel_vars is not None:
non_sel_vars = np.isin(np.arange(o.shape[1]), sel_vars, invert=True)
if sel_vars_zero_mean_unit_var:
E_mean[:, non_sel_vars] = 0 # zero mean
E_std[:, non_sel_vars] = 1 # unit var
S_mean[:, non_sel_vars] = 0 # no uncertainty
S_std[:, non_sel_vars] = 0 # no uncertainty
return np.stack([E_mean, S_mean, E_std, S_std])
def get_random_stats(E_mean, S_mean, E_std, S_std):
mult = np.random.normal(0, 1, 2)
new_mean = E_mean + S_mean * mult[0]
new_std = E_std + S_std * mult[1]
return new_mean, new_std
class TSGaussianStandardize(Transform):
"Scales each batch using modeled mean and std based on UNCERTAINTY MODELING FOR OUT-OF-DISTRIBUTION GENERALIZATION https://arxiv.org/abs/2202.03958"
parameters, order = L('E_mean', 'S_mean', 'E_std', 'S_std'), 90
def __init__(self,
E_mean : np.ndarray, # Mean expected value
S_mean : np.ndarray, # Uncertainty (standard deviation) of the mean
E_std : np.ndarray, # Standard deviation expected value
S_std : np.ndarray, # Uncertainty (standard deviation) of the standard deviation
eps=1e-8, # (epsilon) small amount added to standard deviation to avoid deviding by zero
split_idx=0, # Flag to indicate to which set is this transofrm applied. 0: training, 1:validation, None:both
**kwargs,
):
self.E_mean, self.S_mean = torch.from_numpy(E_mean), torch.from_numpy(S_mean)
self.E_std, self.S_std = torch.from_numpy(E_std), torch.from_numpy(S_std)
self.eps = eps
super().__init__(split_idx=split_idx, **kwargs)
def encodes(self, o:TSTensor):
mult = torch.normal(0, 1, (2,), device=o.device)
new_mean = self.E_mean + self.S_mean * mult[0]
new_std = torch.clamp(self.E_std + self.S_std * mult[1], self.eps)
return (o - new_mean) / new_std
TSRandomStandardize = TSGaussianStandardize
# %% ../../nbs/009_data.preprocessing.ipynb 47
class TSDiff(Transform):
"Differences batch of type `TSTensor`"
order = 90
def __init__(self, lag=1, pad=True, **kwargs):
super().__init__(**kwargs)
self.lag, self.pad = lag, pad
def encodes(self, o:TSTensor):
return torch_diff(o, lag=self.lag, pad=self.pad)
def __repr__(self): return f'{self.__class__.__name__}(lag={self.lag}, pad={self.pad})'
# %% ../../nbs/009_data.preprocessing.ipynb 49
class TSLog(Transform):
"Log transforms batch of type `TSTensor` + 1. Accepts positive and negative numbers"
order = 90
def __init__(self, ex=None, **kwargs):
self.ex = ex
super().__init__(**kwargs)
def encodes(self, o:TSTensor):
output = torch.zeros_like(o)
output[o > 0] = torch.log1p(o[o > 0])
output[o < 0] = -torch.log1p(torch.abs(o[o < 0]))
if self.ex is not None: output[...,self.ex,:] = o[...,self.ex,:]
return output
def decodes(self, o:TSTensor):
output = torch.zeros_like(o)
output[o > 0] = torch.exp(o[o > 0]) - 1
output[o < 0] = -torch.exp(torch.abs(o[o < 0])) + 1
if self.ex is not None: output[...,self.ex,:] = o[...,self.ex,:]
return output
def __repr__(self): return f'{self.__class__.__name__}()'
# %% ../../nbs/009_data.preprocessing.ipynb 51
class TSCyclicalPosition(Transform):
"Concatenates the position along the sequence as 2 additional variables (sine and cosine)"
order = 90
def __init__(self,
cyclical_var=None, # Optional variable to indicate the steps withing the cycle (ie minute of the day)
magnitude=None, # Added for compatibility. It's not used.
drop_var=False, # Flag to indicate if the cyclical var is removed
**kwargs
):
super().__init__(**kwargs)
self.cyclical_var, self.drop_var = cyclical_var, drop_var
def encodes(self, o: TSTensor):
bs,nvars,seq_len = o.shape
if self.cyclical_var is None:
sin, cos = sincos_encoding(seq_len, device=o.device)
output = torch.cat([o, sin.reshape(1,1,-1).repeat(bs,1,1), cos.reshape(1,1,-1).repeat(bs,1,1)], 1)
return output
else:
sin = torch.sin(o[:, [self.cyclical_var]]/seq_len * 2 * np.pi)
cos = torch.cos(o[:, [self.cyclical_var]]/seq_len * 2 * np.pi)
if self.drop_var:
exc_vars = np.isin(np.arange(nvars), self.cyclical_var, invert=True)
output = torch.cat([o[:, exc_vars], sin, cos], 1)
else:
output = torch.cat([o, sin, cos], 1)
return output
# %% ../../nbs/009_data.preprocessing.ipynb 54
class TSLinearPosition(Transform):
"Concatenates the position along the sequence as 1 additional variable"
order = 90
def __init__(self,
linear_var:int=None, # Optional variable to indicate the steps withing the cycle (ie minute of the day)
var_range:tuple=None, # Optional range indicating min and max values of the linear variable
magnitude=None, # Added for compatibility. It's not used.
drop_var:bool=False, # Flag to indicate if the cyclical var is removed
lin_range:tuple=(-1,1),
**kwargs):
self.linear_var, self.var_range, self.drop_var, self.lin_range = linear_var, var_range, drop_var, lin_range
super().__init__(**kwargs)
def encodes(self, o: TSTensor):
bs,nvars,seq_len = o.shape
if self.linear_var is None:
lin = linear_encoding(seq_len, device=o.device, lin_range=self.lin_range)
output = torch.cat([o, lin.reshape(1,1,-1).repeat(bs,1,1)], 1)
else:
linear_var = o[:, [self.linear_var]]
if self.var_range is None:
lin = (linear_var - linear_var.min()) / (linear_var.max() - linear_var.min())
else:
lin = (linear_var - self.var_range[0]) / (self.var_range[1] - self.var_range[0])
lin = (linear_var - self.lin_range[0]) / (self.lin_range[1] - self.lin_range[0])
if self.drop_var:
exc_vars = np.isin(np.arange(nvars), self.linear_var, invert=True)
output = torch.cat([o[:, exc_vars], lin], 1)
else:
output = torch.cat([o, lin], 1)
return output
return output
# %% ../../nbs/009_data.preprocessing.ipynb 57
class TSMissingness(Transform):
"Concatenates data missingness for selected features along the sequence as additional variables"
order = 90
def __init__(self, sel_vars=None, feature_idxs=None, magnitude=None, **kwargs):
sel_vars = sel_vars or feature_idxs
self.sel_vars = listify(sel_vars)
super().__init__(**kwargs)
def encodes(self, o: TSTensor):
if self.sel_vars is not None:
missingness = o[:, self.sel_vars].isnan()
else:
missingness = o.isnan()
return torch.cat([o, missingness], 1)
# %% ../../nbs/009_data.preprocessing.ipynb 59
class TSPositionGaps(Transform):
"""Concatenates gaps for selected features along the sequence as additional variables"""
order = 90
def __init__(self, sel_vars=None, feature_idxs=None, magnitude=None, forward=True, backward=False,
nearest=False, normalize=True, **kwargs):
sel_vars = sel_vars or feature_idxs
self.sel_vars = listify(sel_vars)
self.gap_fn = partial(get_gaps, forward=forward, backward=backward, nearest=nearest, normalize=normalize)
super().__init__(**kwargs)
def encodes(self, o: TSTensor):
if self.sel_vars:
gaps = self.gap_fn(o[:, self.sel_vars])
else:
gaps = self.gap_fn(o)
return torch.cat([o, gaps], 1)
# %% ../../nbs/009_data.preprocessing.ipynb 61
class TSRollingMean(Transform):
"""Calculates the rolling mean for all/ selected features alongside the sequence
It replaces the original values or adds additional variables (default)
If nan values are found, they will be filled forward and backward"""
order = 90
def __init__(self, sel_vars=None, feature_idxs=None, magnitude=None, window=2, replace=False, **kwargs):
sel_vars = sel_vars or feature_idxs
self.sel_vars = listify(sel_vars)
self.rolling_mean_fn = partial(rolling_moving_average, window=window)
self.replace = replace
super().__init__(**kwargs)
def encodes(self, o: TSTensor):
if self.sel_vars:
if torch.isnan(o[:, self.sel_vars]).any():
o[:, self.sel_vars] = fbfill_sequence(o[:, self.sel_vars])
rolling_mean = self.rolling_mean_fn(o[:, self.sel_vars])
if self.replace:
o[:, self.sel_vars] = rolling_mean
return o
else:
if torch.isnan(o).any():
o = fbfill_sequence(o)
rolling_mean = self.rolling_mean_fn(o)
if self.replace: return rolling_mean
return torch.cat([o, rolling_mean], 1)
# %% ../../nbs/009_data.preprocessing.ipynb 63
class TSLogReturn(Transform):
"Calculates log-return of batch of type `TSTensor`. For positive values only"
order = 90
def __init__(self, lag=1, pad=True, **kwargs):
super().__init__(**kwargs)
self.lag, self.pad = lag, pad
def encodes(self, o:TSTensor):
return torch_diff(torch.log(o), lag=self.lag, pad=self.pad)
def __repr__(self): return f'{self.__class__.__name__}(lag={self.lag}, pad={self.pad})'
# %% ../../nbs/009_data.preprocessing.ipynb 65
class TSAdd(Transform):
"Add a defined amount to each batch of type `TSTensor`."
order = 90
def __init__(self, add, **kwargs):
super().__init__(**kwargs)
self.add = add
def encodes(self, o:TSTensor):
return torch.add(o, self.add)
def __repr__(self): return f'{self.__class__.__name__}(lag={self.lag}, pad={self.pad})'
# %% ../../nbs/009_data.preprocessing.ipynb 67
class TSClipByVar(Transform):
"""Clip batch of type `TSTensor` by variable
Args:
var_min_max: list of tuples containing variable index, min value (or None) and max value (or None)
"""
order = 90
def __init__(self, var_min_max, **kwargs):
super().__init__(**kwargs)
self.var_min_max = var_min_max
def encodes(self, o:TSTensor):
for v,m,M in self.var_min_max:
o[:, v] = torch.clamp(o[:, v], m, M)
return o
# %% ../../nbs/009_data.preprocessing.ipynb 69
class TSDropVars(Transform):
"Drops selected variable from the input"
order = 90
def __init__(self, drop_vars, **kwargs):
super().__init__(**kwargs)
self.drop_vars = drop_vars
def encodes(self, o:TSTensor):
exc_vars = np.isin(np.arange(o.shape[1]), self.drop_vars, invert=True)
return o[:, exc_vars]
# %% ../../nbs/009_data.preprocessing.ipynb 71
class TSOneHotEncode(Transform):
order = 90
def __init__(self,
sel_var:int, # Variable that is one-hot encoded
unique_labels:list, # List containing all labels (excluding nan values)
add_na:bool=False, # Flag to indicate if values not included in vocab should be set as 0
drop_var:bool=True, # Flag to indicate if the selected var is removed
magnitude=None, # Added for compatibility. It's not used.
**kwargs
):
unique_labels = listify(unique_labels)
self.sel_var = sel_var
self.unique_labels = unique_labels
self.n_classes = len(unique_labels) + add_na
self.add_na = add_na
self.drop_var = drop_var
super().__init__(**kwargs)
def encodes(self, o: TSTensor):
bs, n_vars, seq_len = o.shape
o_var = o[:, [self.sel_var]]
ohe_var = torch.zeros(bs, self.n_classes, seq_len, device=o.device)
if self.add_na:
is_na = torch.isin(o_var, o_var.new(list(self.unique_labels)), invert=True) # not available in dict
ohe_var[:, [0]] = is_na.to(ohe_var.dtype)
for i,l in enumerate(self.unique_labels):
ohe_var[:, [i + self.add_na]] = (o_var == l).to(ohe_var.dtype)
if self.drop_var:
exc_vars = torch.isin(torch.arange(o.shape[1], device=o.device), self.sel_var, invert=True)
output = torch.cat([o[:, exc_vars], ohe_var], 1)
else:
output = torch.cat([o, ohe_var], 1)
return output
# %% ../../nbs/009_data.preprocessing.ipynb 77
class TSPosition(Transform):
order = 90
def __init__(self,
steps:list, # List containing the steps passed as an additional variable. Theu should be normalized.
magnitude=None, # Added for compatibility. It's not used.
**kwargs
):
self.steps = torch.from_numpy(np.asarray(steps)).reshape(1, 1, -1)
super().__init__(**kwargs)
def encodes(self, o: TSTensor):
bs = o.shape[0]
steps = self.steps.expand(bs, -1, -1).to(device=o.device, dtype=o.dtype)
return torch.cat([o, steps], 1)
# %% ../../nbs/009_data.preprocessing.ipynb 79
import torch
import torch.nn.functional as F
class PatchEncoder():
"Creates a sequence of patches from a 3d input tensor."
def __init__(self,
patch_len:int, # Number of time steps in each patch.
patch_stride:int=None, # Stride of the patch.
pad_at_start:bool=True, # If True, pad the input tensor at the start to ensure that the input tensor is evenly divisible by the patch length.
value:float=0.0, # Value to pad the input tensor with.
seq_len:int=None, # Number of time steps in the input tensor. If None, make sure seq_len >= patch_len and a multiple of stride
merge_dims:bool=True, # If True, merge channels within the same patch.
reduction:str='none', # type of reduction applied. Available: "none", "mean", "min", "max", "mode"
reduction_dim:int=-1, # dimension where the reduction is applied
swap_dims:tuple=None, # If True, swap the time and channel dimensions.
):
super().__init__()
self.seq_len = seq_len
self.patch_len = patch_len
self.patch_stride = patch_stride or patch_len
self.pad_at_start = pad_at_start
self.value = value
self.merge_dims = merge_dims
assert reduction in ["none", "mean", "min", "max", "mode"]
self.reduction = reduction
self.reduction_dim = reduction_dim
self.swap_dims = swap_dims
if seq_len is None:
self.pad_size = 0
elif self.seq_len < self.patch_len:
self.pad_size = self.patch_len - self.seq_len
else:
if (self.seq_len % self.patch_len) % self.patch_stride == 0:
self.pad_size = 0
else:
self.pad_size = self.patch_stride - (self.seq_len % self.patch_len) % self.patch_stride
def __call__(self,
x: torch.Tensor # 3d input tensor with shape [batch size, sequence length, channels]
) -> torch.Tensor: # Transformed tensor of patches with shape [batch size, channels*patch length, number of patches]
if x.ndim == 2:
x = x[:, None]
bs, c_in, *_ = x.size()
if not bs:
return x
if self.pad_size:
x = F.pad(x, (self.pad_size, 0), value=self.value) if self.pad_at_start else F.pad(x, (0, self.pad_size), value=self.value)
x = x.unfold(2, self.patch_len, self.patch_stride)
x = x.permute(0, 1, 3, 2)
if self.merge_dims:
x = x.reshape(bs, c_in * self.patch_len, -1)
if self.reduction == "mean":
x = x.mean(self.reduction_dim)
elif self.reduction == "min":
x = x.min(self.reduction_dim).values
elif self.reduction == "max":
x = x.max(self.reduction_dim).values
elif self.reduction == "mode":
x = x.mode(self.reduction_dim).values
if self.swap_dims:
x = x.swapaxes(*self.swap_dims)
return x
# %% ../../nbs/009_data.preprocessing.ipynb 81
class TSPatchEncoder(Transform):
"Tansforms a time series into a sequence of patches along the last dimension"
order = 90
def __init__(self,
patch_len:int, # Number of time steps in each patch.
patch_stride:int=None, # Stride of the patch.
pad_at_start:bool=True, # If True, pad the input tensor at the start to ensure that the input tensor is evenly divisible by the patch length.
value:float=0.0, # Value to pad the input tensor with.
seq_len:int=None, # Number of time steps in the input tensor. If None, make sure seq_len >= patch_len and a multiple of stride
merge_dims:bool=True, # If True, merge channels within the same patch.
reduction:str='none', # type of reduction applied. Available: "none", "mean", "min", "max", "mode"
reduction_dim:int=-2, # dimension where the y reduction is applied.
swap_dims:tuple=None, # If True, swap the time and channel dimensions.
):
super().__init__()
self.patch_encoder = PatchEncoder(patch_len=patch_len,
patch_stride=patch_stride,
pad_at_start=pad_at_start,
value=value,
seq_len=seq_len,
merge_dims=merge_dims,
reduction=reduction,
reduction_dim=reduction_dim,
swap_dims=swap_dims)
def encodes(self, o:TSTensor):
return self.patch_encoder(o)
# %% ../../nbs/009_data.preprocessing.ipynb 83
from fastcore.transform import ItemTransform
class TSTuplePatchEncoder(ItemTransform):
"Tansforms a time series with x and y into sequences of patches along the last dimension"
order = 90
def __init__(self,
patch_len:int, # Number of time steps in each patch.
patch_stride:int=None, # Stride of the patch.
pad_at_start:bool=True, # If True, pad the input tensor at the start to ensure that the input tensor is evenly divisible by the patch length.
value:float=0.0, # Value to pad the input tensor with.
seq_len:int=None, # Number of time steps in the input tensor. If None, make sure seq_len >= patch_len and a multiple of stride
merge_dims:bool=True, # If True, merge y channels within the same patch.
reduction:str='none', # type of reduction applied to y. Available: "none", "mean", "min", "max", "mode"
reduction_dim:int=-2, # dimension where the y reduction is applied.
swap_dims:tuple=None, # If True, swap the time and channel dimensions in y.
):
super().__init__()
self.x_patch_encoder = PatchEncoder(patch_len=patch_len,
patch_stride=patch_stride,
pad_at_start=pad_at_start,
value=value,
seq_len=seq_len)
self.y_patch_encoder = PatchEncoder(patch_len=patch_len,
patch_stride=patch_stride,
pad_at_start=pad_at_start,
value=value,