-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMLUtilities.py
More file actions
1421 lines (1110 loc) · 49.8 KB
/
Copy pathMLUtilities.py
File metadata and controls
1421 lines (1110 loc) · 49.8 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
import numpy as np
from sklearn.metrics import confusion_matrix
from sklearn.model_selection import train_test_split
from sklearn.model_selection import KFold
#librerias de regresion lineal
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
from sklearn.metrics import mean_squared_error
#Funciones de separación de entrenamiento, validación y prueba.
def particionar(entradas,salidas,porcentaje_entrenamiento, porcentaje_validacion, porcentaje_prueba):
temp_size = porcentaje_validacion + porcentaje_prueba
x_train, x_temp, y_train, y_temp = train_test_split(entradas,salidas,test_size=temp_size)
if(porcentaje_validacion > 0):
test_size = porcentaje_prueba/temp_size
x_val, x_test, y_val, y_test = train_test_split(x_temp, y_temp, test_size=test_size)
else:
return [x_train, None, x_temp, y_train, None, y_temp]
return [x_train, x_val, x_temp, y_train, y_val, y_temp]
#Funciones de separación de datasets con K-Fold (el usuario debe poner el K, si K = 1 debe generar un Leave-One-Out Cross Validation).
def kfold(k):
kfold = KFold(k,True,random_seed=48)
return kfold
#Funciones de evaluación con matriz de confusión.
def conf_matrix(y_esperados, y_predichos):
matrix = confusion_matrix(y_esperados, y_predichos)
return matrix
#Funciones de obtención de Precisión (Accuracy), Sensibilidad y Especificidad.
def conf_matrix(y_esperados, y_predichos):
matrix = confusion_matrix(y_esperados, y_predichos)
return matrix
def parameters(matrix):
(TP, FN, FP, TN) = np.ravel(matrix, order = 'C')
return TP, FN, FP, TN
def accuracy(TP, FN, FP, TN): #exactitud
a = (TP + TN)/(TP+TN+FP+FN)
return a
def sensitivity(TP, FN, FP, TN): #sensibilidad
s = TP/(TP +FN)
return s
def specificity(TP, FN, FP, TN): #especificidad
sp = TN/(TN + FP)
return sp
def precision(TP, FN, FP, TN): #precisión
p = TP/(TP+FP)
return p
#Funciones que comparen dos clasificadores:
#Obtengas precisión, sensibilidad y especificidad del clasificador 1
#Obtengas precisión, sensibilidad y especificidad del clasificador 2
def comparison(matrix1, matrix2): #la función toma dos matrices de confusión
TP, FN, FP, TN = parameters(matrix1)
TP2, FN2, FP2, TN2 = parameters(matrix2)
#valores para la matriz del modelo 1
a1 = accuracy(TP, FN, FP, TN)
s1 = sensitivity(TP, FN, FP, TN)
sp1 = specificity(TP, FN, FP, TN)
p1 = precision(TP, FN, FP, TN)
print("Modelo 1:")
print(f"Exactitud: {a1}")
print(f"Sensibilidad: {s1}")
print(f"Especificidad: {sp1}")
print(f"Precisión: {p1}")
print("\n")
print("Modelo 2:")
print(f"Exactitud: {a2}")
print(f"Sensibilidad: {s2}")
print(f"Especificidad: {sp2}")
print(f"Precisión: {p2}")
print("\n")
#valores para la matriz del modelo 2
a2 = accuracy(TP2, FN2, FP2, TN2)
s2 = sensitivity(TP2, FN2, FP2, TN2)
sp2 = specificity(TP2, FN2, FP2, TN2)
p2 = precision(TP2, FN2, FP2, TN2)
#comparacion entre parámetros
if a1 > a2: #exactitud
print("El clasificador 1 es mejor que el clasificador 2 en términos de exactitud \n")
else:
print("El clasificador 2 es mejor que el clasificador 2 en términos de exactitud \n")
if s1 > s2: #sensibilidad
print("El clasificador 1 es mejor que el clasificador 2 en términos de sensibilidad \n")
else:
print("El clasificador 2 es mejor que el clasificador 2 en términos de sensibilidad \n")
if sp1 > sp2: #especificidad
print("El clasificador 1 es mejor que el clasificador 2 en términos de especificidad \n")
else:
print("El clasificador 2 es mejor que el clasificador 2 en términos de especificidad \n")
if p1 > p2: #precisión
print("El clasificador 1 es mejor que el clasificador 2 en términos de precisión \n")
else:
print("El clasificador 2 es mejor que el clasificador 2 en términos de precisión \n")
#Funciones de evaluación multiclase.
#función de regresion
def regresion_lineal(planta=0, grado=1, meses=False, n_mes=1, prueba=0.2, semilla=50):
#carga los datos directamente del repositorio
df = pd.read_csv("https://raw.githubusercontent.com/maggiesam/BEDU-DataScience/main/Datasets/dataframe-junto.csv")
#diferencia entre las plantas
lista=["maiz","frijol","trigo"]
producto = df[df["producto"] == lista[planta]]
#añade una columna de porcentaje de cosecha
producto["porcentaje"] = producto["Cosechada_ha"]*100/producto["Sembrada_ha"]
#activa el mes que queremos explorar
if meses:
producto = producto[producto["Mes"] == n_mes]
#elimina las columnas no relevantes para la regresion
nuevo = producto.drop(["producto", "ENTIDAD", "Año", "Mes", "Tipo_sequia", "Unnamed: 0", "perdida_ha", "Cosechada_ha"], axis=1)
nuevo = nuevo.reset_index(drop=True)
X = nuevo.drop("porcentaje",axis=1)
Y = nuevo["porcentaje"]
#selecciona los tamaños de entrenamiento y prueba
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = prueba, random_state=semilla)
#regresión lineal
if grado == 1:
print("función de regresion lineal de "+lista[planta])
lin_model = LinearRegression()
lin_model.fit(X_train, Y_train)
y_train_predict = lin_model.predict(X_train)
MSE = mean_squared_error(Y_train,y_train_predict)
print("Entrenamiento: MSE ="+str(MSE))
y_test_predict = lin_model.predict(X_test)
MSE = (mean_squared_error(Y_test, y_test_predict))
print("Pruebas: MSE ="+str(MSE))
df_predicciones = pd.DataFrame({'valor_real':Y_test, 'prediccion':y_test_predict})
df_predicciones = df_predicciones.reset_index(drop = True)
return df_predicciones
#regresión polinomica
if grado >= 2:
print("función de regresion polinomica de grado " + str(grado) + " de " + lista[planta])
poly_model = LinearRegression()
poly = PolynomialFeatures(degree=grado)
Xpolytrain = poly.fit_transform(X_train)
Xpolytest = poly.fit_transform(X_test)
poly_model.fit(Xpolytrain, Y_train)
y_train_predict = poly_model.predict(Xpolytrain)
MSE = mean_squared_error(Y_train,y_train_predict)
print("Entrenamiento: MSE ="+str(MSE))
y_test_predict = poly_model.predict(Xpolytest)
MSE = (mean_squared_error(Y_test, y_test_predict))
print("Pruebas: MSE ="+str(MSE))
df_predicciones = pd.DataFrame({'valor_real':Y_test, 'prediccion':y_test_predict})
df_predicciones = df_predicciones.reset_index(drop = True)
df_predicciones.head(10)
return df_predicciones
#Forecasting - Efrain
################################################################################
# skforecast #
# #
# This work by Joaquín Amat Rodrigo is licensed under a Creative Commons #
# Attribution 4.0 International License. #
################################################################################
# coding=utf-8
import typing
from typing import Union, Dict, List, Tuple
import warnings
import logging
import numpy as np
import pandas as pd
import sklearn
import tqdm
from sklearn.metrics import mean_squared_error
from sklearn.metrics import mean_absolute_error
#from sklearn.metrics import mean_absolute_percentage_error
logging.basicConfig(
format = '%(name)-10s %(levelname)-5s %(message)s',
level = logging.INFO,
)
################################################################################
# ForecasterAutoreg #
################################################################################
class ForecasterAutoreg():
'''
This class turns any regressor compatible with the scikit-learn API into a
recursive autoregressive (multi-step) forecaster.
Parameters
----------
regressor : regressor compatible with the scikit-learn API
An instance of a regressor compatible with the scikit-learn API.
lags : int, list, 1D np.array, range
Lags used as predictors. Index starts at 1, so lag 1 is equal to t-1.
`int`: include lags from 1 to `lags` (included).
`list` or `np.array`: include only lags present in `lags`.
Attributes
----------
regressor : regressor compatible with the scikit-learn API
An instance of a regressor compatible with the scikit-learn API.
lags : 1D np.array
Lags used as predictors.
max_lag : int
Maximum value of lag included in lags.
window_size: int
Size of the window needed to create the predictors. It is equal to
`max_lag`.
last_window : 1D np.ndarray
Last time window the forecaster has seen when trained. It stores the
values needed to calculate the lags used to predict the next `step`
after the training data.
included_exog : bool
If the forecaster has been trained using exogenous variable/s.
exog_type : type
Type used for the exogenous variable/s: pd.Series, pd.DataFrame or np.ndarray.
exog_shape : tuple
Shape of exog used in training.
in_sample_residuals: np.ndarray
Residuals of the model when predicting training data. Only stored up to
1000 values.
out_sample_residuals: np.ndarray
Residuals of the model when predicting non training data. Only stored
up to 1000 values.
fitted: Bool
Tag to identify if the estimator is fitted.
'''
def __init__(self, regressor, lags: Union[int, np.ndarray, list]) -> None:
self.regressor = regressor
self.last_window = None
self.included_exog = False
self.exog_type = None
self.exog_shape = None
self.in_sample_residuals = None
self.out_sample_residuals = None
self.fitted = False
if isinstance(lags, int) and lags < 1:
raise Exception('min value of lags allowed is 1')
if isinstance(lags, (list, range, np.ndarray)) and min(lags) < 1:
raise Exception('min value of lags allowed is 1')
if isinstance(lags, int):
self.lags = np.arange(lags) + 1
elif isinstance(lags, (list, range)):
self.lags = np.array(lags)
elif isinstance(lags, np.ndarray):
self.lags = lags
else:
raise Exception(
f"`lags` argument must be `int`, `1D np.ndarray`, `range` or `list`. "
f"Got {type(lags)}"
)
self.max_lag = max(self.lags)
self.window_size = self.max_lag
def __repr__(self) -> str:
'''
Information displayed when a ForecasterAutoreg object is printed.
'''
info = "=======================" \
+ "ForecasterAutoreg" \
+ "=======================" \
+ "\n" \
+ "Regressor: " + str(self.regressor) \
+ "\n" \
+ "Lags: " + str(self.lags) \
+ "\n" \
+ "Window size: " + str(self.window_size) \
+ "\n" \
+ "Exogenous variable: " + str(self.included_exog) + ', ' + str(self.exog_type) \
+ "\n" \
+ "Parameters: " + str(self.regressor.get_params())
return info
def create_lags(self, y: Union[np.ndarray, pd.Series]) -> Tuple[np.ndarray, np.ndarray]:
'''
Transforms a time series into a 2D array and a 1D array where each value
of `y` is associated with the lags that precede it.
Notice that the returned matrix X_data, contains the lag 1 in the
first column, the lag 2 in the second column and so on.
Parameters
----------
y : 1D np.ndarray, pd.Series
Training time series.
Returns
-------
X_data : 2D np.ndarray, shape (samples, len(self.lags))
2D array with the lag values (predictors).
y_data : 1D np.ndarray, shape (nº observaciones - max(seld.lags),)
Values of the time series related to each row of `X_data`.
'''
self._check_y(y=y)
y = self._preproces_y(y=y)
if self.max_lag > len(y):
raise Exception(
f"Maximum lag can't be higher than `y` length. "
f"Got maximum lag={self.max_lag} and `y` length={len(y)}."
)
n_splits = len(y) - self.max_lag
X_data = np.full(shape=(n_splits, self.max_lag), fill_value=np.nan, dtype=float)
y_data = np.full(shape=(n_splits, 1), fill_value=np.nan, dtype= float)
for i in range(n_splits):
X_index = np.arange(i, self.max_lag + i)
y_index = [self.max_lag + i]
X_data[i, :] = y[X_index]
y_data[i] = y[y_index]
X_data = X_data[:, -self.lags]
y_data = y_data.ravel()
return X_data, y_data
def create_train_X_y(self, y: Union[np.ndarray, pd.Series],
exog: Union[np.ndarray, pd.Series, pd.DataFrame]=None
) -> Tuple[np.array, np.array]:
'''
Create training matrices X, y
Parameters
----------
y : 1D np.ndarray, pd.Series
Training time series.
exog : np.ndarray, pd.Series, pd.DataFrame, default `None`
Exogenous variable/s included as predictor/s. Must have the same
number of observations as `y` and should be aligned so that y[i] is
regressed on exog[i].
Returns
-------
X_train : 2D np.ndarray, shape (len(y) - self.max_lag, len(self.lags))
2D array with the training values (predictors).
y_train : 1D np.ndarray, shape (len(y) - self.max_lag,)
Values (target) of the time series related to each row of `X_train`.
'''
self._check_y(y=y)
y = self._preproces_y(y=y)
if exog is not None:
self._check_exog(exog=exog)
exog = self._preproces_exog(exog=exog)
self.included_exog = True
self.exog_shape = exog.shape
if exog.shape[0] != len(y):
raise Exception(
f"`exog` must have same number of samples as `y`"
)
X_train, y_train = self.create_lags(y=y)
if exog is not None:
# The first `self.max_lag` positions have to be removed from exog
# since they are not in X_train.
X_train = np.column_stack((X_train, exog[self.max_lag:,]))
return X_train, y_train
def fit(self, y: Union[np.ndarray, pd.Series],
exog: Union[np.ndarray, pd.Series, pd.DataFrame]=None) -> None:
'''
Training ForecasterAutoreg
Parameters
----------
y : 1D np.ndarray, pd.Series
Training time series.
exog : np.ndarray, pd.Series, pd.DataFrame, default `None`
Exogenous variable/s included as predictor/s. Must have the same
number of observations as `y` and should be aligned so that y[i] is
regressed on exog[i].
Returns
-------
self : ForecasterAutoreg
Trained ForecasterAutoreg
'''
# Reset values in case the forecaster has already been fitted before.
self.included_exog = False
self.exog_type = None
self.exog_shape = None
self._check_y(y=y)
y = self._preproces_y(y=y)
if exog is not None:
self._check_exog(exog=exog)
self.exog_type = type(exog)
exog = self._preproces_exog(exog=exog)
self.included_exog = True
self.exog_shape = exog.shape
if exog.shape[0] != len(y):
raise Exception(
f"`exog` must have same number of samples as `y`"
)
X_train, y_train = self.create_train_X_y(y=y, exog=exog)
self.regressor.fit(X=X_train, y=y_train)
self.fitted = True
residuals = y_train - self.regressor.predict(X_train)
if len(residuals) > 1000:
# Only up to 1000 residuals are stored
residuals = np.random.choice(a=residuals, size=1000, replace=False)
self.in_sample_residuals = residuals
# The last time window of training data is stored so that lags needed as
# predictors in the first iteration of `predict()` can be calculated.
self.last_window = y_train[-self.max_lag:].copy()
def predict(self, steps: int, last_window: Union[np.ndarray, pd.Series]=None,
exog: Union[np.ndarray, pd.Series, pd.DataFrame]=None) -> np.ndarray:
'''
Iterative process in which, each prediction, is used as a predictor
for the next step.
Parameters
----------
steps : int
Number of future steps predicted.
last_window : 1D np.ndarray, pd.Series, shape (, max_lag), default `None`
Values of the series used to create the predictors (lags) need in the
first iteration of predictiont (t + 1).
If `last_window = None`, the values stored in` self.last_window` are
used to calculate the initial predictors, and the predictions start
right after training data.
exog : np.ndarray, pd.Series, pd.DataFrame, default `None`
Exogenous variable/s included as predictor/s.
Returns
-------
predictions : 1D np.array, shape (steps,)
Values predicted.
'''
if not self.fitted:
raise Exception(
'This Forecaster instance is not fitted yet. Call `fit` with appropriate arguments before using this it.'
)
if steps < 1:
raise Exception(
f"`steps` must be integer greater than 0. Got {steps}."
)
if exog is None and self.included_exog:
raise Exception(
f"Forecaster trained with exogenous variable/s. "
f"Same variable/s must be provided in `predict()`."
)
if exog is not None and not self.included_exog:
raise Exception(
f"Forecaster trained without exogenous variable/s. "
f"`exog` must be `None` in `predict()`."
)
if exog is not None:
self._check_exog(
exog=exog, ref_type = self.exog_type, ref_shape=self.exog_shape
)
exog = self._preproces_exog(exog=exog)
if exog.shape[0] < steps:
raise Exception(
f"`exog` must have at least as many values as `steps` predicted."
)
if last_window is not None:
self._check_last_window(last_window=last_window)
last_window = self._preproces_last_window(last_window=last_window)
if last_window.shape[0] < self.max_lag:
raise Exception(
f"`last_window` must have as many values as as needed to "
f"calculate the maximum lag ({self.max_lag})."
)
else:
last_window = self.last_window.copy()
predictions = np.full(shape=steps, fill_value=np.nan)
for i in range(steps):
X = last_window[-self.lags].reshape(1, -1)
if exog is None:
prediction = self.regressor.predict(X)
else:
prediction = self.regressor.predict(
np.column_stack((X, exog[i,].reshape(1, -1)))
)
predictions[i] = prediction.ravel()[0]
# Update `last_window` values. The first position is discarded and
# the new prediction is added at the end.
last_window = np.append(last_window[1:], prediction)
return predictions
def _estimate_boot_interval(self, steps: int,
last_window: Union[np.ndarray, pd.Series]=None,
exog: Union[np.ndarray, pd.Series, pd.DataFrame]=None,
interval: list=[5, 95], n_boot: int=500,
in_sample_residuals: bool=True) -> np.ndarray:
'''
Iterative process in which, each prediction, is used as a predictor
for the next step and bootstrapping is used to estimate prediction
intervals. This method only returns prediction intervals.
See predict_intervals() to calculate both, predictions and intervals.
Parameters
----------
steps : int
Number of future steps predicted.
last_window : 1D np.ndarray, pd.Series, shape (, max_lag), default `None`
Values of the series used to create the predictors (lags) need in the
first iteration of predictiont (t + 1).
If `last_window = None`, the values stored in` self.last_window` are
used to calculate the initial predictors, and the predictions start
right after training data.
exog : np.ndarray, pd.Series, pd.DataFrame, default `None`
Exogenous variable/s included as predictor/s.
n_boot: int, default `100`
Number of bootstrapping iterations used to estimate prediction
intervals.
interval: list, default `[5, 100]`
Confidence of the prediction interval estimated. Sequence of percentiles
to compute, which must be between 0 and 100 inclusive.
in_sample_residuals: bool, default `True`
If `True`, residuals from the training data are used as proxy of
prediction error to create prediction intervals. If `False`, out of
sample residuals are used. In the latter case, the user shoud have
calculated and stored the residuals within the forecaster (see
`set_out_sample_residuals()`).
Returns
-------
predicction_interval : np.array, shape (steps, 2)
Interval estimated for each prediction by bootstrapping.
Notes
-----
More information about prediction intervals in forecasting:
https://otexts.com/fpp2/prediction-intervals.html
Forecasting: Principles and Practice (2nd ed) Rob J Hyndman and
George Athanasopoulos.
'''
if steps < 1:
raise Exception(
f"`steps` must be integer greater than 0. Got {steps}."
)
if not in_sample_residuals and self.out_sample_residuals is None:
raise Exception(
('out_sample_residuals is empty. In order to estimate prediction '
'intervals using out of sample residuals, the user shoud have '
'calculated and stored the residuals within the forecaster (see'
'`set_out_sample_residuals()`.')
)
if exog is None and self.included_exog:
raise Exception(
f"Forecaster trained with exogenous variable/s. "
f"Same variable/s must be provided in `predict()`."
)
if exog is not None and not self.included_exog:
raise Exception(
f"Forecaster trained without exogenous variable/s. "
f"`exog` must be `None` in `predict()`."
)
if exog is not None:
self._check_exog(
exog=exog, ref_type = self.exog_type, ref_shape=self.exog_shape
)
exog = self._preproces_exog(exog=exog)
if exog.shape[0] < steps:
raise Exception(
f"`exog` must have at least as many values as `steps` predicted."
)
if last_window is not None:
self._check_last_window(last_window=last_window)
last_window = self._preproces_last_window(last_window=last_window)
if last_window.shape[0] < self.max_lag:
raise Exception(
f"`last_window` must have as many values as as needed to "
f"calculate the maximum lag ({self.max_lag})."
)
else:
last_window = self.last_window.copy()
boot_predictions = np.full(
shape = (steps, n_boot),
fill_value = np.nan,
dtype = float
)
for i in range(n_boot):
# In each bootstraping iteration the initial last_window and exog
# need to be restored.
last_window_boot = last_window.copy()
if exog is not None:
exog_boot = exog.copy()
else:
exog_boot = None
if in_sample_residuals:
residuals = self.in_sample_residuals
else:
residuals = self.out_sample_residuals
sample_residuals = np.random.choice(
a = residuals,
size = steps,
replace = True
)
for step in range(steps):
prediction = self.predict(
steps = 1,
last_window = last_window_boot,
exog = exog_boot
)
prediction_with_residual = prediction + sample_residuals[step]
boot_predictions[step, i] = prediction_with_residual
last_window_boot = np.append(
last_window_boot[1:],
prediction_with_residual
)
if exog is not None:
exog_boot = exog_boot[1:]
prediction_interval = np.percentile(boot_predictions, q=interval, axis=1)
prediction_interval = prediction_interval.transpose()
return prediction_interval
def predict_interval(self, steps: int, last_window: Union[np.ndarray, pd.Series]=None,
exog: Union[np.ndarray, pd.Series, pd.DataFrame]=None,
interval: list=[5, 95], n_boot: int=500,
in_sample_residuals: bool=True) -> np.ndarray:
'''
Iterative process in which, each prediction, is used as a predictor
for the next step and bootstrapping is used to estimate prediction
intervals. Both, predictions and intervals, are returned.
Parameters
----------
steps : int
Number of future steps predicted.
last_window : 1D np.ndarray, pd.Series, shape (, max_lag), default `None`
Values of the series used to create the predictors (lags) need in the
first iteration of predictiont (t + 1).
If `last_window = None`, the values stored in` self.last_window` are
used to calculate the initial predictors, and the predictions start
right after training data.
exog : np.ndarray, pd.Series, pd.DataFrame, default `None`
Exogenous variable/s included as predictor/s.
interval: list, default `[5, 100]`
Confidence of the prediction interval estimated. Sequence of percentiles
to compute, which must be between 0 and 100 inclusive.
n_boot: int, default `500`
Number of bootstrapping iterations used to estimate prediction
intervals.
in_sample_residuals: bool, default `True`
If `True`, residuals from the training data are used as proxy of
prediction error to create prediction intervals. If `False`, out of
sample residuals are used. In the latter case, the user shoud have
calculated and stored the residuals within the forecaster (see
`set_out_sample_residuals()`).
Returns
-------
predictions : np.array, shape (steps, 3)
Values predicted by the forecaster and their estimated interval.
Column 0 = predictions
Column 1 = lower bound interval
Column 2 = upper bound interval
Notes
-----
More information about prediction intervals in forecasting:
https://otexts.com/fpp2/prediction-intervals.html
Forecasting: Principles and Practice (2nd ed) Rob J Hyndman and
George Athanasopoulos.
'''
if steps < 1:
raise Exception(
f"`steps` must be integer greater than 0. Got {steps}."
)
if not in_sample_residuals and self.out_sample_residuals is None:
raise Exception(
('out_sample_residuals is empty. In order to estimate prediction '
'intervals using out of sample residuals, the user shoud have '
'calculated and stored the residuals within the forecaster (see'
'`set_out_sample_residuals()`.')
)
if exog is None and self.included_exog:
raise Exception(
f"Forecaster trained with exogenous variable/s. "
f"Same variable/s must be provided in `predict()`."
)
if exog is not None and not self.included_exog:
raise Exception(
f"Forecaster trained without exogenous variable/s. "
f"`exog` must be `None` in `predict()`."
)
if exog is not None:
self._check_exog(
exog=exog, ref_type = self.exog_type, ref_shape=self.exog_shape
)
exog = self._preproces_exog(exog=exog)
if exog.shape[0] < steps:
raise Exception(
f"`exog` must have as many values as `steps` predicted."
)
if last_window is not None:
self._check_last_window(last_window=last_window)
last_window = self._preproces_last_window(last_window=last_window)
if last_window.shape[0] < self.max_lag:
raise Exception(
f"`last_window` must have as many values as as needed to "
f"calculate the maximum lag ({self.max_lag})."
)
else:
last_window = self.last_window.copy()
# Since during predict() `last_window` and `exog` are modified, the
# originals are stored to be used later
last_window_original = last_window.copy()
if exog is not None:
exog_original = exog.copy()
else:
exog_original = exog
predictions = self.predict(
steps = steps,
last_window = last_window,
exog = exog
)
predictions_interval = self._estimate_boot_interval(
steps = steps,
last_window = last_window_original,
exog = exog_original,
interval = interval,
n_boot = n_boot,
in_sample_residuals = in_sample_residuals
)
predictions = np.column_stack((predictions, predictions_interval))
return predictions
def _check_y(self, y: Union[np.ndarray, pd.Series]) -> None:
'''
Raise Exception if `y` is not 1D `np.ndarray` or `pd.Series`.
Parameters
----------
y : np.ndarray, pd.Series
Time series values
'''
if not isinstance(y, (np.ndarray, pd.Series)):
raise Exception('`y` must be `1D np.ndarray` or `pd.Series`.')
elif isinstance(y, np.ndarray) and y.ndim != 1:
raise Exception(
f"`y` must be `1D np.ndarray` o `pd.Series`, "
f"got `np.ndarray` with {y.ndim} dimensions."
)
return
def _check_last_window(self, last_window: Union[np.ndarray, pd.Series]) -> None:
'''
Raise Exception if `last_window` is not 1D `np.ndarray` or `pd.Series`.
Parameters
----------
last_window : np.ndarray, pd.Series
Time series values
'''
if not isinstance(last_window, (np.ndarray, pd.Series)):
raise Exception('`last_window` must be `1D np.ndarray` or `pd.Series`.')
elif isinstance(last_window, np.ndarray) and last_window.ndim != 1:
raise Exception(
f"`last_window` must be `1D np.ndarray` o `pd.Series`, "
f"got `np.ndarray` with {last_window.ndim} dimensions."
)
return
def _check_exog(self, exog: Union[np.ndarray, pd.Series, pd.DataFrame],
ref_type: type=None, ref_shape: tuple=None) -> None:
'''
Raise Exception if `exog` is not `np.ndarray`, `pd.Series` or `pd.DataFrame`.
If `ref_shape` is provided, raise Exception if `ref_shape[1]` do not match
`exog.shape[1]` (number of columns).
Parameters
----------
exog : np.ndarray, pd.Series, pd.DataFrame
Exogenous variable/s included as predictor/s.
exog_type : type, default `None`
Type of reference for exog.
exog_shape : tuple, default `None`
Shape of reference for exog.
'''
if not isinstance(exog, (np.ndarray, pd.Series, pd.DataFrame)):
raise Exception('`exog` must be `np.ndarray`, `pd.Series` or `pd.DataFrame`.')
if isinstance(exog, np.ndarray) and exog.ndim > 2:
raise Exception(
f" If `exog` is `np.ndarray`, maximum allowed dim=2. "
f"Got {exog.ndim}."
)
if ref_type is not None:
if ref_type == pd.Series:
if isinstance(exog, pd.Series):
return
elif isinstance(exog, np.ndarray) and exog.ndim == 1:
return
elif isinstance(exog, np.ndarray) and exog.shape[1] == 1:
return
else:
raise Exception(
f"`exog` must be: `pd.Series`, `np.ndarray` with 1 dimension "
f"or `np.ndarray` with 1 column in the second dimension. "
f"Got `np.ndarray` with {exog.shape[1]} columns."
)
if ref_type == np.ndarray:
if exog.ndim == 1 and ref_shape[1] == 1:
return
elif exog.ndim == 1 and ref_shape[1] > 1:
raise Exception(
f"`exog` must have {ref_shape[1]} columns. "
f"Got `np.ndarray` with 1 dimension or `pd.Series`."
)
elif ref_shape[1] != exog.shape[1]:
raise Exception(
f"`exog` must have {ref_shape[1]} columns. "
f"Got `np.ndarray` with {exog.shape[1]} columns."
)
if ref_type == pd.DataFrame:
if ref_shape[1] != exog.shape[1]:
raise Exception(
f"`exog` must have {ref_shape[1]} columns. "
f"Got `pd.DataFrame` with {exog.shape[1]} columns."
)
return
def _preproces_y(self, y: Union[np.ndarray, pd.Series]) -> np.ndarray:
'''
Transforms `y` to 1D `np.ndarray` if it is `pd.Series`.
Parameters
----------
y :1D np.ndarray, pd.Series
Time series values
Returns
-------
y: 1D np.ndarray, shape(samples,)
'''
if isinstance(y, pd.Series):
return y.to_numpy(copy=True)
else:
return y
def _preproces_last_window(self, last_window: Union[np.ndarray, pd.Series]) -> np.ndarray:
'''
Transforms `last_window` to 1D `np.ndarray` if it is `pd.Series`.
Parameters
----------
last_window :1D np.ndarray, pd.Series
Time series values