-
Notifications
You must be signed in to change notification settings - Fork 828
Expand file tree
/
Copy pathtest_transform.py
More file actions
1260 lines (1057 loc) · 38.4 KB
/
Copy pathtest_transform.py
File metadata and controls
1260 lines (1057 loc) · 38.4 KB
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
# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License").
# You may not use this file except in compliance with the License.
# A copy of the License is located at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# or in the "license" file accompanying this file. This file is distributed
# on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
# express or implied. See the License for the specific language governing
# permissions and limitations under the License.
from typing import Tuple, List
import numpy as np
import pandas as pd
from pandas.tseries.frequencies import to_offset
import pytest
import gluonts
from gluonts import time_feature, transform
from gluonts.core import fqname_for
from gluonts.core.serde import dump_json, load_json
from gluonts.dataset.common import DataEntry, ListDataset
from gluonts.dataset.field_names import FieldName
from gluonts.dataset.stat import ScaleHistogram, calculate_dataset_statistics
from gluonts.transform import (
CausalMeanValueImputation,
DummyValueImputation,
LastValueImputation,
MeanValueImputation,
RollingMeanValueImputation,
Valmap,
)
from gluonts.transform.convert import ToIntervalSizeFormat, erf, erfinv
from gluonts.transform.feature import CountTrailingZeros
FREQ = "1D"
TEST_VALUES = {
"is_train": [True, False],
"target": [np.zeros(0), np.random.rand(13), np.random.rand(100)],
"start": [
pd.Period("2012-01-02", freq="1D"),
pd.Period("1994-02-19 20:01:02", freq="3D"),
],
"use_prediction_features": [True, False],
"allow_target_padding": [True, False],
"lead_time": [0, 1, 10, 20],
}
def test_align_timestamp():
def aligned_with(date_str, freq):
return pd.Period(date_str, freq=freq).to_timestamp()
for _ in range(2):
assert aligned_with("2012-03-05 09:13:12", "min") == pd.Timestamp(
"2012-03-05 09:13:00"
)
assert aligned_with("2012-03-05 09:13:12", "2min") == pd.Timestamp(
"2012-03-05 09:13:00"
)
assert aligned_with("2012-03-05 09:13:12", "H") == pd.Timestamp(
"2012-03-05 09:00:00"
)
assert aligned_with("2012-03-05 09:13:12", "D") == pd.Timestamp(
"2012-03-05 00:00:00"
)
assert aligned_with("2012-03-05 09:13:12", "W") == pd.Timestamp(
"2012-03-05 00:00:00"
)
assert aligned_with("2012-03-05 09:13:12", "4W") == pd.Timestamp(
"2012-03-05 00:00:00"
)
assert aligned_with("2012-03-05 09:13:12", "M") == pd.Timestamp(
"2012-03-01 00:00:00"
)
assert aligned_with("2012-03-05 09:13:12", "3M") == pd.Timestamp(
"2012-03-01 00:00:00"
)
assert aligned_with("2012-03-05 09:13:12", "Y") == pd.Timestamp(
"2012-01-01 00:00:00"
)
assert aligned_with("2012-03-05 09:14:11", "min") == pd.Timestamp(
"2012-03-05 09:14:00"
)
assert aligned_with("2012-03-05 09:14:11", "2min") == pd.Timestamp(
"2012-03-05 09:14:00"
)
assert aligned_with("2012-03-05 09:14:11", "H") == pd.Timestamp(
"2012-03-05 09:00:00"
)
assert aligned_with("2012-03-05 09:14:11", "D") == pd.Timestamp(
"2012-03-05 00:00:00"
)
assert aligned_with("2012-03-05 09:14:11", "W") == pd.Timestamp(
"2012-03-05 00:00:00"
)
assert aligned_with("2012-03-05 09:14:11", "4W") == pd.Timestamp(
"2012-03-05 00:00:00"
)
assert aligned_with("2012-03-05 09:14:11", "M") == pd.Timestamp(
"2012-03-01 00:00:00"
)
assert aligned_with("2012-03-05 09:14:11", "3M") == pd.Timestamp(
"2012-03-01 00:00:00"
)
def test_add_method():
chain = transform.AddTimeFeatures(
start_field=FieldName.START,
target_field=FieldName.TARGET,
output_field="time_feat",
time_features=[
time_feature.day_of_week,
time_feature.day_of_month,
time_feature.month_of_year,
],
pred_length=24,
) + transform.AddAgeFeature(
target_field=FieldName.TARGET,
output_field="age",
pred_length=24,
log_scale=True,
)
assert isinstance(chain, transform.Chain)
@pytest.mark.parametrize("is_train", TEST_VALUES["is_train"])
@pytest.mark.parametrize("target", TEST_VALUES["target"])
@pytest.mark.parametrize("start", TEST_VALUES["start"])
def test_AddTimeFeatures(start, target, is_train: bool):
pred_length = 13
t = transform.AddTimeFeatures(
start_field=FieldName.START,
target_field=FieldName.TARGET,
output_field="myout",
pred_length=pred_length,
time_features=[time_feature.day_of_week, time_feature.day_of_month],
dtype=np.float64,
)
assert_serializable(t)
data = {"start": start, "target": target}
res = t.map_transform(data, is_train=is_train)
mat = res["myout"]
expected_length = len(target) + (0 if is_train else pred_length)
assert mat.shape == (2, expected_length)
tmp_idx = pd.period_range(
start=start, freq=start.freq, periods=expected_length
)
assert np.all(mat[0] == time_feature.day_of_week(tmp_idx))
assert np.all(mat[1] == time_feature.day_of_month(tmp_idx))
@pytest.mark.parametrize("is_train", TEST_VALUES["is_train"])
@pytest.mark.parametrize("target", TEST_VALUES["target"])
@pytest.mark.parametrize("start", TEST_VALUES["start"])
def test_AddTimeFeatures_empty_time_features(start, target, is_train: bool):
pred_length = 13
t = transform.AddTimeFeatures(
start_field=FieldName.START,
target_field=FieldName.TARGET,
output_field="myout",
pred_length=pred_length,
time_features=[],
)
assert_serializable(t)
data = {"start": start, "target": target}
res = t.map_transform(data, is_train=is_train)
assert res["myout"] is None
@pytest.mark.parametrize("is_train", TEST_VALUES["is_train"])
@pytest.mark.parametrize("target", TEST_VALUES["target"])
@pytest.mark.parametrize("start", TEST_VALUES["start"])
def test_AddAgeFeatures(start, target, is_train: bool):
pred_length = 13
t = transform.AddAgeFeature(
pred_length=pred_length,
target_field=FieldName.TARGET,
output_field="age",
log_scale=True,
)
assert_serializable(t)
data = {"start": start, "target": target}
out = t.map_transform(data, is_train=is_train)
expected_length = len(target) + (0 if is_train else pred_length)
assert out["age"].shape[-1] == expected_length
assert np.allclose(
out["age"],
np.log10(2.0 + np.arange(expected_length)).reshape(
(1, expected_length)
),
)
@pytest.mark.parametrize(
"pick_incomplete", TEST_VALUES["allow_target_padding"]
)
@pytest.mark.parametrize("is_train", TEST_VALUES["is_train"])
@pytest.mark.parametrize("target", TEST_VALUES["target"])
@pytest.mark.parametrize("start", TEST_VALUES["start"])
@pytest.mark.parametrize("lead_time", TEST_VALUES["lead_time"])
def test_InstanceSplitter(
start, target, lead_time: int, is_train: bool, pick_incomplete: bool
):
train_length = 100
pred_length = 13
t = transform.InstanceSplitter(
target_field=FieldName.TARGET,
is_pad_field=FieldName.IS_PAD,
start_field=FieldName.START,
forecast_start_field=FieldName.FORECAST_START,
instance_sampler=(
transform.UniformSplitSampler(
p=1.0,
min_past=0 if pick_incomplete else train_length,
min_future=lead_time + pred_length,
)
if is_train
else transform.TestSplitSampler(
min_past=0 if pick_incomplete else train_length
)
),
past_length=train_length,
future_length=pred_length,
lead_time=lead_time,
time_series_fields=["some_time_feature"],
)
assert_serializable(t)
other_feat = np.arange(len(target) + 100)
data = {
"start": start,
"target": target,
"some_time_feature": other_feat,
"some_other_col": "ABC",
}
if not is_train and not pick_incomplete and len(target) < train_length:
with pytest.raises(AssertionError):
out = list(t.flatmap_transform(data, is_train=is_train))
return
else:
out = list(t.flatmap_transform(data, is_train=is_train))
if is_train:
assert len(out) == max(
0,
len(target)
- pred_length
- lead_time
+ 1
- (0 if pick_incomplete else train_length),
)
else:
assert len(out) == 1
for o in out:
assert "target" not in o
assert "some_time_feature" not in o
assert "some_other_col" in o
assert len(o["past_some_time_feature"]) == train_length
assert len(o["past_target"]) == train_length
if is_train:
assert len(o["future_target"]) == pred_length
assert len(o["future_some_time_feature"]) == pred_length
else:
assert len(o["future_target"]) == 0
assert len(o["future_some_time_feature"]) == pred_length
# expected_length = len(target) + (0 if is_train else pred_length)
# assert len(out['age']) == expected_length
# assert np.all(out['age'] == np.log10(2.0 + np.arange(expected_length)))
@pytest.mark.parametrize("is_train", TEST_VALUES["is_train"])
@pytest.mark.parametrize("target", TEST_VALUES["target"])
@pytest.mark.parametrize("start", TEST_VALUES["start"])
@pytest.mark.parametrize(
"use_prediction_features", TEST_VALUES["use_prediction_features"]
)
@pytest.mark.parametrize(
"allow_target_padding", TEST_VALUES["allow_target_padding"]
)
def test_CanonicalInstanceSplitter(
start,
target,
is_train: bool,
use_prediction_features: bool,
allow_target_padding: bool,
):
train_length = 100
pred_length = 13
t = transform.CanonicalInstanceSplitter(
target_field=FieldName.TARGET,
is_pad_field=FieldName.IS_PAD,
start_field=FieldName.START,
forecast_start_field=FieldName.FORECAST_START,
instance_sampler=(
transform.UniformSplitSampler(
p=1.0,
min_past=train_length,
)
if is_train
else (
transform.ValidationSplitSampler()
if allow_target_padding
else transform.TestSplitSampler()
)
),
instance_length=train_length,
prediction_length=pred_length,
time_series_fields=["some_time_feature"],
allow_target_padding=allow_target_padding,
use_prediction_features=use_prediction_features,
)
assert_serializable(t)
other_feat = np.arange(len(target) + 100)
data = {
"start": start,
"target": target,
"some_time_feature": other_feat,
"some_other_col": "ABC",
}
out = list(t.flatmap_transform(data, is_train=is_train))
min_num_instances = 1 if allow_target_padding and not is_train else 0
if is_train:
assert len(out) == max(
min_num_instances, len(target) - train_length + 1
)
else:
assert len(out) == 1
for o in out:
assert "target" not in o
assert "future_target" not in o
assert "some_time_feature" not in o
assert "some_other_col" in o
assert len(o["past_some_time_feature"]) == train_length
assert len(o["past_target"]) == train_length
if use_prediction_features and not is_train:
assert len(o["future_some_time_feature"]) == pred_length
def test_Transformation():
train_length = 100
ds = gluonts.dataset.common.ListDataset(
[{"start": "2012-01-01", "target": [0.2] * train_length}], freq="1D"
)
pred_length = 10
t = transform.Chain(
[
transform.AddTimeFeatures(
start_field=FieldName.START,
target_field=FieldName.TARGET,
output_field="time_feat",
time_features=[
time_feature.day_of_week,
time_feature.day_of_month,
time_feature.month_of_year,
],
pred_length=pred_length,
),
transform.AddAgeFeature(
target_field=FieldName.TARGET,
output_field="age",
pred_length=pred_length,
log_scale=True,
),
transform.AddObservedValuesIndicator(
target_field=FieldName.TARGET, output_field="observed_values"
),
transform.VstackFeatures(
output_field="dynamic_feat",
input_fields=["age", "time_feat"],
drop_inputs=True,
),
transform.InstanceSplitter(
target_field=FieldName.TARGET,
is_pad_field=FieldName.IS_PAD,
start_field=FieldName.START,
forecast_start_field=FieldName.FORECAST_START,
instance_sampler=transform.ExpectedNumInstanceSampler(
num_instances=4
),
past_length=train_length,
future_length=pred_length,
time_series_fields=["dynamic_feat", "observed_values"],
),
]
)
assert_serializable(t)
for u in t(iter(ds), is_train=True):
print(u)
@pytest.mark.parametrize("is_train", TEST_VALUES["is_train"])
def test_multi_dim_transformation(is_train):
train_length = 10
first_dim: list = list(np.arange(1, 11, 1))
first_dim[-1] = "NaN"
second_dim: list = list(np.arange(11, 21, 1))
second_dim[0] = "NaN"
ds = gluonts.dataset.common.ListDataset(
data_iter=[{"start": "2012-01-01", "target": [first_dim, second_dim]}],
freq="1D",
one_dim_target=False,
)
pred_length = 2
# Looks weird - but this is necessary to assert the nan entries correctly.
first_dim[-1] = np.nan
second_dim[0] = np.nan
t = transform.Chain(
[
transform.AddTimeFeatures(
start_field=FieldName.START,
target_field=FieldName.TARGET,
output_field="time_feat",
time_features=[
time_feature.day_of_week,
time_feature.day_of_month,
time_feature.month_of_year,
],
pred_length=pred_length,
),
transform.AddAgeFeature(
target_field=FieldName.TARGET,
output_field="age",
pred_length=pred_length,
log_scale=True,
),
transform.AddObservedValuesIndicator(
target_field=FieldName.TARGET,
output_field="observed_values",
imputation_method=None,
),
transform.VstackFeatures(
output_field="dynamic_feat",
input_fields=["age", "time_feat"],
drop_inputs=True,
),
transform.InstanceSplitter(
target_field=FieldName.TARGET,
is_pad_field=FieldName.IS_PAD,
start_field=FieldName.START,
forecast_start_field=FieldName.FORECAST_START,
instance_sampler=(
transform.ExpectedNumInstanceSampler(
num_instances=4, min_future=pred_length
)
if is_train
else transform.TestSplitSampler()
),
past_length=train_length,
future_length=pred_length,
time_series_fields=["dynamic_feat", "observed_values"],
output_NTC=False,
),
]
)
assert_serializable(t)
if is_train:
for u in t(iter(ds), is_train=True):
assert_shape(u["past_target"], (2, 10))
assert_shape(u["past_dynamic_feat"], (4, 10))
assert_shape(u["past_observed_values"], (2, 10))
assert_shape(u["future_target"], (2, 2))
assert_padded_array(
u["past_observed_values"],
np.array([[1.0] * 9 + [0.0], [0.0] + [1.0] * 9]),
u["past_is_pad"],
)
assert_padded_array(
u["past_target"],
np.array([first_dim, second_dim]),
u["past_is_pad"],
)
else:
for u in t(iter(ds), is_train=False):
assert_shape(u["past_target"], (2, 10))
assert_shape(u["past_dynamic_feat"], (4, 10))
assert_shape(u["past_observed_values"], (2, 10))
assert_shape(u["future_target"], (2, 0))
assert_padded_array(
u["past_observed_values"],
np.array([[1.0] * 9 + [0.0], [0.0] + [1.0] * 9]),
u["past_is_pad"],
)
assert_padded_array(
u["past_target"],
np.array([first_dim, second_dim]),
u["past_is_pad"],
)
def test_ExpectedNumInstanceSampler():
N = 6
train_length = 2
pred_length = 1
ds = make_dataset(N, train_length)
t = transform.InstanceSplitter(
target_field=FieldName.TARGET,
is_pad_field=FieldName.IS_PAD,
start_field=FieldName.START,
forecast_start_field=FieldName.FORECAST_START,
instance_sampler=transform.ExpectedNumInstanceSampler(
num_instances=4, min_future=pred_length
),
past_length=train_length,
future_length=pred_length,
)
assert_serializable(t)
scale_hist = ScaleHistogram()
repetition = 2
for i in range(repetition):
for data in t(iter(ds), is_train=True):
target_values = data["past_target"]
# for simplicity, discard values that are zeros to avoid confusion with padding
target_values = target_values[target_values > 0]
scale_hist.add(target_values)
expected_values = {i: 2**i * repetition for i in range(1, N)}
assert expected_values == scale_hist.bin_counts
def test_BucketInstanceSampler():
N = 6
train_length = 2
pred_length = 1
ds = make_dataset(N, train_length)
dataset_stats = calculate_dataset_statistics(ds)
t = transform.InstanceSplitter(
target_field=FieldName.TARGET,
is_pad_field=FieldName.IS_PAD,
start_field=FieldName.START,
forecast_start_field=FieldName.FORECAST_START,
instance_sampler=transform.BucketInstanceSampler(
scale_histogram=dataset_stats.scale_histogram
),
past_length=train_length,
future_length=pred_length,
)
assert_serializable(t)
scale_hist = ScaleHistogram()
repetition = 200
for i in range(repetition):
for data in t(iter(ds), is_train=True):
target_values = data["past_target"]
# for simplicity, discard values that are zeros to avoid confusion with padding
target_values = target_values[target_values > 0]
scale_hist.add(target_values)
expected_values = {i: repetition for i in range(1, N)}
found_values = scale_hist.bin_counts
for i in range(1, N):
assert abs(
expected_values[i] - found_values[i] < expected_values[i] * 0.3
)
def test_cdf_to_gaussian_transformation():
def make_test_data():
target = [
0,
0,
0,
0,
10,
10,
20,
20,
30,
30,
40,
50,
59,
60,
60,
70,
80,
90,
100,
]
np.random.shuffle(target)
multi_dim_target = np.array([target, target]).transpose()
past_is_pad = np.atleast_2d(np.zeros_like(target)).transpose()
past_observed_target = np.array(
[np.ones_like(target), np.ones_like(target)]
).transpose()
ds = gluonts.dataset.common.ListDataset(
# Mimic output from InstanceSplitter
[
{
"start": "2012-01-01",
"target": multi_dim_target,
"past_target": multi_dim_target,
"future_target": multi_dim_target,
"past_is_pad": past_is_pad,
f"past_{FieldName.OBSERVED_VALUES}": past_observed_target,
}
],
freq="1D",
one_dim_target=False,
)
return ds
def make_fake_output(u: DataEntry):
return np.expand_dims(
np.expand_dims(u["past_target_cdf"], axis=0), axis=0
)
ds = make_test_data()
t = transform.CDFtoGaussianTransform(
target_field=FieldName.TARGET,
observed_values_field=FieldName.OBSERVED_VALUES,
max_context_length=20,
target_dim=2,
)
for u in t(iter(ds), is_train=False):
fake_output = make_fake_output(u)
# Fake transformation chain output
u["past_target_sorted"] = np.expand_dims(
u["past_target_sorted"], axis=0
)
u["slopes"] = np.expand_dims(u["slopes"], axis=0)
u["intercepts"] = np.expand_dims(u["intercepts"], axis=0)
back_transformed = transform.cdf_to_gaussian_forward_transform(
u, fake_output
)
# Get any sample/batch (slopes[i][:, d]they are all the same)
back_transformed = back_transformed[0][0]
original_target = u["target"]
# Original target and back-transformed target should be the same
assert np.allclose(original_target, back_transformed)
def test_gaussian_cdf():
pytest.importorskip("scipy")
from scipy.stats import norm
x = np.array(
[-1000, -100, -10]
+ np.linspace(-2, 2, 1001).tolist()
+ [10, 100, 1000]
)
y_gluonts = transform.CDFtoGaussianTransform.standard_gaussian_cdf(x)
y_scipy = norm.cdf(x)
assert np.allclose(y_gluonts, y_scipy, atol=1e-7)
def test_gaussian_ppf():
pytest.importorskip("scipy")
from scipy.stats import norm
x = np.linspace(0.0001, 0.9999, 1001)
y_gluonts = transform.CDFtoGaussianTransform.standard_gaussian_ppf(x)
y_scipy = norm.ppf(x)
assert np.allclose(y_gluonts, y_scipy, atol=1e-7)
def test_target_dim_indicator():
target = np.array([0, 2, 3, 10]).tolist()
multi_dim_target = np.array([target, target, target, target])
dataset = gluonts.dataset.common.ListDataset(
data_iter=[{"start": "2012-01-01", "target": multi_dim_target}],
freq="1D",
one_dim_target=False,
)
t = transform.TargetDimIndicator(
target_field=FieldName.TARGET, field_name="target_dimensions"
)
for data_entry in t(dataset, is_train=True):
assert (
data_entry["target_dimensions"] == np.array([0, 1, 2, 3])
).all()
@pytest.fixture
def point_process_dataset():
ia_times = np.array([0.2, 0.7, 0.2, 0.5, 0.3, 0.3, 0.2, 0.1])
marks = np.array([0, 1, 2, 0, 1, 2, 2, 2])
return ListDataset(
[
{
"target": np.c_[ia_times, marks].T,
"start": pd.Timestamp("2011-01-01 00:00:00"),
"end": pd.Timestamp("2011-01-01 03:00:00"),
}
],
freq="H",
one_dim_target=False,
use_timestamp=True,
)
class MockContinuousTimeSampler(transform.ContinuousTimePointSampler):
ret_values: List[float]
def __call__(self, *args, **kwargs):
return np.array(self.ret_values)
@pytest.fixture
def test_ctsplitter_mask_sorted(point_process_dataset):
d = next(iter(point_process_dataset))
ia_times = d["target"][0, :]
ts = np.cumsum(ia_times)
splitter = transform.ContinuousTimeInstanceSplitter(
past_interval_length=2,
future_interval_length=1,
instance_sampler=transform.ContinuousTimeUniformSampler(
num_instances=10,
min_past=2,
min_future=1,
),
freq=to_offset("H"),
)
# no boundary conditions
res = splitter._mask_sorted(ts, 1, 2)
assert all([a == b for a, b in zip([2, 3, 4], res)])
# lower bound equal, exclusive of upper bound
res = splitter._mask_sorted(np.array([1, 2, 3, 4, 5, 6]), 1, 2)
assert all([a == b for a, b in zip([0], res)])
def test_ctsplitter_no_train_last_point(point_process_dataset):
splitter = transform.ContinuousTimeInstanceSplitter(
past_interval_length=2,
future_interval_length=1,
instance_sampler=transform.ContinuousTimePredictionSampler(
allow_empty_interval=False,
min_past=2,
),
freq=to_offset("H"),
)
iter_de = splitter(point_process_dataset, is_train=False)
d_out = next(iter(iter_de))
assert "future_target" not in d_out
assert "future_valid_length" not in d_out
assert "past_target" in d_out
assert "past_valid_length" in d_out
assert d_out["past_valid_length"] == 6
assert np.allclose(
[0.1, 0.5, 0.3, 0.3, 0.2, 0.1], d_out["past_target"][..., 0], atol=0.01
)
def test_ctsplitter_train_correct(point_process_dataset):
splitter = transform.ContinuousTimeInstanceSplitter(
past_interval_length=1,
future_interval_length=1,
instance_sampler=MockContinuousTimeSampler(
ret_values=[1.01, 1.5, 1.99]
),
freq=to_offset("H"),
)
iter_de = splitter(point_process_dataset, is_train=True)
outputs = list(iter_de)
assert outputs[0]["past_valid_length"] == 2
assert outputs[0]["future_valid_length"] == 3
assert np.allclose(
outputs[0]["past_target"], np.array([[0.19, 0.7], [0, 1]]).T
)
assert np.allclose(
outputs[0]["future_target"], np.array([[0.09, 0.5, 0.3], [2, 0, 1]]).T
)
assert outputs[1]["past_valid_length"] == 2
assert outputs[1]["future_valid_length"] == 4
assert outputs[2]["past_valid_length"] == 3
assert outputs[2]["future_valid_length"] == 3
def test_ctsplitter_train_correct_out_count(point_process_dataset):
# produce new TPP data by shuffling existing TS instance
def shuffle_iterator(num_duplications=5):
for entry in point_process_dataset:
for i in range(num_duplications):
d = dict.copy(entry)
d["target"] = np.random.permutation(d["target"].T).T
yield d
splitter = transform.ContinuousTimeInstanceSplitter(
past_interval_length=1,
future_interval_length=1,
instance_sampler=MockContinuousTimeSampler(
ret_values=[1.01, 1.5, 1.99]
),
freq=to_offset("H"),
)
iter_de = splitter(shuffle_iterator(), is_train=True)
outputs = list(iter_de)
assert len(outputs) == 5 * 3
def test_ctsplitter_train_samples_correct_times(point_process_dataset):
splitter = transform.ContinuousTimeInstanceSplitter(
past_interval_length=1.25,
future_interval_length=1.25,
instance_sampler=transform.ContinuousTimeUniformSampler(
num_instances=20,
min_past=1.25,
min_future=1.25,
),
freq=to_offset("H"),
)
iter_de = splitter(point_process_dataset, is_train=True)
assert all(
[
(
pd.Timestamp("2011-01-01 01:15:00")
<= d["forecast_start"]
<= pd.Timestamp("2011-01-01 01:45:00")
)
for d in iter_de
]
)
def test_ctsplitter_train_short_intervals(point_process_dataset):
splitter = transform.ContinuousTimeInstanceSplitter(
0.01,
0.01,
instance_sampler=MockContinuousTimeSampler(
ret_values=[1.01, 1.5, 1.99]
),
freq=to_offset("H"),
)
iter_de = splitter(point_process_dataset, is_train=True)
for d in iter_de:
assert d["future_valid_length"] == d["past_valid_length"] == 0
assert np.prod(np.shape(d["past_target"])) == 0
assert np.prod(np.shape(d["future_target"])) == 0
def test_AddObservedIndicator():
"""
Tests the different methods to impute missing values.
"""
array_values = [
np.array([np.nan, 1.0, 1.0, np.nan, 2.0, np.nan, 1.0, np.nan]),
np.array([np.nan]),
np.array([np.nan, np.nan, np.nan, np.nan, np.nan]),
np.array([10.0]),
]
l_methods = [
"dummy_value",
"mean",
"causal_mean",
"last_value",
"rolling_mean1",
"rolling_mean10",
]
d_method_instances = {
"dummy_value": DummyValueImputation(),
"mean": MeanValueImputation(),
"causal_mean": CausalMeanValueImputation(),
"last_value": LastValueImputation(),
"rolling_mean1": RollingMeanValueImputation(1),
"rolling_mean10": RollingMeanValueImputation(10),
}
d_expected_results = {
"dummy_value": [
np.array([0.0, 1.0, 1.0, 0.0, 2.0, 0.0, 1.0, 0.0]),
np.array([0.0]),
np.array([0.0, 0.0, 0.0, 0.0, 0.0]),
np.array([10.0]),
],
"mean": [
np.array([1.25, 1.0, 1.0, 1.25, 2.0, 1.25, 1.0, 1.25]),
np.array([0.0]),
np.array([0.0, 0.0, 0.0, 0.0, 0.0]),
np.array([10.0]),
],
"causal_mean": [
np.array([1.0, 1.0, 1.0, 1.0, 2.0, 1.2, 1.0, 9 / 7]),
np.array([0.0]),
np.array([0.0, 0.0, 0.0, 0.0, 0.0]),
np.array([10.0]),
],
"last_value": [
np.array([1.0, 1.0, 1.0, 1.0, 2.0, 2.0, 1.0, 1.0]),
np.array([0.0]),
np.array([0.0, 0.0, 0.0, 0.0, 0.0]),
np.array([10.0]),
],
"rolling_mean10": [
np.array([1.0, 1.0, 1.0, 1.0, 2.0, 1.1, 1.0, 1.2]),
np.array([0.0]),
np.array([0.0, 0.0, 0.0, 0.0, 0.0]),
np.array([10.0]),
],
"rolling_mean1": [
np.array([1.0, 1.0, 1.0, 1.0, 2.0, 2.0, 1.0, 1.0]),
np.array([0.0]),
np.array([0.0, 0.0, 0.0, 0.0, 0.0]),
np.array([10.0]),
],
}
expected_missindicators = [
np.array([0.0, 1.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0]),
np.array([0.0]),
np.array([0.0, 0.0, 0.0, 0.0, 0.0]),
np.array([1.0]),
]
for i, array_value in enumerate(array_values):
for method in l_methods:
transfo = transform.AddObservedValuesIndicator(
target_field=FieldName.TARGET,
output_field=FieldName.OBSERVED_VALUES,
imputation_method=d_method_instances[method],
)