-
Notifications
You must be signed in to change notification settings - Fork 89
/
_classes.py
2325 lines (1992 loc) · 91.6 KB
/
_classes.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
#!/usr/bin/env python3 -u
# -*- coding: utf-8 -*-
# copyright: aeon developers, BSD-3-Clause License (see LICENSE file)
"""Metrics classes to assess performance on forecasting task.
Classes named as ``*Score`` return a value to maximize: the higher the better.
Classes named as ``*Error`` or ``*Loss`` return a value to minimize:
the lower the better.
"""
from copy import deepcopy
from inspect import getfullargspec, isfunction, signature
from warnings import warn
import numpy as np
import pandas as pd
from sklearn.utils import check_array
from aeon.datatypes import VectorizedDF, check_is_scitype, convert_to
from aeon.performance_metrics.base import BaseMetric
from aeon.performance_metrics.forecasting._functions import (
geometric_mean_absolute_error,
geometric_mean_relative_absolute_error,
geometric_mean_relative_squared_error,
geometric_mean_squared_error,
mean_absolute_error,
mean_absolute_percentage_error,
mean_absolute_scaled_error,
mean_asymmetric_error,
mean_linex_error,
mean_relative_absolute_error,
mean_squared_error,
mean_squared_percentage_error,
mean_squared_scaled_error,
median_absolute_error,
median_absolute_percentage_error,
median_absolute_scaled_error,
median_relative_absolute_error,
median_squared_error,
median_squared_percentage_error,
median_squared_scaled_error,
relative_loss,
)
__author__ = ["mloning", "Tomasz Chodakowski", "RNKuhns", "fkiraly"]
__all__ = [
"make_forecasting_scorer",
"MeanAbsoluteScaledError",
"MedianAbsoluteScaledError",
"MeanSquaredScaledError",
"MedianSquaredScaledError",
"MeanAbsoluteError",
"MeanSquaredError",
"MedianAbsoluteError",
"MedianSquaredError",
"GeometricMeanAbsoluteError",
"GeometricMeanSquaredError",
"MeanAbsolutePercentageError",
"MedianAbsolutePercentageError",
"MeanSquaredPercentageError",
"MedianSquaredPercentageError",
"MeanRelativeAbsoluteError",
"MedianRelativeAbsoluteError",
"GeometricMeanRelativeAbsoluteError",
"GeometricMeanRelativeSquaredError",
"MeanAsymmetricError",
"MeanLinexError",
"RelativeLoss",
]
def _coerce_to_scalar(obj):
"""Coerce obj to scalar, from polymorphic input scalar or pandas."""
if isinstance(obj, pd.DataFrame):
assert len(obj) == 1
assert len(obj.columns) == 1
return obj.iloc[0, 0]
if isinstance(obj, pd.Series):
assert len(obj) == 1
return obj.iloc[0]
return obj
def _coerce_to_df(obj):
"""Coerce to pd.DataFrame, from polymorphic input scalar or pandas."""
return pd.DataFrame(obj)
class BaseForecastingErrorMetric(BaseMetric):
"""Base class for defining forecasting error metrics in aeon.
Extends aeon's BaseMetric to the forecasting interface. Forecasting error
metrics measure the error (loss) between forecasts and true values.
`multioutput` and `multilevel` parameters can be used to control averaging
across variables (`multioutput`) and (non-temporal) hierarchy levels (`multilevel`).
Parameters
----------
multioutput : {'raw_values', 'uniform_average'} or array-like of shape \
(n_outputs,), default='uniform_average'
Defines whether and how to aggregate metric for across variables.
If 'uniform_average' (default), errors are mean-averaged across variables.
If array-like, errors are weighted averaged across variables, values as weights.
If 'raw_values', does not average errors across variables, columns are retained.
multilevel : {'raw_values', 'uniform_average', 'uniform_average_time'}
Defines how to aggregate metric for hierarchical data (with levels).
If 'uniform_average' (default), errors are mean-averaged across levels.
If 'uniform_average_time', errors are mean-averaged across rows.
If 'raw_values', does not average errors across levels, hierarchy is retained.
"""
_tags = {
"requires-y-train": False,
"requires-y-pred-benchmark": False,
"univariate-only": False,
"lower_is_better": True,
# "y_inner_mtype": ["pd.DataFrame", "pd-multiindex", "pd_multiindex_hier"]
"inner_implements_multilevel": False,
}
def __init__(self, multioutput="uniform_average", multilevel="uniform_average"):
self.multioutput = multioutput
self.multilevel = multilevel
if not hasattr(self, "name"):
self.name = type(self).__name__
super(BaseForecastingErrorMetric, self).__init__()
def __call__(self, y_true, y_pred, **kwargs):
"""Calculate metric value using underlying metric function.
Parameters
----------
y_true : time series in aeon compatible data container format
Ground truth (correct) target values
y can be in one of the following formats:
Series scitype: pd.Series, pd.DataFrame, or np.ndarray (1D or 2D)
Panel scitype: pd.DataFrame with 2-level row MultiIndex,
3D np.ndarray, list of Series pd.DataFrame, or nested pd.DataFrame
Hierarchical scitype: pd.DataFrame with 3 or more level row MultiIndex
y_pred :time series in aeon compatible data container format
Forecasted values to evaluate
must be of same format as y_true, same indices and columns if indexed
Returns
-------
loss : float, np.ndarray, or pd.DataFrame
Calculated metric, averaged or by variable.
float if self.multioutput="uniform_average" or array-like
and self.multilevel="uniform_average" or "uniform_average_time"
value is metric averaged over variables and levels (see class docstring)
np.ndarray of shape (y_true.columns,) if self.multioutput="raw_values"
and self.multilevel="uniform_average" or "uniform_average_time"
i-th entry is metric calculated for i-th variable
pd.DataFrame if self.multilevel=raw.values
of shape (n_levels, ) if self.multioutput = "uniform_average" or array
of shape (n_levels, y_true.columns) if self.multioutput="raw_values"
metric is applied per level, row averaging (yes/no) as in multioutput
"""
return self.evaluate(y_true, y_pred, **kwargs)
def evaluate(self, y_true, y_pred, **kwargs):
"""Evaluate the desired metric on given inputs.
Parameters
----------
y_true : time series in aeon compatible data container format
Ground truth (correct) target values
y can be in one of the following formats:
Series scitype: pd.Series, pd.DataFrame, or np.ndarray (1D or 2D)
Panel scitype: pd.DataFrame with 2-level row MultiIndex,
3D np.ndarray, list of Series pd.DataFrame, or nested pd.DataFrame
Hierarchical scitype: pd.DataFrame with 3 or more level row MultiIndex
y_pred :time series in aeon compatible data container format
Forecasted values to evaluate
must be of same format as y_true, same indices and columns if indexed
Returns
-------
loss : float, np.ndarray, or pd.DataFrame
Calculated metric, averaged or by variable.
float if self.multioutput="uniform_average" or array-like
and self.multilevel="uniform_average" or "uniform_average_time"
value is metric averaged over variables and levels (see class docstring)
np.ndarray of shape (y_true.columns,) if self.multioutput="raw_values"
and self.multilevel="uniform_average" or "uniform_average_time"
i-th entry is metric calculated for i-th variable
pd.DataFrame if self.multilevel=raw.values
of shape (n_levels, ) if self.multioutput = "uniform_average" or array
of shape (n_levels, y_true.columns) if self.multioutput="raw_values"
metric is applied per level, row averaging (yes/no) as in multioutput
"""
multioutput = self.multioutput
multilevel = self.multilevel
# Input checks and conversions
y_true_inner, y_pred_inner, multioutput, multilevel, kwargs = self._check_ys(
y_true, y_pred, multioutput, multilevel, **kwargs
)
requires_vectorization = isinstance(y_true_inner, VectorizedDF)
if not requires_vectorization:
# pass to inner function
out_df = self._evaluate(y_true=y_true_inner, y_pred=y_pred_inner, **kwargs)
else:
out_df = self._evaluate_vectorized(
y_true=y_true_inner, y_pred=y_pred_inner, **kwargs
)
if multilevel == "uniform_average":
out_df = out_df.mean(axis=0)
# if level is averaged, but not variables, return numpy
if multioutput == "raw_values":
out_df = out_df.values
if multilevel == "uniform_average" and multioutput == "uniform_average":
out_df = _coerce_to_scalar(out_df)
if multilevel == "raw_values":
out_df = _coerce_to_df(out_df)
return out_df
def _evaluate(self, y_true, y_pred, **kwargs):
"""Evaluate the desired metric on given inputs.
private _evaluate containing core logic, called from evaluate
By default this uses evaluate_by_index, taking arithmetic mean over time points.
Parameters
----------
y_true : time series in aeon compatible data container format
Ground truth (correct) target values
y can be in one of the following formats:
Series scitype: pd.Series, pd.DataFrame, or np.ndarray (1D or 2D)
Panel scitype: pd.DataFrame with 2-level row MultiIndex,
3D np.ndarray, list of Series pd.DataFrame, or nested pd.DataFrame
Hierarchical scitype: pd.DataFrame with 3 or more level row MultiIndex
y_pred :time series in aeon compatible data container format
Forecasted values to evaluate
must be of same format as y_true, same indices and columns if indexed
Returns
-------
loss : float or np.ndarray
Calculated metric, averaged or by variable.
float if self.multioutput="uniform_average" or array-like
value is metric averaged over variables (see class docstring)
np.ndarray of shape (y_true.columns,) if self.multioutput="raw_values"
i-th entry is metric calculated for i-th variable
"""
# multioutput = self.multioutput
# multilevel = self.multilevel
try:
index_df = self._evaluate_by_index(y_true, y_pred, **kwargs)
return index_df.mean(axis=0)
except RecursionError:
RecursionError("Must implement one of _evaluate or _evaluate_by_index")
def _evaluate_vectorized(self, y_true, y_pred, **kwargs):
"""Vectorized version of _evaluate.
Runs _evaluate for all instances in y_true, y_pred,
and returns results in a hierarchical pandas.DataFrame.
Parameters
----------
y_true : pandas.DataFrame with MultiIndex, last level time-like
y_pred : pandas.DataFrame with MultiIndex, last level time-like
non-time-like instanceso of y_true, y_pred must be identical
"""
kwargsi = deepcopy(kwargs)
n_batches = len(y_true)
res = []
for i in range(n_batches):
if "y_train" in kwargs:
kwargsi["y_train"] = kwargs["y_train"][i]
if "y_pred_benchmark" in kwargs:
kwargsi["y_pred_benchmark"] = kwargs["y_pred_benchmark"][i]
resi = self._evaluate(y_true=y_true[i], y_pred=y_pred[i], **kwargsi)
if isinstance(resi, float):
resi = pd.Series(resi)
if self.multioutput == "raw_values":
assert isinstance(resi, np.ndarray)
df = pd.DataFrame(columns=y_true.X.columns)
df.loc[0] = resi
resi = df
res += [resi]
out_df = y_true.reconstruct(res)
if out_df.index.nlevels == y_true.X.index.nlevels:
out_df.index = out_df.index.droplevel(-1)
return out_df
def evaluate_by_index(self, y_true, y_pred, **kwargs):
"""Return the metric evaluated at each time point.
Parameters
----------
y_true : time series in aeon compatible data container format
Ground truth (correct) target values
y can be in one of the following formats:
Series scitype: pd.Series, pd.DataFrame, or np.ndarray (1D or 2D)
Panel scitype: pd.DataFrame with 2-level row MultiIndex,
3D np.ndarray, list of Series pd.DataFrame, or nested pd.DataFrame
Hierarchical scitype: pd.DataFrame with 3 or more level row MultiIndex
y_pred :time series in aeon compatible data container format
Forecasted values to evaluate
must be of same format as y_true, same indices and columns if indexed
Returns
-------
loss : pd.Series or pd.DataFrame
Calculated metric, by time point (default=jackknife pseudo-values).
pd.Series if self.multioutput="uniform_average" or array-like
index is equal to index of y_true
entry at index i is metric at time i, averaged over variables
pd.DataFrame if self.multioutput="raw_values"
index and columns equal to those of y_true
i,j-th entry is metric at time i, at variable j
"""
multioutput = self.multioutput
multilevel = self.multilevel
# Input checks and conversions
y_true_inner, y_pred_inner, multioutput, multilevel, kwargs = self._check_ys(
y_true, y_pred, multioutput, multilevel, **kwargs
)
# pass to inner function
out_df = self._evaluate_by_index(y_true_inner, y_pred_inner, **kwargs)
return out_df
def _evaluate_by_index(self, y_true, y_pred, **kwargs):
"""Return the metric evaluated at each time point.
private _evaluate_by_index containing core logic, called from evaluate_by_index
By default this uses _evaluate to find jackknifed pseudosamples.
This yields estimates for the metric at each of the time points.
Caution: this is only sensible for differentiable statistics,
i.e., not for medians, quantiles or median/quantile based statistics.
Parameters
----------
y_true : time series in aeon compatible data container format
Ground truth (correct) target values
y can be in one of the following formats:
Series scitype: pd.Series, pd.DataFrame, or np.ndarray (1D or 2D)
Panel scitype: pd.DataFrame with 2-level row MultiIndex,
3D np.ndarray, list of Series pd.DataFrame, or nested pd.DataFrame
Hierarchical scitype: pd.DataFrame with 3 or more level row MultiIndex
y_pred :time series in aeon compatible data container format
Forecasted values to evaluate
must be of same format as y_true, same indices and columns if indexed
Returns
-------
loss : pd.Series or pd.DataFrame
Calculated metric, by time point (default=jackknife pseudo-values).
pd.Series if self.multioutput="uniform_average" or array-like
index is equal to index of y_true
entry at index i is metric at time i, averaged over variables
pd.DataFrame if self.multioutput="raw_values"
index and columns equal to those of y_true
i,j-th entry is metric at time i, at variable j
"""
multioutput = self.multioutput
n = y_true.shape[0]
if multioutput == "raw_values":
out_series = pd.DataFrame(index=y_true.index, columns=y_true.columns)
else:
out_series = pd.Series(index=y_true.index)
try:
x_bar = self.evaluate(y_true, y_pred, **kwargs)
for i in range(n):
idx = y_true.index[i]
pseudovalue = n * x_bar - (n - 1) * self.evaluate(
y_true.drop(idx),
y_pred.drop(idx),
)
out_series.loc[idx] = pseudovalue
return out_series
except RecursionError:
RecursionError("Must implement one of _evaluate or _evaluate_by_index")
def _check_consistent_input(self, y_true, y_pred, multioutput, multilevel):
y_true_orig = y_true
y_pred_orig = y_pred
# unwrap y_true, y_pred, if wrapped in VectorizedDF
if isinstance(y_true, VectorizedDF):
y_true = y_true.X
if isinstance(y_pred, VectorizedDF):
y_pred = y_pred.X
# check row and column indices if y_true vs y_pred
same_rows = y_true.index.equals(y_pred.index)
same_row_num = len(y_true.index) == len(y_pred.index)
same_cols = y_true.columns.equals(y_pred.columns)
same_col_num = len(y_true.columns) == len(y_pred.columns)
if not same_row_num:
raise ValueError("y_pred and y_true do not have the same number of rows.")
if not same_col_num:
raise ValueError(
"y_pred and y_true do not have the same number of columns."
)
if not same_rows:
warn(
"y_pred and y_true do not have the same row index. "
"This may indicate incorrect objects passed to the metric. "
"Indices of y_true will be used for y_pred."
)
y_pred_orig = y_pred_orig.copy()
if isinstance(y_pred_orig, VectorizedDF):
y_pred_orig.X.index = y_true.index
else:
y_pred_orig.index = y_true.index
if not same_cols:
warn(
"y_pred and y_true do not have the same column index. "
"This may indicate incorrect objects passed to the metric. "
"Indices of y_true will be used for y_pred."
)
y_pred_orig = y_pred_orig.copy()
if isinstance(y_pred_orig, VectorizedDF):
y_pred_orig.X.columns = y_true.columns
else:
y_pred_orig.columns = y_true.columns
# check multioutput arg
# todo: add this back when variance_weighted is supported
# ("raw_values", "uniform_average", "variance_weighted")
allowed_multioutput_str = ("raw_values", "uniform_average")
if isinstance(multioutput, str):
if multioutput not in allowed_multioutput_str:
raise ValueError(
f"Allowed 'multioutput' values are {allowed_multioutput_str}, "
f"but found multioutput={multioutput}"
)
else:
multioutput = check_array(multioutput, ensure_2d=False)
if len(y_pred.columns) != len(multioutput):
raise ValueError(
"There must be equally many custom weights (%d) as outputs (%d)."
% (len(multioutput), len(y_pred.columns))
)
# check multilevel arg
allowed_multilevel_str = (
"raw_values",
"uniform_average",
"uniform_average_time",
)
if not isinstance(multilevel, str):
raise ValueError(f"multilevel must be a str, but found {type(multilevel)}")
if multilevel not in allowed_multilevel_str:
raise ValueError(
f"Allowed 'multilevel' values are {allowed_multilevel_str}, "
f"but found multilevel={multilevel}"
)
return y_true_orig, y_pred_orig, multioutput, multilevel
def _check_ys(self, y_true, y_pred, multioutput, multilevel, **kwargs):
SCITYPES = ["Series", "Panel", "Hierarchical"]
INNER_MTYPES = ["pd.DataFrame", "pd-multiindex", "pd_multiindex_hier"]
def _coerce_to_df(y, var_name="y"):
valid, msg, metadata = check_is_scitype(
y, scitype=SCITYPES, return_metadata=True, var_name=var_name
)
if not valid:
raise TypeError(msg)
y_inner = convert_to(y, to_type=INNER_MTYPES)
scitype = metadata["scitype"]
ignore_index = multilevel == "uniform_average_time"
if scitype in ["Panel", "Hierarchical"] and not ignore_index:
y_inner = VectorizedDF(y_inner, is_scitype=scitype)
return y_inner
y_true = _coerce_to_df(y_true, var_name="y_true")
y_pred = _coerce_to_df(y_pred, var_name="y_pred")
if "y_train" in kwargs.keys():
kwargs["y_train"] = _coerce_to_df(kwargs["y_train"], var_name="y_train")
if "y_pred_benchmark" in kwargs.keys():
kwargs["y_pred_benchmark"] = _coerce_to_df(
kwargs["y_pred_benchmark"], var_name="y_pred_benchmark"
)
y_true, y_pred, multioutput, multilevel = self._check_consistent_input(
y_true, y_pred, multioutput, multilevel
)
return y_true, y_pred, multioutput, multilevel, kwargs
class BaseForecastingErrorMetricFunc(BaseForecastingErrorMetric):
"""Adapter for numpy metrics."""
# all descendants should have a func class attribute
# of signature func(y_true: np.ndarray, y_pred: np.darray, multioutput: bool)
# additional optional args: y_train: np.darray, y_pred_benchmark: np.darray
# further args that are parameters
# all np.ndarray should be 2D
# func should return 1D np.ndarray if multioutput="raw_values", otherwise float
def _evaluate(self, y_true, y_pred, **kwargs):
"""Evaluate the desired metric on given inputs."""
# this dict should contain all parameters
params = self.get_params()
# adding kwargs to the metric, should not overwrite params (but does if clashes)
params.update(kwargs)
# calls class variable func, if available, or dynamic (object) variable
# we need to call type since we store func as a class attribute
if hasattr(type(self), "func") and isfunction(type(self).func):
func = type(self).func
else:
func = self.func
# if func does not catch kwargs, subset to args of func
if getfullargspec(func).varkw is None:
func_params = signature(func).parameters.keys()
func_params = set(func_params).difference(["y_true", "y_pred"])
params = {key: params[key] for key in func_params}
res = func(y_true=y_true, y_pred=y_pred, **params)
return res
class _DynamicForecastingErrorMetric(BaseForecastingErrorMetricFunc):
"""Class for defining forecasting error metrics from a function dynamically."""
def __init__(
self,
func,
name=None,
multioutput="uniform_average",
multilevel="uniform_average",
lower_is_better=True,
):
self.multioutput = multioutput
self.multilevel = multilevel
self.func = func
self.name = name
self.lower_is_better = lower_is_better
super(_DynamicForecastingErrorMetric, self).__init__(
multioutput=multioutput, multilevel=multilevel
)
self.set_tags(**{"lower_is_better": lower_is_better})
@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, default = {}
Parameters to create testing instances of the class
Each dict are parameters to construct an "interesting" test instance, i.e.,
`MyClass(**params)` or `MyClass(**params[i])` creates a valid test instance.
`create_test_instance` uses the first (or only) dictionary in `params`
"""
def custom_mape(y_true, y_pred) -> float:
eps = np.finfo(np.float64).eps
result = np.mean(np.abs(y_true - y_pred) / np.maximum(np.abs(y_true), eps))
return float(result)
params = {"func": custom_mape, "name": "custom_mape", "lower_is_better": False}
return params
class _ScaledMetricTags:
"""Tags for metrics that are scaled on training data y_train."""
_tags = {
"requires-y-train": True,
"requires-y-pred-benchmark": False,
"univariate-only": False,
}
def make_forecasting_scorer(
func,
name=None,
greater_is_better=False,
multioutput="uniform_average",
multilevel="uniform_average",
):
"""Create a metric class from a metric functions.
Parameters
----------
func
Function to convert to a forecasting scorer class.
Score function (or loss function) with signature ``func(y, y_pred, **kwargs)``.
name : str, default=None
Name to use for the forecasting scorer loss class.
greater_is_better : bool, default=False
If True then maximizing the metric is better.
If False then minimizing the metric is better.
multioutput : {'raw_values', 'uniform_average'} or array-like of shape \
(n_outputs,), default='uniform_average'
Defines how to aggregate metric for multivariate (multioutput) data.
If array-like, values used as weights to average the errors.
If 'raw_values', returns a full set of errors in case of multioutput input.
If 'uniform_average', errors of all outputs are averaged with uniform weight.
multilevel : {'raw_values', 'uniform_average'}
Defines how to aggregate metric for hierarchical data (with levels).
If 'uniform_average' (default), errors are mean-averaged across levels.
If 'raw_values', does not average errors across levels, hierarchy is retained.
Returns
-------
scorer:
Metric class that can be used as forecasting scorer.
"""
lower_is_better = not greater_is_better
return _DynamicForecastingErrorMetric(
func,
name=name,
multioutput=multioutput,
multilevel=multilevel,
lower_is_better=lower_is_better,
)
class MeanAbsoluteScaledError(_ScaledMetricTags, BaseForecastingErrorMetricFunc):
"""Mean absolute scaled error (MASE).
MASE output is non-negative floating point. The best value is 0.0.
Like other scaled performance metrics, this scale-free error metric can be
used to compare forecast methods on a single series and also to compare
forecast accuracy between series.
This metric is well suited to intermittent-demand series because it
will not give infinite or undefined values unless the training data
is a flat timeseries. In this case the function returns a large value
instead of inf.
Works with multioutput (multivariate) timeseries data
with homogeneous seasonal periodicity.
Parameters
----------
sp : int, default = 1
Seasonal periodicity of the data
multioutput : {'raw_values', 'uniform_average'} or array-like of shape \
(n_outputs,), default='uniform_average'
Defines how to aggregate metric for multivariate (multioutput) data.
If array-like, values used as weights to average the errors.
If 'raw_values', returns a full set of errors in case of multioutput input.
If 'uniform_average', errors of all outputs are averaged with uniform weight.
See Also
--------
MedianAbsoluteScaledError
MeanSquaredScaledError
MedianSquaredScaledError
References
----------
Hyndman, R. J and Koehler, A. B. (2006). "Another look at measures of
forecast accuracy", International Journal of Forecasting, Volume 22, Issue 4.
Hyndman, R. J. (2006). "Another look at forecast accuracy metrics
for intermittent demand", Foresight, Issue 4.
Makridakis, S., Spiliotis, E. and Assimakopoulos, V. (2020)
"The M4 Competition: 100,000 time series and 61 forecasting methods",
International Journal of Forecasting, Volume 3.
Examples
--------
>>> import numpy as np
>>> from aeon.performance_metrics.forecasting import MeanAbsoluteScaledError
>>> y_train = np.array([5, 0.5, 4, 6, 3, 5, 2])
>>> y_true = np.array([3, -0.5, 2, 7, 2])
>>> y_pred = np.array([2.5, 0.0, 2, 8, 1.25])
>>> mase = MeanAbsoluteScaledError()
>>> mase(y_true, y_pred, y_train=y_train)
0.18333333333333335
>>> y_train = np.array([[0.5, 1], [-1, 1], [7, -6]])
>>> y_true = np.array([[0.5, 1], [-1, 1], [7, -6]])
>>> y_pred = np.array([[0, 2], [-1, 2], [8, -5]])
>>> mase(y_true, y_pred, y_train=y_train)
0.18181818181818182
>>> mase = MeanAbsoluteScaledError(multioutput='raw_values')
>>> mase(y_true, y_pred, y_train=y_train)
array([0.10526316, 0.28571429])
>>> mase = MeanAbsoluteScaledError(multioutput=[0.3, 0.7])
>>> mase(y_true, y_pred, y_train=y_train)
0.21935483870967742
"""
func = mean_absolute_scaled_error
def __init__(
self,
multioutput="uniform_average",
multilevel="uniform_average",
sp=1,
):
self.sp = sp
super().__init__(multioutput=multioutput, multilevel=multilevel)
class MedianAbsoluteScaledError(_ScaledMetricTags, BaseForecastingErrorMetricFunc):
"""Median absolute scaled error (MdASE).
MdASE output is non-negative floating point. The best value is 0.0.
Taking the median instead of the mean of the test and train absolute errors
makes this metric more robust to error outliers since the median tends
to be a more robust measure of central tendency in the presence of outliers.
Like MASE and other scaled performance metrics this scale-free metric can be
used to compare forecast methods on a single series or between series.
Also like MASE, this metric is well suited to intermittent-demand series
because it will not give infinite or undefined values unless the training
data is a flat timeseries. In this case the function returns a large value
instead of inf.
Works with multioutput (multivariate) timeseries data
with homogeneous seasonal periodicity.
Parameters
----------
sp : int, default = 1
Seasonal periodicity of data.
multioutput : {'raw_values', 'uniform_average'} or array-like of shape \
(n_outputs,), default='uniform_average'
Defines how to aggregate metric for multivariate (multioutput) data.
If array-like, values used as weights to average the errors.
If 'raw_values', returns a full set of errors in case of multioutput input.
If 'uniform_average', errors of all outputs are averaged with uniform weight.
See Also
--------
MeanAbsoluteScaledError
MeanSquaredScaledError
MedianSquaredScaledError
References
----------
Hyndman, R. J and Koehler, A. B. (2006). "Another look at measures of
forecast accuracy", International Journal of Forecasting, Volume 22, Issue 4.
Hyndman, R. J. (2006). "Another look at forecast accuracy metrics
for intermittent demand", Foresight, Issue 4.
Makridakis, S., Spiliotis, E. and Assimakopoulos, V. (2020)
"The M4 Competition: 100,000 time series and 61 forecasting methods",
International Journal of Forecasting, Volume 3.
Examples
--------
>>> import numpy as np
>>> from aeon.performance_metrics.forecasting import MedianAbsoluteScaledError
>>> y_train = np.array([5, 0.5, 4, 6, 3, 5, 2])
>>> y_true = np.array([3, -0.5, 2, 7])
>>> y_pred = np.array([2.5, 0.0, 2, 8])
>>> mdase = MedianAbsoluteScaledError()
>>> mdase(y_true, y_pred, y_train=y_train)
0.16666666666666666
>>> y_train = np.array([[0.5, 1], [-1, 1], [7, -6]])
>>> y_true = np.array([[0.5, 1], [-1, 1], [7, -6]])
>>> y_pred = np.array([[0, 2], [-1, 2], [8, -5]])
>>> mdase(y_true, y_pred, y_train=y_train)
0.18181818181818182
>>> mdase = MedianAbsoluteScaledError(multioutput='raw_values')
>>> mdase(y_true, y_pred, y_train=y_train)
array([0.10526316, 0.28571429])
>>> mdase = MedianAbsoluteScaledError(multioutput=[0.3, 0.7])
>>> mdase( y_true, y_pred, y_train=y_train)
0.21935483870967742
"""
func = median_absolute_scaled_error
def __init__(
self,
multioutput="uniform_average",
multilevel="uniform_average",
sp=1,
):
self.sp = sp
super().__init__(multioutput=multioutput, multilevel=multilevel)
class MeanSquaredScaledError(_ScaledMetricTags, BaseForecastingErrorMetricFunc):
"""Mean squared scaled error (MSSE) or root mean squared scaled error (RMSSE).
If `square_root` is False then calculates MSSE, otherwise calculates RMSSE if
`square_root` is True. Both MSSE and RMSSE output is non-negative floating
point. The best value is 0.0.
This is a squared varient of the MASE loss metric. Like MASE and other
scaled performance metrics this scale-free metric can be used to compare
forecast methods on a single series or between series.
This metric is also suited for intermittent-demand series because it
will not give infinite or undefined values unless the training data
is a flat timeseries. In this case the function returns a large value
instead of inf.
Works with multioutput (multivariate) timeseries data
with homogeneous seasonal periodicity.
Parameters
----------
sp : int, default = 1
Seasonal periodicity of data.
square_root : bool, default = False
Whether to take the square root of the metric
multioutput : {'raw_values', 'uniform_average'} or array-like of shape \
(n_outputs,), default='uniform_average'
Defines how to aggregate metric for multivariate (multioutput) data.
If array-like, values used as weights to average the errors.
If 'raw_values', returns a full set of errors in case of multioutput input.
If 'uniform_average', errors of all outputs are averaged with uniform weight.
See Also
--------
MeanAbsoluteScaledError
MedianAbsoluteScaledError
MedianSquaredScaledError
References
----------
M5 Competition Guidelines.
https://mofc.unic.ac.cy/wp-content/uploads/2020/03/M5-Competitors-Guide-Final-10-March-2020.docx
Hyndman, R. J and Koehler, A. B. (2006). "Another look at measures of
forecast accuracy", International Journal of Forecasting, Volume 22, Issue 4.
Examples
--------
>>> import numpy as np
>>> from aeon.performance_metrics.forecasting import MeanSquaredScaledError
>>> y_train = np.array([5, 0.5, 4, 6, 3, 5, 2])
>>> y_true = np.array([3, -0.5, 2, 7, 2])
>>> y_pred = np.array([2.5, 0.0, 2, 8, 1.25])
>>> rmsse = MeanSquaredScaledError(square_root=True)
>>> rmsse(y_true, y_pred, y_train=y_train)
0.20568833780186058
>>> y_train = np.array([[0.5, 1], [-1, 1], [7, -6]])
>>> y_true = np.array([[0.5, 1], [-1, 1], [7, -6]])
>>> y_pred = np.array([[0, 2], [-1, 2], [8, -5]])
>>> rmsse(y_true, y_pred, y_train=y_train)
0.15679361328058636
>>> rmsse = MeanSquaredScaledError(multioutput='raw_values', square_root=True)
>>> rmsse(y_true, y_pred, y_train=y_train)
array([0.11215443, 0.20203051])
>>> rmsse = MeanSquaredScaledError(multioutput=[0.3, 0.7], square_root=True)
>>> rmsse(y_true, y_pred, y_train=y_train)
0.17451891814894502
"""
func = mean_squared_scaled_error
def __init__(
self,
multioutput="uniform_average",
multilevel="uniform_average",
sp=1,
square_root=False,
):
self.sp = sp
self.square_root = square_root
super().__init__(multioutput=multioutput, multilevel=multilevel)
class MedianSquaredScaledError(_ScaledMetricTags, BaseForecastingErrorMetricFunc):
"""Median squared scaled error (MdSSE) or root median squared scaled error (RMdSSE).
If `square_root` is False then calculates MdSSE, otherwise calculates RMdSSE if
`square_root` is True. Both MdSSE and RMdSSE output is non-negative floating
point. The best value is 0.0.
This is a squared varient of the MdASE loss metric. Like MASE and other
scaled performance metrics this scale-free metric can be used to compare
forecast methods on a single series or between series.
This metric is also suited for intermittent-demand series because it
will not give infinite or undefined values unless the training data
is a flat timeseries. In this case the function returns a large value
instead of inf.
Works with multioutput (multivariate) timeseries data
with homogeneous seasonal periodicity.
Parameters
----------
sp : int, default = 1
Seasonal periodicity of data.
square_root : bool, default = False
Whether to take the square root of the metric
multioutput : {'raw_values', 'uniform_average'} or array-like of shape \
(n_outputs,), default='uniform_average'
Defines how to aggregate metric for multivariate (multioutput) data.
If array-like, values used as weights to average the errors.
If 'raw_values', returns a full set of errors in case of multioutput input.
If 'uniform_average', errors of all outputs are averaged with uniform weight.
See Also
--------
MeanAbsoluteScaledError
MedianAbsoluteScaledError
MedianSquaredScaledError
References
----------
M5 Competition Guidelines.
https://mofc.unic.ac.cy/wp-content/uploads/2020/03/M5-Competitors-Guide-Final-10-March-2020.docx
Hyndman, R. J and Koehler, A. B. (2006). "Another look at measures of
forecast accuracy", International Journal of Forecasting, Volume 22, Issue 4.
Examples
--------
>>> import numpy as np
>>> from aeon.performance_metrics.forecasting import MedianSquaredScaledError
>>> y_train = np.array([5, 0.5, 4, 6, 3, 5, 2])
>>> y_true = np.array([3, -0.5, 2, 7, 2])
>>> y_pred = np.array([2.5, 0.0, 2, 8, 1.25])
>>> rmdsse = MedianSquaredScaledError(square_root=True)
>>> rmdsse(y_true, y_pred, y_train=y_train)
0.16666666666666666
>>> y_train = np.array([[0.5, 1], [-1, 1], [7, -6]])
>>> y_true = np.array([[0.5, 1], [-1, 1], [7, -6]])
>>> y_pred = np.array([[0, 2], [-1, 2], [8, -5]])
>>> rmdsse(y_true, y_pred, y_train=y_train)
0.1472819539849714
>>> rmdsse = MedianSquaredScaledError(multioutput='raw_values', square_root=True)
>>> rmdsse(y_true, y_pred, y_train=y_train)
array([0.08687445, 0.20203051])
>>> rmdsse = MedianSquaredScaledError(multioutput=[0.3, 0.7], square_root=True)
>>> rmdsse(y_true, y_pred, y_train=y_train)
0.16914781383660782
"""
func = median_squared_scaled_error
def __init__(
self,
multioutput="uniform_average",
multilevel="uniform_average",
sp=1,
square_root=False,
):
self.sp = sp
self.square_root = square_root
super().__init__(multioutput=multioutput, multilevel=multilevel)
class MeanAbsoluteError(BaseForecastingErrorMetricFunc):
"""Mean absolute error (MAE).
MAE output is non-negative floating point. The best value is 0.0.
MAE is on the same scale as the data. Because MAE takes the absolute value
of the forecast error rather than squaring it, MAE penalizes large errors
to a lesser degree than MSE or RMSE.
Parameters
----------
multioutput : {'raw_values', 'uniform_average'} or array-like of shape \
(n_outputs,), default='uniform_average'
Defines how to aggregate metric for multivariate (multioutput) data.
If array-like, values used as weights to average the errors.
If 'raw_values', returns a full set of errors in case of multioutput input.
If 'uniform_average', errors of all outputs are averaged with uniform weight.
See Also
--------
MedianAbsoluteError
MeanSquaredError
MedianSquaredError
References
----------