-
Notifications
You must be signed in to change notification settings - Fork 87
/
_functions.py
2709 lines (2306 loc) · 104 KB
/
_functions.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
"""Metrics functions to assess performance on forecasting task.
Functions named as ``*_score`` return a value to maximize: the higher the better.
Function named as ``*_error`` or ``*_loss`` return a value to minimize:
the lower the better.
"""
import numpy as np
from scipy.stats import gmean
from sklearn.metrics import mean_absolute_error as _mean_absolute_error
from sklearn.metrics import mean_squared_error as _mean_squared_error
from sklearn.metrics import median_absolute_error as _median_absolute_error
from sklearn.metrics._regression import _check_reg_targets
from sklearn.utils.stats import _weighted_percentile
from sklearn.utils.validation import check_consistent_length
from aeon.utils.stats import _weighted_geometric_mean
from aeon.utils.validation.series import check_series
__author__ = ["mloning", "Tomasz Chodakowski", "RNKuhns"]
__all__ = [
"relative_loss",
"mean_linex_error",
"mean_asymmetric_error",
"mean_absolute_scaled_error",
"median_absolute_scaled_error",
"mean_squared_scaled_error",
"median_squared_scaled_error",
"mean_absolute_error",
"mean_squared_error",
"median_absolute_error",
"median_squared_error",
"geometric_mean_absolute_error",
"geometric_mean_squared_error",
"mean_absolute_percentage_error",
"median_absolute_percentage_error",
"mean_squared_percentage_error",
"median_squared_percentage_error",
"mean_relative_absolute_error",
"median_relative_absolute_error",
"geometric_mean_relative_absolute_error",
"geometric_mean_relative_squared_error",
]
EPS = np.finfo(np.float64).eps
def _get_kwarg(kwarg, metric_name="Metric", **kwargs):
"""Pop a kwarg from kwargs and raise warning if kwarg not present."""
kwarg_ = kwargs.pop(kwarg, None)
if kwarg_ is None:
msg = "".join(
[
f"{metric_name} requires `{kwarg}`. ",
f"Pass `{kwarg}` as a keyword argument when calling the metric.",
]
)
raise ValueError(msg)
return kwarg_
def mean_linex_error(
y_true,
y_pred,
a=1.0,
b=1.0,
horizon_weight=None,
multioutput="uniform_average",
**kwargs,
):
"""Calculate mean linex error.
Output is non-negative floating point. The best value is 0.0.
Many forecasting loss functions (like those discussed in [1]_) assume that
over- and under- predictions should receive an equal penalty. However, this
may not align with the actual cost faced by users' of the forecasts.
Asymmetric loss functions are useful when the cost of under- and over-
prediction are not the same.
The linex error function accounts for this by penalizing errors on one side
of a threshold approximately linearly, while penalizing errors on the other
side approximately exponentially.
Parameters
----------
y_true : pd.Series, pd.DataFrame or np.array of shape (fh,) or (fh, n_outputs) \
where fh is the forecasting horizon
Ground truth (correct) target values.
y_pred : pd.Series, pd.DataFrame or np.array of shape (fh,) or (fh, n_outputs) \
where fh is the forecasting horizon
Forecasted values.
a : int or float
Controls whether over- or under- predictions receive an approximately
linear or exponential penalty. If `a` > 0 then negative errors
(over-predictions) are penalized approximately linearly and positive errors
(under-predictions) are penalized approximately exponentially. If `a` < 0
the reverse is true.
b : int or float
Multiplicative penalty to apply to calculated errors.
horizon_weight : array-like of shape (fh,), default=None
Forecast horizon weights.
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.
Returns
-------
asymmetric_loss : float
Loss using asymmetric penalty of on errors.
If multioutput is 'raw_values', then asymmetric loss is returned for
each output separately.
If multioutput is 'uniform_average' or an ndarray of weights, then the
weighted average asymmetric loss of all output errors is returned.
See Also
--------
mean_asymmetric_error
Notes
-----
Calculated as b * (np.exp(a * error) - a * error - 1), where a != 0 and b > 0
according to formula in [2]_.
References
----------
.. [1] Hyndman, R. J and Koehler, A. B. (2006). "Another look at measures of
forecast accuracy", International Journal of Forecasting, Volume 22, Issue 4.
.. [1] Diebold, Francis X. (2007). "Elements of Forecasting (4th ed.)",
Thomson, South-Western: Ohio, US.
Examples
--------
>>> import numpy as np
>>> from aeon.performance_metrics.forecasting import mean_linex_error
>>> y_true = np.array([3, -0.5, 2, 7, 2])
>>> y_pred = np.array([2.5, 0.0, 2, 8, 1.25])
>>> mean_linex_error(y_true, y_pred) # doctest: +SKIP
0.19802627763937575
>>> mean_linex_error(y_true, y_pred, b=2) # doctest: +SKIP
0.3960525552787515
>>> mean_linex_error(y_true, y_pred, a=-1) # doctest: +SKIP
0.2391800623225643
>>> y_true = np.array([[0.5, 1], [-1, 1], [7, -6]])
>>> y_pred = np.array([[0, 2], [-1, 2], [8, -5]])
>>> mean_linex_error(y_true, y_pred) # doctest: +SKIP
0.2700398392309829
>>> mean_linex_error(y_true, y_pred, a=-1) # doctest: +SKIP
0.49660966225813563
>>> mean_linex_error(y_true, y_pred, multioutput='raw_values') # doctest: +SKIP
array([0.17220024, 0.36787944])
>>> mean_linex_error(y_true, y_pred, multioutput=[0.3, 0.7]) # doctest: +SKIP
0.30917568000716666
"""
_, y_true, y_pred, multioutput = _check_reg_targets(y_true, y_pred, multioutput)
if horizon_weight is not None:
check_consistent_length(y_true, horizon_weight)
linex_error = _linex_error(y_true, y_pred, a=a, b=b)
output_errors = np.average(linex_error, weights=horizon_weight, axis=0)
if isinstance(multioutput, str):
if multioutput == "raw_values":
return output_errors
elif multioutput == "uniform_average":
# pass None as weights to np.average: uniform mean
multioutput = None
return np.average(output_errors, weights=multioutput)
def mean_asymmetric_error(
y_true,
y_pred,
asymmetric_threshold=0.0,
left_error_function="squared",
right_error_function="absolute",
left_error_penalty=1.0,
right_error_penalty=1.0,
horizon_weight=None,
multioutput="uniform_average",
**kwargs,
):
"""Calculate mean of asymmetric loss function.
Output is non-negative floating point. The best value is 0.0.
Error values that are less than the asymmetric threshold have
`left_error_function` applied. Error values greater than or equal to
asymmetric threshold have `right_error_function` applied.
Many forecasting loss functions (like those discussed in [1]_) assume that
over- and under- predictions should receive an equal penalty. However, this
may not align with the actual cost faced by users' of the forecasts.
Asymmetric loss functions are useful when the cost of under- and over-
prediction are not the same.
Setting `asymmetric_threshold` to zero, `left_error_function` to 'squared'
and `right_error_function` to 'absolute` results in a greater penalty
applied to over-predictions (y_true - y_pred < 0). The opposite is true
for `left_error_function` set to 'absolute' and `right_error_function`
set to 'squared`.
The left_error_penalty and right_error_penalty can be used to add differing
multiplicative penalties to over-predictions and under-predictions.
Parameters
----------
y_true : pd.Series, pd.DataFrame or np.array of shape (fh,) or (fh, n_outputs) \
where fh is the forecasting horizon
Ground truth (correct) target values.
y_pred : pd.Series, pd.DataFrame or np.array of shape (fh,) or (fh, n_outputs) \
where fh is the forecasting horizon
Forecasted values.
asymmetric_threshold : float, default = 0.0
The value used to threshold the asymmetric loss function. Error values
that are less than the asymmetric threshold have `left_error_function`
applied. Error values greater than or equal to asymmetric threshold
have `right_error_function` applied.
left_error_function : {'squared', 'absolute'}, default='squared'
Loss penalty to apply to error values less than the asymmetric threshold.
right_error_function : {'squared', 'absolute'}, default='absolute'
Loss penalty to apply to error values greater than or equal to the
asymmetric threshold.
left_error_penalty : int or float, default=1.0
An additional multiplicative penalty to apply to error values less than
the asymetric threshold.
right_error_penalty : int or float, default=1.0
An additional multiplicative penalty to apply to error values greater
than the asymmetric threshold.
horizon_weight : array-like of shape (fh,), default=None
Forecast horizon weights.
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.
Returns
-------
asymmetric_loss : float
Loss using asymmetric penalty of on errors.
If multioutput is 'raw_values', then asymmetric loss is returned for
each output separately.
If multioutput is 'uniform_average' or an ndarray of weights, then the
weighted average asymmetric loss of all output errors is returned.
See Also
--------
mean_linex_error
Notes
-----
Setting `left_error_function` and `right_error_function` to "aboslute", but
choosing different values for `left_error_penalty` and `right_error_penalty`
results in the "lin-lin" error function discussed in [2]_.
References
----------
.. [1] Hyndman, R. J and Koehler, A. B. (2006). "Another look at measures of
forecast accuracy", International Journal of Forecasting, Volume 22, Issue 4.
.. [2] Diebold, Francis X. (2007). "Elements of Forecasting (4th ed.)",
Thomson, South-Western: Ohio, US.
Examples
--------
>>> import numpy as np
>>> from aeon.performance_metrics.forecasting import mean_asymmetric_error
>>> y_true = np.array([3, -0.5, 2, 7, 2])
>>> y_pred = np.array([2.5, 0.0, 2, 8, 1.25])
>>> mean_asymmetric_error(y_true, y_pred)
0.5
>>> mean_asymmetric_error(y_true, y_pred, left_error_function='absolute', \
right_error_function='squared')
0.4625
>>> y_true = np.array([[0.5, 1], [-1, 1], [7, -6]])
>>> y_pred = np.array([[0, 2], [-1, 2], [8, -5]])
>>> mean_asymmetric_error(y_true, y_pred)
0.75
>>> mean_asymmetric_error(y_true, y_pred, left_error_function='absolute', \
right_error_function='squared')
0.7083333333333334
>>> mean_asymmetric_error(y_true, y_pred, multioutput='raw_values')
array([0.5, 1. ])
>>> mean_asymmetric_error(y_true, y_pred, multioutput=[0.3, 0.7])
0.85
"""
_, y_true, y_pred, multioutput = _check_reg_targets(y_true, y_pred, multioutput)
if horizon_weight is not None:
check_consistent_length(y_true, horizon_weight)
asymmetric_errors = _asymmetric_error(
y_true,
y_pred,
asymmetric_threshold=asymmetric_threshold,
left_error_function=left_error_function,
right_error_function=right_error_function,
left_error_penalty=left_error_penalty,
right_error_penalty=right_error_penalty,
)
output_errors = np.average(asymmetric_errors, weights=horizon_weight, axis=0)
if isinstance(multioutput, str):
if multioutput == "raw_values":
return output_errors
elif multioutput == "uniform_average":
# pass None as weights to np.average: uniform mean
multioutput = None
return np.average(output_errors, weights=multioutput)
def mean_absolute_scaled_error(
y_true, y_pred, sp=1, horizon_weight=None, multioutput="uniform_average", **kwargs
):
"""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
----------
y_true : pd.Series, pd.DataFrame or np.array of shape (fh,) or (fh, n_outputs) \
where fh is the forecasting horizon
Ground truth (correct) target values.
y_pred : pd.Series, pd.DataFrame or np.array of shape (fh,) or (fh, n_outputs) \
where fh is the forecasting horizon
Forecasted values.
y_train : pd.Series, pd.DataFrame or np.array of shape (n_timepoints,) or \
(n_timepoints, n_outputs), default = None
Observed training values.
sp : int
Seasonal periodicity of training data.
horizon_weight : array-like of shape (fh,), default=None
Forecast horizon weights.
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.
Returns
-------
loss : float or ndarray of floats
MASE loss.
If multioutput is 'raw_values', then MASE is returned for each
output separately.
If multioutput is 'uniform_average' or an ndarray of weights, then the
weighted average MASE of all output errors is returned.
See Also
--------
median_absolute_scaled_error
mean_squared_scaled_error
median_squared_scaled_error
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
--------
>>> from aeon.performance_metrics.forecasting import mean_absolute_scaled_error
>>> 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])
>>> mean_absolute_scaled_error(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]])
>>> mean_absolute_scaled_error(y_true, y_pred, y_train=y_train)
0.18181818181818182
>>> mean_absolute_scaled_error(y_true, y_pred, y_train=y_train, \
multioutput='raw_values')
array([0.10526316, 0.28571429])
>>> mean_absolute_scaled_error(y_true, y_pred, y_train=y_train, \
multioutput=[0.3, 0.7])
0.21935483870967742
"""
y_train = _get_kwarg("y_train", metric_name="mean_absolute_scaled_error", **kwargs)
# Other input checks
_, y_true, y_pred, multioutput = _check_reg_targets(y_true, y_pred, multioutput)
if horizon_weight is not None:
check_consistent_length(y_true, horizon_weight)
y_train = check_series(y_train, enforce_univariate=False)
# _check_reg_targets converts 1-dim y_true,y_pred to 2-dim so need to match
if y_train.ndim == 1:
y_train = np.expand_dims(y_train, 1)
# Check test and train have same dimensions
if y_true.ndim != y_train.ndim:
raise ValueError("Equal dimension required for y_true and y_train")
if (y_true.ndim > 1) and (y_true.shape[1] != y_train.shape[1]):
raise ValueError("Equal number of columns required for y_true and y_train")
# naive seasonal prediction
y_train = np.asarray(y_train)
y_pred_naive = y_train[:-sp]
# mean absolute error of naive seasonal prediction
mae_naive = mean_absolute_error(y_train[sp:], y_pred_naive, multioutput=multioutput)
mae_pred = mean_absolute_error(
y_true, y_pred, horizon_weight=horizon_weight, multioutput=multioutput
)
return mae_pred / np.maximum(mae_naive, EPS)
def median_absolute_scaled_error(
y_true, y_pred, sp=1, horizon_weight=None, multioutput="uniform_average", **kwargs
):
"""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
----------
y_true : pd.Series, pd.DataFrame or np.array of shape (fh,) or (fh, n_outputs) \
where fh is the forecasting horizon
Ground truth (correct) target values.
y_pred : pd.Series, pd.DataFrame or np.array of shape (fh,) or (fh, n_outputs) \
where fh is the forecasting horizon
Forecasted values.
y_train : pd.Series, pd.DataFrame or np.array of shape (n_timepoints,) or \
(n_timepoints, n_outputs), default = None
Observed training values.
sp : int
Seasonal periodicity of training data.
horizon_weight : array-like of shape (fh,), default=None
Forecast horizon weights.
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
--------
mean_absolute_scaled_error
mean_squared_scaled_error
median_squared_scaled_error
Returns
-------
loss : float or ndarray of floats
MdASE loss.
If multioutput is 'raw_values', then MdASE is returned for each
output separately.
If multioutput is 'uniform_average' or an ndarray of weights, then the
weighted average MdASE of all output errors is returned.
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
--------
>>> from aeon.performance_metrics.forecasting import median_absolute_scaled_error
>>> y_train = np.array([5, 0.5, 4, 6, 3, 5, 2])
>>> y_true = [3, -0.5, 2, 7]
>>> y_pred = [2.5, 0.0, 2, 8]
>>> median_absolute_scaled_error(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]])
>>> median_absolute_scaled_error(y_true, y_pred, y_train=y_train)
0.18181818181818182
>>> median_absolute_scaled_error(y_true, y_pred, y_train=y_train, \
multioutput='raw_values')
array([0.10526316, 0.28571429])
>>> median_absolute_scaled_error( y_true, y_pred, y_train=y_train, \
multioutput=[0.3, 0.7])
0.21935483870967742
"""
y_train = _get_kwarg(
"y_train", metric_name="median_absolute_scaled_error", **kwargs
)
# Other input checks
_, y_true, y_pred, multioutput = _check_reg_targets(y_true, y_pred, multioutput)
if horizon_weight is not None:
check_consistent_length(y_true, horizon_weight)
y_train = check_series(y_train, enforce_univariate=False)
if y_train.ndim == 1:
y_train = np.expand_dims(y_train, 1)
# Check test and train have same dimensions
if y_true.ndim != y_train.ndim:
raise ValueError("Equal dimension required for y_true and y_train")
if (y_true.ndim > 1) and (y_true.shape[1] != y_train.shape[1]):
raise ValueError("Equal number of columns required for y_true and y_train")
# naive seasonal prediction
y_train = np.asarray(y_train)
y_pred_naive = y_train[:-sp]
# mean absolute error of naive seasonal prediction
mdae_naive = median_absolute_error(
y_train[sp:], y_pred_naive, multioutput=multioutput
)
mdae_pred = median_absolute_error(
y_true, y_pred, horizon_weight=horizon_weight, multioutput=multioutput
)
return mdae_pred / np.maximum(mdae_naive, EPS)
def mean_squared_scaled_error(
y_true,
y_pred,
sp=1,
horizon_weight=None,
multioutput="uniform_average",
square_root=False,
**kwargs,
):
"""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
----------
y_true : pd.Series, pd.DataFrame or np.array of shape (fh,) or (fh, n_outputs) \
where fh is the forecasting horizon
Ground truth (correct) target values.
y_pred : pd.Series, pd.DataFrame or np.array of shape (fh,) or (fh, n_outputs) \
where fh is the forecasting horizon
Forecasted values.
y_train : pd.Series, pd.DataFrame or np.array of shape (n_timepoints,) or \
(n_timepoints, n_outputs), default = None
Observed training values.
sp : int
Seasonal periodicity of training data.
horizon_weight : array-like of shape (fh,), default=None
Forecast horizon weights.
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.
square_root : bool, default=False
Whether to take the square root of the mean squared scaled error.
If True, returns root mean squared scaled error (RMSSE)
If False, returns mean squared scaled error (MSSE)
Returns
-------
loss : float
RMSSE loss.
If multioutput is 'raw_values', then MSSE or RMSSE is returned for each
output separately.
If multioutput is 'uniform_average' or an ndarray of weights, then the
weighted average MSSE or RMSSE of all output errors is returned.
See Also
--------
mean_absolute_scaled_error
median_absolute_scaled_error
median_squared_scaled_error
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
--------
>>> from aeon.performance_metrics.forecasting import mean_squared_scaled_error
>>> 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])
>>> mean_squared_scaled_error(y_true, y_pred, y_train=y_train, square_root=True)
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]])
>>> mean_squared_scaled_error(y_true, y_pred, y_train=y_train, square_root=True)
0.15679361328058636
>>> mean_squared_scaled_error(y_true, y_pred, y_train=y_train, \
multioutput='raw_values', square_root=True)
array([0.11215443, 0.20203051])
>>> mean_squared_scaled_error(y_true, y_pred, y_train=y_train, \
multioutput=[0.3, 0.7], square_root=True)
0.17451891814894502
"""
y_train = _get_kwarg("y_train", metric_name="mean_squared_scaled_error", **kwargs)
# Other input checks
_, y_true, y_pred, multioutput = _check_reg_targets(y_true, y_pred, multioutput)
if horizon_weight is not None:
check_consistent_length(y_true, horizon_weight)
y_train = check_series(y_train, enforce_univariate=False)
if y_train.ndim == 1:
y_train = np.expand_dims(y_train, 1)
# Check test and train have same dimensions
if y_true.ndim != y_train.ndim:
raise ValueError("Equal dimension required for y_true and y_train")
if (y_true.ndim > 1) and (y_true.shape[1] != y_train.shape[1]):
raise ValueError("Equal number of columns required for y_true and y_train")
# naive seasonal prediction
y_train = np.asarray(y_train)
y_pred_naive = y_train[:-sp]
# mean squared error of naive seasonal prediction
mse_naive = mean_squared_error(y_train[sp:], y_pred_naive, multioutput=multioutput)
mse = mean_squared_error(
y_true, y_pred, horizon_weight=horizon_weight, multioutput=multioutput
)
if square_root:
loss = np.sqrt(mse / np.maximum(mse_naive, EPS))
else:
loss = mse / np.maximum(mse_naive, EPS)
return loss
def median_squared_scaled_error(
y_true,
y_pred,
sp=1,
horizon_weight=None,
multioutput="uniform_average",
square_root=False,
**kwargs,
):
"""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
----------
y_true : pd.Series, pd.DataFrame or np.array of shape (fh,) or (fh, n_outputs) \
where fh is the forecasting horizon
Ground truth (correct) target values.
y_pred : pd.Series, pd.DataFrame or np.array of shape (fh,) or (fh, n_outputs) \
where fh is the forecasting horizon
Forecasted values.
y_train : pd.Series, pd.DataFrame or np.array of shape (n_timepoints,) or \
(n_timepoints, n_outputs), default = None
Observed training values.
sp : int
Seasonal periodicity of training data.
horizon_weight : array-like of shape (fh,), default=None
Forecast horizon weights.
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.
Returns
-------
loss : float
RMdSSE loss.
If multioutput is 'raw_values', then RMdSSE is returned for each
output separately.
If multioutput is 'uniform_average' or an ndarray of weights, then the
weighted average RMdSSE of all output errors is returned.
See Also
--------
mean_absolute_scaled_error
median_absolute_scaled_error
mean_squared_scaled_error
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
--------
>>> from aeon.performance_metrics.forecasting import median_squared_scaled_error
>>> 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])
>>> median_squared_scaled_error(y_true, y_pred, y_train=y_train, square_root=True)
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]])
>>> median_squared_scaled_error(y_true, y_pred, y_train=y_train, square_root=True)
0.1472819539849714
>>> median_squared_scaled_error(y_true, y_pred, y_train=y_train, \
multioutput='raw_values', square_root=True)
array([0.08687445, 0.20203051])
>>> median_squared_scaled_error(y_true, y_pred, y_train=y_train, \
multioutput=[0.3, 0.7], square_root=True)
0.16914781383660782
"""
y_train = _get_kwarg("y_train", metric_name="median_squared_scaled_error", **kwargs)
# Other input checks
_, y_true, y_pred, multioutput = _check_reg_targets(y_true, y_pred, multioutput)
if horizon_weight is not None:
check_consistent_length(y_true, horizon_weight)
y_train = check_series(y_train, enforce_univariate=False)
if y_train.ndim == 1:
y_train = np.expand_dims(y_train, 1)
# Check test and train have same dimensions
if y_true.ndim != y_train.ndim:
raise ValueError("Equal dimension required for y_true and y_train")
if (y_true.ndim > 1) and (y_true.shape[1] != y_train.shape[1]):
raise ValueError("Equal number of columns required for y_true and y_train")
# naive seasonal prediction
y_train = np.asarray(y_train)
y_pred_naive = y_train[:-sp]
# median squared error of naive seasonal prediction
mdse_naive = median_squared_error(
y_train[sp:], y_pred_naive, multioutput=multioutput
)
mdse = median_squared_error(
y_true, y_pred, horizon_weight=horizon_weight, multioutput=multioutput
)
if square_root:
loss = np.sqrt(mdse / np.maximum(mdse_naive, EPS))
else:
loss = mdse / np.maximum(mdse_naive, EPS)
return loss
def mean_absolute_error(
y_true, y_pred, horizon_weight=None, multioutput="uniform_average", **kwargs
):
"""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
----------
y_true : pd.Series, pd.DataFrame or np.array of shape (fh,) or (fh, n_outputs) \
where fh is the forecasting horizon
Ground truth (correct) target values.
y_pred : pd.Series, pd.DataFrame or np.array of shape (fh,) or (fh, n_outputs) \
where fh is the forecasting horizon
Forecasted values.
horizon_weight : array-like of shape (fh,), default=None
Forecast horizon weights.
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.
Returns
-------
loss : float or ndarray of floats
MAE loss.
If multioutput is 'raw_values', then MAE is returned for each
output separately.
If multioutput is 'uniform_average' or an ndarray of weights, then the
weighted average MAE of all output errors is returned.
See Also
--------
median_absolute_error
mean_squared_error
median_squared_error
geometric_mean_absolute_error
geometric_mean_squared_error
References
----------
Hyndman, R. J and Koehler, A. B. (2006). "Another look at measures of
forecast accuracy", International Journal of Forecasting, Volume 22, Issue 4.
Examples
--------
>>> from aeon.performance_metrics.forecasting import mean_absolute_error
>>> y_true = np.array([3, -0.5, 2, 7, 2])
>>> y_pred = np.array([2.5, 0.0, 2, 8, 1.25])
>>> mean_absolute_error(y_true, y_pred)
0.55
>>> y_true = np.array([[0.5, 1], [-1, 1], [7, -6]])
>>> y_pred = np.array([[0, 2], [-1, 2], [8, -5]])
>>> mean_absolute_error(y_true, y_pred)
0.75
>>> mean_absolute_error(y_true, y_pred, multioutput='raw_values')
array([0.5, 1. ])
>>> mean_absolute_error(y_true, y_pred, multioutput=[0.3, 0.7])
0.85
"""
return _mean_absolute_error(
y_true, y_pred, sample_weight=horizon_weight, multioutput=multioutput
)
def mean_squared_error(
y_true,
y_pred,
horizon_weight=None,
multioutput="uniform_average",
square_root=False,
**kwargs,
):
"""Mean squared error (MSE) or root mean squared error (RMSE).
If `square_root` is False then calculates MSE and if `square_root` is True
then RMSE is calculated. Both MSE and RMSE are both non-negative floating
point. The best value is 0.0.
MSE is measured in squared units of the input data, and RMSE is on the
same scale as the data. Because MSE and RMSE square the forecast error
rather than taking the absolute value, they penalize large errors more than
MAE.
Parameters
----------
y_true : pd.Series, pd.DataFrame or np.array of shape (fh,) or (fh, n_outputs) \
where fh is the forecasting horizon
Ground truth (correct) target values.
y_pred : pd.Series, pd.DataFrame or np.array of shape (fh,) or (fh, n_outputs) \
where fh is the forecasting horizon
Forecasted values.
horizon_weight : array-like of shape (fh,), default=None
Forecast horizon weights.
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.
square_root : bool, default=False
Whether to take the square root of the mean squared error.
If True, returns root mean squared error (RMSE)
If False, returns mean squared error (MSE)
Returns
-------
loss : float or ndarray of floats
MSE loss.
If multioutput is 'raw_values', then MSE is returned for each
output separately.
If multioutput is 'uniform_average' or an ndarray of weights, then the
weighted average MSE of all output errors is returned.
See Also
--------
mean_absolute_error
median_absolute_error
median_squared_error
geometric_mean_absolute_error
geometric_mean_squared_error
References
----------
Hyndman, R. J and Koehler, A. B. (2006). "Another look at measures of
forecast accuracy", International Journal of Forecasting, Volume 22, Issue 4.
Examples
--------
>>> from aeon.performance_metrics.forecasting import mean_squared_error
>>> y_true = np.array([3, -0.5, 2, 7, 2])
>>> y_pred = np.array([2.5, 0.0, 2, 8, 1.25])
>>> mean_squared_error(y_true, y_pred)
0.4125
>>> y_true = np.array([[0.5, 1], [-1, 1], [7, -6]])
>>> y_pred = np.array([[0, 2], [-1, 2], [8, -5]])
>>> mean_squared_error(y_true, y_pred)
0.7083333333333334
>>> mean_squared_error(y_true, y_pred, square_root=True)
0.8227486121839513
>>> mean_squared_error(y_true, y_pred, multioutput='raw_values')
array([0.41666667, 1. ])
>>> mean_squared_error(y_true, y_pred, multioutput='raw_values', square_root=True)
array([0.64549722, 1. ])
>>> mean_squared_error(y_true, y_pred, multioutput=[0.3, 0.7])
0.825
>>> mean_squared_error(y_true, y_pred, multioutput=[0.3, 0.7], square_root=True)
0.8936491673103708
"""
# Scikit-learn argument `squared` returns MSE when True and RMSE when False